コード例 #1
1
        /// <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 ExecutePreValidateCaseUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            string s = "this works again";
        }
コード例 #2
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 ExecutePostAccountCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

            // 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 parmameters.
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "account")
                {
                    if (context.MessageName.ToUpper() == "CREATE")
                    {

                        AccountCreateFollowUp accountCreateFollowUp = new AccountCreateFollowUp();
                        accountCreateFollowUp.CreateAccountTask(service, entity);

                    }
                }
            }
        }
コード例 #3
0
        protected void Execute(LocalPluginContext Context)
        {
            int triggerEvent = Context.PreImage.Contains("cel_triggerevent") && Context.PreImage.GetAttributeValue<OptionSetValue>("cel_triggerevent").Value == 1 ? 1 : 0;

            var remainingAutoNumberList = Context.OrganizationDataContext.CreateQuery("cel_autonumber")
                                                                         .Where(s => s.GetAttributeValue<string>("cel_entityname").Equals(Context.PreImage.GetAttributeValue<string>("cel_entityname")))
                                                                         .Select(s => new { Id = s.GetAttributeValue<Guid>("cel_autonumberid"), TriggerEvent = s.Contains("cel_triggerevent") ? s.GetAttributeValue<OptionSetValue>("cel_triggerevent").Value : 0  })
                                                                         .ToList();

            if (remainingAutoNumberList.Any(s => s.TriggerEvent == triggerEvent ))  // If there are still other autonumber records on this entity, then do nothing.
            {
                return;
            }

            // Find and remove the registerd plugin
            string pluginName = String.Format(CreateAutoNumber.PLUGIN_NAME, Context.PreImage.GetAttributeValue<string>("cel_entityname"));
            if (Context.PreImage.Contains("cel_triggerevent") && Context.PreImage.GetAttributeValue<OptionSetValue>("cel_triggerevent").Value == 1)
            {
                pluginName += " Update";
            }

            var pluginStepList = Context.OrganizationDataContext.CreateQuery("sdkmessageprocessingstep")
                                                                .Where(s => s.GetAttributeValue<string>("name").Equals(pluginName))
                                                                .Select(s => s.GetAttributeValue<Guid>("sdkmessageprocessingstepid"))
                                                                .ToList();

            if (!pluginStepList.Any())  // Plugin is already deleted, nothing to do here.
            {
                return;
            }

            // Delete plugin step
            Context.OrganizationService.Delete("sdkmessageprocessingstep", pluginStepList.First());
        }
コード例 #4
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 ExecutePreValidateCaseDelete(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.
        }
コード例 #5
0
 public void ExecuteWebResourcePreRetrieveMultiple(LocalPluginContext context)
 {
     var query = context.PluginExecutionContext.InputParameters["Query"] as QueryExpression;
     if (query != null && !query.ColumnSet.AllColumns &&
         !query.ColumnSet.Columns.Contains("description"))
     {
         query.ColumnSet.Columns.Add("description");
     }
 }
コード例 #6
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 ExecutePostAttachmentSearchUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

            

            Guid searchID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;


            var searchEntity = service.Retrieve("new_attachmentsearch", searchID, set);

            if (context.Depth > 1)
            {
                searchEntity["new_results"] = "This created a loop!";
                return;
            }
            else
            {
                //acquires the keyword

                string keywordToLook = (string)searchEntity["new_searchword"];
                var countPerPage = 20;
                    //(int)searchEntity["new_countperpage"];
                var pagesCount = (int)searchEntity["new_numberofpages"];
                var lastPage = 1;
                var firstPage = 1;

                //creates the critieria of the query
                ColumnSet NoteSet = new ColumnSet(new string[] { "filename", "documentbody", "subject" });
                QueryExpression Notes = new QueryExpression { EntityName = "annotation", ColumnSet = NoteSet };
                Notes.PageInfo = new PagingInfo();
                Notes.PageInfo.Count = countPerPage;
                Notes.Criteria.AddCondition("documentbody", ConditionOperator.NotNull);

                //retrieve the Notes that fulfill the condition
                searchEntity["new_results"] = "";

                for (int i = firstPage; i < lastPage; i++)
                {
                      var NotesRetrieved = fillCollection(Notes, pagesCount, service);
                      searchForKeyWord(keywordToLook, searchEntity, NotesRetrieved, pagesCount);
                }

                //EntityCollection fullListOfEntities = new EntityCollection();
                // searchEntity["new_results"] += "\r\n" + keywordToLook;
            }
            service.Update(searchEntity);
        }
コード例 #7
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 ExecutePreValidateContactRetrieve(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                string s = "ds";
                throw new ArgumentNullException("localContext");

            }

            // TODO: Implement your custom Plug-in business logic.
        }
コード例 #8
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 ExecutePricingTypeUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid quoteProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var quote = service.Retrieve("quote", quoteProductID, set);


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

                //First I get the base values that I need for the calculations

                var pricingType = (OptionSetValue)quote["new_pricingtype"];

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "quoteid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(quoteProductID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "quotedetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection quotedetails = service.RetrieveMultiple(query);

                foreach (var detail in quotedetails.Entities)
                {
                    detail["new_pricingtype"] = new OptionSetValue(pricingType.Value);
                    service.Update(detail);
                }


                service.Update(quote);

            }
        }
コード例 #9
0
 protected void ExecutePreCreate(LocalPluginContext localContext)
 {
     if (localContext == null)
     {
         throw new ArgumentNullException("localContext");
     }
     IPluginExecutionContext context = localContext.PluginExecutionContext;
     Entity targetEntity = (Entity)context.InputParameters["Target"];
     IncidentServiceEventCalc calc = new IncidentServiceEventCalc(localContext.OrganizationService, true);
     new_incidentservice new_servicecostTarget = targetEntity.ToEntity<Xrm.new_incidentservice>();
     calc.CalcIncidentService(new_servicecostTarget, null);
 }
コード例 #10
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 ExecuteGetSiteMap(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            Entity output = new Entity("webresource");

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

            // Exract the search criteria 
            QueryBase query = (QueryBase)localContext.PluginExecutionContext.InputParameters["Query"];
            Type queryType = query.GetType();
            if (queryType == typeof(QueryExpression))
            {
                trace.Trace("Found QueryExpression");
                // Get condition
                QueryExpression queryExpression = (QueryExpression)query;
                if (queryExpression.EntityName != "webresource")
                    return;

                if (queryExpression.Criteria == null || queryExpression.Criteria.Conditions.Count != 1 || queryExpression.Criteria.Conditions[0].AttributeName != "name")
                    return;

                string webresourceName = (string)queryExpression.Criteria.Conditions[0].Values[0];
                if ((webresourceName.Length > SiteMapResourceName.Length + 3) && webresourceName.StartsWith(SiteMapResourceName) && webresourceName.EndsWith(".js"))
                {

                    string lcid = webresourceName.Substring(16);
                    lcid = lcid.Substring(0, lcid.Length - 3);
                    trace.Trace("LCID={0}",lcid);
                    var outputCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"];
                    SiteMapLoader siteMap = new SiteMapLoader(int.Parse(lcid));
                    StringWriter json = new StringWriter();

                    siteMap.ParseSiteMapToJson(service, trace, json);

                    var scriptBytes = System.Text.Encoding.UTF8.GetBytes(json.ToString());
                    trace.Trace("Parsed Sit Map OK");

                    output["name"] = webresourceName;
                    output["content"] = System.Convert.ToBase64String(scriptBytes);
                    output["webresourcetype"] = new OptionSetValue(3);
                    outputCollection.Entities.Clear();
                    outputCollection.Entities.Add(output);
                }
            }
        }
コード例 #11
0
 public void ExecuteWebResourcePostRetrieveMultiple(LocalPluginContext context)
 {
     var query = (QueryBase)context.PluginExecutionContext.InputParameters["Query"] as QueryExpression;
     if (query != null)
     {
         var entities = context.PluginExecutionContext.OutputParameters["BusinessEntityCollection"] as EntityCollection;
         foreach(var entity in entities.Entities){
             var description = entity.GetAttributeValue<string>("description");
             if (description != null && description.StartsWith("proxy:"))
             {
                 ReplaceContent(entity, description, context.OrganizationService);
             }
         }
     }
 }
コード例 #12
0
        protected void ExecutePreUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
                throw new ArgumentNullException("localContext");

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            Entity targetEntity, preEntity;
            targetEntity = (Entity)context.InputParameters["Target"];
            preEntity = (Entity)context.PreEntityImages[preImageAlias];
            IncidentServiceEventCalc calc = new IncidentServiceEventCalc(localContext.OrganizationService, false);
            var new_servicecostTarget = targetEntity.ToEntity<Xrm.new_incidentservice>();

            new_incidentservice new_servicecostImage = preEntity.ToEntity<Xrm.new_incidentservice>();
            calc.CalcIncidentService(new_servicecostTarget, new_servicecostImage);
        }
コード例 #13
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 ExecutePreValidateContactUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.
            var context = localContext.PluginExecutionContext;
            if (context.InputParameters.Contains(targetEntityAlias) && context.InputParameters[targetEntityAlias] is Entity)
            {
                var target = context.InputParameters[targetEntityAlias] as Entity;

                target["firstname"] = target["firstname"].ToString().RemoveSpaces();
            }
        }
コード例 #14
0
ファイル: Plugin.cs プロジェクト: srgl/webresourceproxy
        public void Execute(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            LocalPluginContext localContext = new LocalPluginContext(serviceProvider);

            localContext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", ChildClassName));

            try
            {
                Action<LocalPluginContext> entityAction =
                    (from a in RegisteredEvents
                     where (
                     a.Item1 == localContext.PluginExecutionContext.Stage &&
                     a.Item2 == localContext.PluginExecutionContext.MessageName &&
                     (string.IsNullOrWhiteSpace(a.Item3) || a.Item3 == localContext.PluginExecutionContext.PrimaryEntityName))
                     select a.Item4).FirstOrDefault();

                if (entityAction != null)
                {
                    localContext.Trace(string.Format(
                        CultureInfo.InvariantCulture,
                        "{0} is firing for Entity: {1}, Message: {2}",
                        ChildClassName,
                        localContext.PluginExecutionContext.PrimaryEntityName,
                        localContext.PluginExecutionContext.MessageName));

                    entityAction.Invoke(localContext);
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                localContext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e));

                // Handle the exception.
                throw;
            }
            finally
            {
                localContext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", ChildClassName));
            }
        }
コード例 #15
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 ExecutePricingOrderCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

            Guid quoteDetailID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var orderDetail = service.Retrieve("salesorderdetail", quoteDetailID, set);
            const decimal minimumValue = 0;
            const decimal minimumRatio = 1;

            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var priceperunit = (Money)orderDetail["priceperunit"];
                orderDetail["new_specificdiscountpercentage"] = minimumValue;
                orderDetail["new_ratio"] = minimumRatio;
                orderDetail["new_grossannualincome"] = new Money(minimumValue);
                orderDetail["new_gaixratio"] = new Money(minimumValue);
                orderDetail["new_recommendedvalue"] = priceperunit;
                //orderDetail["new_fixedpriceplusratio"] = priceperunit;

                //This sets the current pricing type of the quote product, to the default pricing type of the quote
                var parentOrder = (EntityReference)orderDetail["salesorderid"];

                var quote = service.Retrieve(parentOrder.LogicalName, parentOrder.Id, new ColumnSet(true));

                var pricingType = (OptionSetValue)quote["new_pricingtype"];

                orderDetail["new_pricingtype"] = new OptionSetValue(pricingType.Value);

                service.Update(orderDetail);
            }
        }
コード例 #16
0
ファイル: PostQuoteUpdate.cs プロジェクト: borisov90/Projects
        /// <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 ExecutePostQuoteUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            //IPluginExecutionContext context = localContext.PluginExecutionContext;
            //IOrganizationService service = localContext.OrganizationService;
            //Guid quoteProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            //var serviceContext = new OrganizationServiceContext(service);
            //ColumnSet set = new ColumnSet();
            //set.AllColumns = true;
            //var quote = service.Retrieve("quote", quoteProductID, set);

            //if (context.Depth > 5)
            //{
            //    return;
            //}
            //else
            //{
            //    var salesorderType = (OptionSetValue)quote["new_createinvoice"];

            //    if (salesorderType.Value == 1)
            //    {
            //        var salesorder = new Entity("salesorder");
            //        salesorder["name"] = quote["name"] + " Invoice Order for the Prepayment";
            //        service.Create(salesorder);
            //    }
            //    else if(salesorderType.Value == 2)
            //    {
            //        var salesorder = new Entity("salesorder");
            //        salesorder["name"] = quote["name"] + " Invoice Order";
            //        service.Create(salesorder);
            //    }
               
            //}
        }
コード例 #17
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 ExecutePreAccountUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            // TODO: Implement your custom Plug-in business logic.
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

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

                var query = new QueryExpression("account");

                var columnNames = new[] { "fullname", "accountid" };

                if (entity.LogicalName == "account")
                {

                    string entityDes = "Test plugin - Test 06302015";
                    try
                    {
                        if (entity.Attributes.Contains("description"))
                        {
                            entity.Attributes["description"] = entityDes;
                        }
                        else
                        {
                            entity.Attributes.Add("description", entityDes);
                        }
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("Issues with the plugin", ex);
                    }
                }
            }
        }
コード例 #18
0
ファイル: RCIPlugin.cs プロジェクト: tc-ca/TSIS-2.0
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (!(localContext.PluginExecutionContext.InputParameters["Target"] is Entity target))
            {
                return;
            }



            //Traveler Entity being updated
            var traveler = target.ToEntity <ppp_Traveller>();



            //Don't continue if fields are empty
            if (traveler.ppp_AirCarrierRepresentative == null && traveler.ppp_RepresentativePhoneNumber == null)
            {
                return;
            }

            if (localContext.PluginExecutionContext.MessageName == "Update")
            {
                traveler = GetTraveler(localContext, traveler.Id);
            }


            //New RepCallInfo to be added to the Traveler
            var callInfo = new ppp_repcallinfo();

            //Add info from Traveler to new RepCallInfo
            callInfo.ppp_Name        = traveler.ppp_AirCarrierRepresentative;
            callInfo.ppp_PhoneNumber = traveler.ppp_RepresentativePhoneNumber;
            callInfo.ppp_CallTime    = DateTime.Now;
            callInfo.ppp_Traveller   = traveler.ToEntityReference(); //Create the reference

            //Create the repCallInfo in the DB
            localContext.OrganizationService.Create(callInfo);
        }
コード例 #19
0
ファイル: AutoNumbering.cs プロジェクト: sri1981/ElitePlugin
        protected void AutoNameCoverOnCreate(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            if (target == null)
            {
                throw new InvalidPluginExecutionException("Invalid plug-in registration, expecting 'Target' input parameter.");
            }

            var riskRef = target.GetAttributeValue <EntityReference>("new_riskid");

            if (riskRef == null)
            {
                throw new InvalidPluginExecutionException("Cover section does not contain risk object.");
            }

            var basicCoverRef = target.GetAttributeValue <EntityReference>("new_basiccover");

            if (basicCoverRef == null)
            {
                throw new InvalidPluginExecutionException("Cover section does not contain basic cover section.");
            }

            var risk       = context.OrganizationService.Retrieve(riskRef);
            var basicCover = context.OrganizationService.Retrieve(basicCoverRef);

            var riskName       = risk.GetAttributeValue <string>("new_name");
            var basicCoverName = basicCover.GetAttributeValue <string>("new_name");

            var coverName = "{0} - {1}".FormatWith(riskName, basicCoverName);

            if (coverName.Length > 150)
            {
                coverName = coverName.Substring(0, 150);
            }

            target["new_name"] = coverName;
        }
コード例 #20
0
ファイル: AutoNumbering.cs プロジェクト: sri1981/ElitePlugin
        protected void AutoNameRiskOnCreate(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            if (target == null)
            {
                throw new InvalidPluginExecutionException("Invalid plug-in registration, expecting 'Target' input parameter.");
            }

            var productRef = target.GetAttributeValue <EntityReference>("new_productid");

            if (productRef == null)
            {
                throw new InvalidPluginExecutionException("Risk does not contain product.");
            }

            var riskSubClassRef = target.GetAttributeValue <EntityReference>("new_secondlevelriskclassid");

            if (riskSubClassRef == null)
            {
                throw new InvalidPluginExecutionException("Risk does not contain risk subclass.");
            }

            var product      = context.OrganizationService.Retrieve(productRef);
            var riskSubClass = context.OrganizationService.Retrieve(riskSubClassRef);

            var productName  = product.GetAttributeValue <string>("new_name");
            var subClassName = riskSubClass.GetAttributeValue <string>("new_name");

            var riskName = "{0} - {1}".FormatWith(productName, subClassName);

            if (riskName.Length > 150)
            {
                riskName = riskName.Substring(0, 150);
            }

            target["new_name"] = riskName;
        }
コード例 #21
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 ExecutePreValidateVehicleAdjustmentVarianceEntryDelete(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            ITracingService         trace   = localContext.TracingService;
            EntityReference         vehicleAdjusmentVarianceEntryEntity = (EntityReference)context.InputParameters["Target"];
            string message = context.MessageName;

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

            try
            {
                EntityCollection vehicleAdjustmentVarianceEntryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_vehicleadjustmentvarianceentry", "gsc_sls_vehicleadjustmentvarianceentryid", vehicleAdjusmentVarianceEntryEntity.Id, service,
                                                                                                                 null, OrderType.Ascending, new[] { "gsc_adjustmentvariancestatus" });

                VehicleAdjustmentVarianceEntryHandler vehicleAdjustmentVarianceEntryHandler = new VehicleAdjustmentVarianceEntryHandler(service, trace);
                vehicleAdjustmentVarianceEntryHandler.AdjustInventoryOnUnpostedDelete(vehicleAdjustmentVarianceEntryRecords.Entities[0]);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Unable to delete already posted Vehicle Adjustment/Variance Entry"))
                {
                    throw new InvalidPluginExecutionException("Unable to delete already posted Vehicle Adjustment/Variance Entry");
                }
                else
                {
                    throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace));
                }
            }
        }
コード例 #22
0
        public void ExecutePluginLogic(IServiceProvider serviceProvider)
        {
            // Use a 'using' statement to dispose of the service context properly
            // To use a specific early bound entity replace the 'Entity' below with the appropriate class type
            var tracingservice = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            using (var localContext = new LocalPluginContext <Entity>(serviceProvider))
            {
                IOrganizationService service = localContext.OrganizationService;
                tracingservice.Trace("Tracing: ExecutePluginLogic");

                try
                {
                    tracingservice.Trace("Tracing ExecutePluginLogic : Try");
                    XRMController controller = new XRMController(service);

                    if (controller.IsMCRActive() == true)
                    {
                        journalController jcontrol = new journalController(service);
                        //gets the plugin target image which only contains updated or filled in fields.
                        Entity       phonecall = localContext.TargetEntity;
                        JournalEntry journal   = CreateJournalEntry(service, phonecall);
                        tracingservice.Trace("ExecutePluginLogic : " + journal.ToString());
                        jcontrol.WriteJournalEntry(journal);
                        bool success = controller.logJournalWrite(journal);
                    }
                    tracingservice.Trace("Tracing ExecutePluginLogic : End");
                }
                catch (Exception e)
                {
                    XRMController controller = new XRMController(service);
                    bool          success    = controller.logJournalWrite(e.Message + e.StackTrace + sw.ToString());
                    tracingservice.Trace(e.ToString());
                    localContext.Trace(e.StackTrace);
                    localContext.Trace(e.Message);
                }
            }
        }
コード例 #23
0
 private void AssociateProcedure(LocalPluginContext localContext)
 {
     try
     {
         IPluginExecutionContext context        = localContext.PluginExecutionContext;
         ITracingService         tracingService = localContext.TracingService;
         IOrganizationService    service        = localContext.OrganizationService;
         tracingService.Trace("Procedure association");
         if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
         {
             Entity agreementBooking = context.InputParameters["Target"] as Entity;
             if (agreementBooking.GetAttributeValue <EntityReference>("msdyn_workorder") != null)
             {
                 tracingService.Trace("Retrieveing the Booking setup");
                 Entity agreementbookingrecord = service.Retrieve(agreementBooking.LogicalName, agreementBooking.Id, new ColumnSet("msdyn_bookingsetup", "msdyn_workorder"));
                 Entity agreementbookingSetUp  = service.Retrieve(agreementbookingrecord.GetAttributeValue <EntityReference>("msdyn_bookingsetup").LogicalName, agreementbookingrecord.GetAttributeValue <EntityReference>("msdyn_bookingsetup").Id, new ColumnSet("smp_procedureid"));
                 if (agreementbookingSetUp.Attributes.Contains("smp_procedureid"))
                 {
                     try
                     {
                         tracingService.Trace(" Creating new association");
                         EntityReference procedure = (EntityReference)agreementbookingSetUp.Attributes["smp_procedureid"];
                         this.UpdateProcedureTOWOrkorder(service, agreementBooking.GetAttributeValue <EntityReference>("msdyn_workorder").Id, procedure);
                         tracingService.Trace(" End association");
                     }
                     catch (Exception ex)
                     {
                         tracingService.Trace(" Error in association:" + ex.Message);
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
コード例 #24
0
        /// <summary>
        /// Main entry point for he business logic that the plug-in is to execute.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            Entity  preEntity   = (Entity)context.PreEntityImages["contactPreImage"];
            Contact precontact  = preEntity.ToEntity <Contact>();
            Entity  postEntity  = (Entity)context.PostEntityImages["contactPostImage"];
            Contact postContact = postEntity.ToEntity <Contact>();

            if (precontact.di_IntialInvesmentFinal != postContact.di_IntialInvesmentFinal || precontact.di_interest_rate != postContact.di_interest_rate || precontact.di_InvestmentPeriod != postContact.di_InvestmentPeriod)
            {
                Entity        entity        = GetGlobalTemplate("Changes", service);
                Email         email         = new Email();
                ActivityParty activityParty = new ActivityParty();
                email.LogicalName = "email";
                email.Subject     = GetDataFromXml("match", entity.Attributes["subject"].ToString());
                email.Subject     = email.Subject.ToString().Replace("[subject]", "Changes Noticed on your account");
                email.Description = GetDataFromXml("match", entity.Attributes["body"].ToString());
                string urlToReplace =
                    "<html><body><table border=1>" +
                    "<tr><th>Field</th><th>Before</th><th>After</th>" +
                    "</tr><tr><td>Initial Investment</td><td>" + Math.Round(precontact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_IntialInvesmentFinal.GetValueOrDefault(0), 2) +
                    "</td></tr><tr><td>Interest Rate</td><td>" + Math.Round(precontact.di_interest_rate.GetValueOrDefault(0), 2) + "</td><td>" + Math.Round(postContact.di_interest_rate.GetValueOrDefault(0), 2) +
                    "</td></tr><tr><td>Investment Period</td><td>" + precontact.di_InvestmentPeriod + "</td><td>" + postContact.di_InvestmentPeriod + "</td></tr>" +
                    "</table></body></html>";
                email.Description       = email.Description.ToString().Replace("[fullname]", postContact.FullName);
                email.Description       = email.Description.ToString().Replace("[table]", urlToReplace);
                email.From              = CreateActivityPartyList(postContact.OwnerId);
                email.To                = CreateActivityPartyList(new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value));
                email.RegardingObjectId = (new EntityReference(Contact.EntityLogicalName, postContact.ContactId.Value));
                Guid             emailCreated = service.Create(email);
                SendEmailRequest req          = new SendEmailRequest();
                req.EmailId       = emailCreated;
                req.TrackingToken = string.Empty;
                req.IssueSend     = true;
                SendEmailResponse res = (SendEmailResponse)service.Execute(req);
            }
        }
コード例 #25
0
        protected void FieldMappingOnUpdate(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            string entityName = null;

            if (target.Contains("new_destinationentityschemaname"))
            {
                entityName = target.GetAttributeValue <string>("new_destinationentityschemaname").ToLowerInvariant();
                target["new_destinationentityschemaname"] = entityName; // to ensure it's lowercase in result
            }
            else if (context.PreImage.Contains("new_destinationentityschemaname"))
            {
                entityName = context.PreImage.GetAttributeValue <string>("new_destinationentityschemaname");
            }
            else
            {
                throw new InvalidPluginExecutionException("'new_destinationentityschemaname' must not be empty.");
            }

            string fieldName = null;

            if (target.Contains("new_destinationfield"))
            {
                fieldName = target.GetAttributeValue <string>("new_destinationfield").ToLowerInvariant();
                target["new_destinationfield"] = fieldName;
            }
            else if (context.PreImage.Contains("new_destinationfield"))
            {
                fieldName = context.PreImage.GetAttributeValue <string>("new_destinationfield");
            }
            else
            {
                throw new InvalidPluginExecutionException("'new_destinationfield' must not be empty.");
            }

            target["new_name"] = CreateEntityName(context.OrganizationService, entityName, fieldName);
        }
コード例 #26
0
ファイル: Account.cs プロジェクト: jbaarssen/azuread-b2b
        /// <summary>
        /// Main entry point for he business logic that the plug-in is to execute.
        /// </summary>
        /// <param name="localContext">The <see cref="PluginBase.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 override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("localContext");
            }

            var context = localContext.PluginExecutionContext;

            // Obtain the target entity from the input parameters
            var entity = GlobalHelper.RetrieveEntity(context);

            // Verify that the target entity represents an entity type you are expecting
            if (entity.LogicalName != "account")
            {
                return;
            }

            var preImageEntity  = GlobalHelper.RetrievePreImageEntity(context, "PreImage");
            var postImageEntity = GlobalHelper.RetrievePostImageEntity(context, "PostImage");

            var pluginStage = GlobalHelper.GetPluginStage(localContext);

            localContext.Trace($"pluginStage: '{pluginStage}'");
            switch (pluginStage)
            {
            case PluginStage.PostOperationCreate:
                AccountPluginContextHelper.CreateGroup(localContext.OrganizationService,
                                                       localContext.TracingService, entity, postImageEntity);
                break;

            case PluginStage.PreOperationUpdate:
                break;

            case PluginStage.PostOperationUpdate:
                break;
            }
        }
コード例 #27
0
        public void Execute(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new InvalidPluginExecutionException("serviceProvider");
            }
            //IPluginExecutionContext context = (IPluginExecutionContext)
            //serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Construct the local plug-in context.
            LocalPluginContext localcontext = new LocalPluginContext(serviceProvider, RunAsSystem);

            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));

            try
            {
                // Invoke the custom implementation
                ExecuteCrmPlugin(localcontext);
                // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
                // guard against multiple executions.
                return;
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));

                // Handle the exception.
                throw new InvalidPluginExecutionException("OrganizationServiceFault", e);
            }
            catch (InvalidPluginExecutionException e)
            {
                throw e;
            }
            finally
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
            }
        }
コード例 #28
0
        protected void TemplateColumnOnCreate(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            var bxTemplateRef = target.GetAttributeValue <EntityReference>("new_bordereauxtemplate");

            if (bxTemplateRef == null)
            {
                throw new InvalidPluginExecutionException("Bordereau template is empty.");
            }

            var valueType = target.GetAttributeValue <OptionSetValue>("new_valuetype");

            if (valueType == null || valueType.ToEnum <ColumnValueType>() == ColumnValueType.ColumnMapping)
            {
                // set correct column number based on column label, if number is null
                var columnLabel  = target.GetAttributeValue <string>("new_columnlabel");
                var columnNumber = target.GetAttributeValue <int?>("new_columnnumber");
                if (columnNumber == null && !string.IsNullOrEmpty(columnLabel))
                {
                    target["new_columnnumber"] = Utils.LettersToNumber(columnLabel);
                }
            }
            else
            {
                target["new_columnnumber"] = null;
                target["new_columnlabel"]  = null;
            }

            var bxTemplate = context.OrganizationService.Retrieve(bxTemplateRef);
            var template   = new BordereauTemplate(context.OrganizationService, context.TracingService, bxTemplate);

            var numberOfColumns = template.TemplateColumns.Count();

            var name = "{0} - {1:000}".FormatWith(bxTemplate.GetAttributeValue <string>("new_name"), numberOfColumns + 1);

            target["new_name"] = name;
        }
コード例 #29
0
        private void RetriveMultiple(LocalPluginContext localcontext)
        {
            var query = (QueryBase)localcontext
                        .PluginExecutionContext
                        .InputParameters["Query"];

            if (query == null)
            {
                return;
            }

            // Get the flight number query

            var expression = query as QueryExpression;
            var filter     = expression.Criteria.Conditions
                             .Where(c => c.AttributeName == "sf365_name")
                             .FirstOrDefault();
            var flightnumber = filter?.Values[0].ToString();
            var data         = GetFlightData(null, flightnumber);

            localcontext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"] =
                new EntityCollection(data);
        }
コード例 #30
0
ファイル: PostPriceListCreate.cs プロジェクト: weedkiller/dms
        /// <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 ExecutePostPriceListCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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


            try
            {
                PriceListHandler priceListHandler = new PriceListHandler(service, trace);
                priceListHandler.ValidateGlobal(entity);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.ToString());
            }
        }
コード例 #31
0
ファイル: VendorIntegration.cs プロジェクト: Voingod/DevFiles
        protected void HandleUpdateBankAccount(LocalPluginContext context)
        {
            var preImage = context.PluginExecutionContext.PreEntityImages["PreImage"] as Entity;
            var target   = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            if (preImage.Contains("uds_integratedwithcode") &&
                preImage.GetAttributeValue <OptionSetValue>("uds_integratedwithcode").Value == IntegratedSystemCode.Basware.GetHashCode())
            {
                if (target.Contains("uds_name") ||
                    target.Contains("uds_operatorid") ||
                    target.Contains("uds_personid") ||
                    target.Contains("uds_organizationid") ||
                    (target.Contains("statecode") &&
                     target.GetAttributeValue <OptionSetValue>("statecode").Value !=
                     preImage.GetAttributeValue <OptionSetValue>("statecode").Value))
                {
                    new BaswareExchangeService(context.OrganizationService)
                    .CreateBankAccountUpdatingLog(preImage,
                                                  target,
                                                  context.PluginExecutionContext.InitiatingUserId);
                }
            }
        }
コード例 #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 ExecutePrePurchaseOrderDetailCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            try
            {
                VehiclePurchaseOrderDetailsHandler vpoDetailsHandler = new VehiclePurchaseOrderDetailsHandler(service, trace);
                vpoDetailsHandler.RestrictMultipleCreate(vpoDetails);
            }

            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #33
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 ExecutePrePriceListCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            try
            {
                PriceListHandler priceListItemHandler = new PriceListHandler(service, trace);
                priceListItemHandler.CheckIfThereIsExistingDefaultPriceList(priceList);
            }

            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #34
0
        /// <summary>
        /// Principal method
        /// </summary>
        /// <param name="localContext"> Contexto de execução. </param>

        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("Context not found!");
            }
            ;

            //Language Code
            int languageCode = (int)localContext.PluginExecutionContext.InputParameters["LanguageCode"];
            //Record Id
            string recordId = (string)localContext.PluginExecutionContext.InputParameters["RecordId"];
            //Record Logical Name
            string recordLogicalName = (string)localContext.PluginExecutionContext.InputParameters["RecordLogicalName"];
            //One To Many Relationships
            string oneToManyRelationships = (string)localContext.PluginExecutionContext.InputParameters["OneToManyRelationships"];
            //Many to Many Relationships
            string manyToManyRelationships = (string)localContext.PluginExecutionContext.InputParameters["ManyToManyRelationships"];

            var DAO = new DynamicsDAO(localContext.OrganizationService, localContext.OrganizationServiceAdmin, new EntityReference(recordLogicalName, new Guid(recordId)), languageCode);

            localContext.PluginExecutionContext.OutputParameters["Relationships"] = DAO.RetrieveRelationships(oneToManyRelationships, manyToManyRelationships).ToJSON();
        }
コード例 #35
0
ファイル: PostIDRequestCreate.cs プロジェクト: weedkiller/dms
        /// <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 ExecutePostIDRequestCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            try
            {
                IDRequestHandler requestHandler = new IDRequestHandler(service, trace);
                requestHandler.GenerateName(requestEntity);
            }

            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #36
0
ファイル: AutoNumbering.cs プロジェクト: sri1981/ElitePlugin
        protected void AutoNumberPolicyVersion(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            if (target == null)
            {
                throw new InvalidPluginExecutionException("Invalid plug-in registration, expecting 'Target' input parameter.");
            }

            var policyFolderRef = target.GetAttributeValue <EntityReference>("new_policy");

            if (policyFolderRef == null)
            {
                return;
            }

            var policyFolderEntity = context.OrganizationService.Retrieve(policyFolderRef);
            var policyFolder       = new Policy(context.OrganizationService, context.TracingService, policyFolderEntity);

            var name = "{0}{1:D2}".FormatWith(policyFolderEntity.GetAttributeValue <string>("new_name"), policyFolder.Versions.Count() + 1);

            target["new_name"] = name;
        }
コード例 #37
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 ExecutePostPriceListItemCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            string message = context.MessageName;
            string error   = "";

            try
            {
                PriceListItemHandler priceListItemHandler = new PriceListItemHandler(service, trace);

                #region Calling SetStandardSellPriceAmount method
                EntityCollection priceListItemRecords = CommonHandler.RetrieveRecordsByOneValue("productpricelevel", "productpricelevelid", priceListItemEntity.Id, service, null, OrderType.Ascending,
                                                                                                new[] { "productid", "pricelevelid", "amount", "transactioncurrencyid" });

                if (priceListItemRecords != null && priceListItemRecords.Entities.Count > 0)
                {
                    Entity priceListItem = priceListItemRecords.Entities[0];
                    priceListItemHandler.CheckifPriceListisDefault(priceListItem);
                    //    priceListItemHandler.CreateExtendedPriceListItemRecord(priceListItem);
                }
                #endregion
            }
            catch (Exception ex)
            {
                //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #38
0
        /// <summary>
        /// Main entry point for he business logic that the plug-in is to execute.
        /// </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 365 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 override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("localContext");
            }

            try
            {
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;


                if (context.IsInTransaction)
                {
                    lock (SyncLock)
                    {

                        if (context.Depth < 2)
                        {
                            if (context.InputParameters["Target"] is Entity)
                            {
                                Entity target = (Entity)context.InputParameters["Target"];


                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                throw new InvalidPluginExecutionException("delete fail");
            }



        }
コード例 #39
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 ExecutePostOrderDiscountCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            string message = context.MessageName;
            string error   = "";

            try
            {
                SalesOrderDiscountHandler salesOrderDiscountHandler = new SalesOrderDiscountHandler(service, trace);
                salesOrderDiscountHandler.ReplicateDiscountInformation(salesOrderDiscountEntity);
                salesOrderDiscountHandler.SetOrderTotalDiscountAmount(salesOrderDiscountEntity, message);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The Promo selected is not applicable for the product of this Order."))
                {
                    throw new InvalidPluginExecutionException("The Promo selected is not applicable for the product of this Order.");
                }
                else if (ex.Message.Contains("Cannot associate discount. Vehicle is missing in Order Record."))
                {
                    throw new InvalidPluginExecutionException("Cannot associate discount. Vehicle is missing in Order Record.");
                }
                else
                {
                    throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
                }
            }
        }
コード例 #40
0
        protected void NormalizePostalcodeForSearch(LocalPluginContext context)
        {
            var target = context.PluginExecutionContext.InputParameters["Target"] as Entity;

            var postalCode = target.GetAttributeValue <string>("new_name");

            if (string.IsNullOrEmpty(postalCode))
            {
                return;
            }

            EntityReference countryRef = null;

            if (context.PluginExecutionContext.MessageName == "Create")
            {
                countryRef = target.GetAttributeValue <EntityReference>("new_country");
            }
            else if (context.PluginExecutionContext.MessageName == "Update")
            {
                var preImage = context.PreImage;
                countryRef = target.GetAttributeWithFallback <EntityReference>("new_country", preImage);
            }

            if (countryRef == null)
            {
                throw new InvalidPluginExecutionException("Country cannot be empty for postal code.");
            }

            var existing = context.OrganizationService.SearchPostalCode(postalCode, countryRef.Id, context.PluginExecutionContext.PrimaryEntityId);

            if (existing != null)
            {
                throw new InvalidPluginExecutionException("Postal code '{0}' already exists in the system.".FormatWith(postalCode));
            }

            target["new_codeforsearch"] = Utils.NormalizePostalCode(postalCode);
        }
        /// <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 ExecutePreEscalationCreateDuplicateDetection(LocalPluginContext localContext)
        {
            string escalationContactName = string.Empty;

            if (localContext == null)
            {
                return;
            }

            // TODO: Implement your custom Plug-in business logic.
            IPluginExecutionContext context = localContext.PluginExecutionContext;

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity  = (Entity)context.InputParameters["Target"];
                var    service = localContext.OrganizationService;
                if (context.Depth <= 1)
                {
                    if (entity.LogicalName == "smp_escalation")
                    {
                        try
                        {
                            escalationContactName = entity.Attributes["smp_name"].ToString();
                            GetDuplicateEscalationContact(service, escalationContactName);
                        }
                        catch (CustomServiceManagementPortalException)
                        {
                            ////throw;
                        }
                    }
                }
                else
                {
                    return;
                }
            }
        }
コード例 #42
0
        protected void AutoNameRiskIdentifierOnUpdate(LocalPluginContext context)
        {
            var target   = context.PluginExecutionContext.InputParameters["Target"] as Entity;
            var preImage = context.PreImage;

            var fieldMappingRef = target.GetAttributeWithFallback <EntityReference>("new_field", preImage);

            if (fieldMappingRef == null)
            {
                throw new InvalidPluginExecutionException("Risk identifier error: Field mapping cannot be empty.");
            }

            var fieldMapping = context.OrganizationService.Retrieve(fieldMappingRef);

            var riskClassRef = target.GetAttributeWithFallback <EntityReference>("new_riskclass", preImage);

            if (riskClassRef == null)
            {
                throw new InvalidPluginExecutionException("Risk identifier error: Risk class cannot be empty.");
            }

            var riskClass = context.OrganizationService.Retrieve(riskClassRef);

            var sequence = target.GetAttributeWithFallback <int?>("new_sequence", preImage);

            if (sequence == null)
            {
                sequence = 0;
            }

            var riskClassName    = riskClass.GetAttributeValue <string>("new_name");
            var fieldMappingName = fieldMapping.GetAttributeValue <string>("new_name");

            var name = "{0} - {1} - {2}".FormatWith(riskClassName, sequence, fieldMappingName);

            target["new_name"] = name;
        }
コード例 #43
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 ExecutePreOrderPlanningCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

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

            if (orderPlanningEntity.LogicalName != "gsc_sls_orderplanning")
            {
                return;
            }

            string message = context.MessageName;

            if (context.Mode == 0) //synchronous plugin
            {
                try
                {
                    // OrderPlanningHandler orderPlanningHandler = new OrderPlanningHandler(service, trace);
                    //orderPlanningHandler.GeneratePrimaryName(orderPlanningEntity);
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine));
                }
            }
        }
コード例 #44
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 ExecutePostCommittedFirmOrderCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }


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

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

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

            if (context.Mode == 0) //synchronous plugin
            {
                try
                {
                    CommittedFirmOrderHandler cfoHandler = new CommittedFirmOrderHandler(service, trace);
                    cfoHandler.SuggestCFOQuantity(cfoEntity);
                }
                catch (Exception ex)
                {
                    //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
        }
コード例 #45
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 ExecutePostOrderCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            string message = context.MessageName;
            string error   = "";

            try
            {
                SalesOrderHandler salesOrderHandler = new SalesOrderHandler(service, trace);

                salesOrderHandler.ReplicateQuoteVehicleAccessories(salesOrderEntity);
                salesOrderHandler.ReplicateQuoteDiscount(salesOrderEntity);
                //salesOrderHandler.ReplicateDiscountFields(salesOrder);
                salesOrderHandler.ReplicateQuoteCharges(salesOrderEntity);
                //salesOrderHandler.CreateCoverageAvailable(salesOrder, message);
                salesOrderHandler.CreateRequirementChecklist(salesOrderEntity, message);
                salesOrderHandler.DeleteExistingMonthlyAmortizationRecords(salesOrderEntity);
                salesOrderHandler.GetSelectedMonthlyAmortization(salesOrderEntity);
                salesOrderHandler.GenerateAccessoriesforVehicleModel(salesOrderEntity);
                salesOrderHandler.ReplicateDiscountFields(salesOrderEntity);
                salesOrderHandler.ReplicateQuoteCabChassis(salesOrderEntity);
            }
            catch (Exception ex)
            {
                //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #46
0
        protected void SetDueDate(LocalPluginContext localContext)
        {
            try
            {
                IPluginExecutionContext context        = localContext.PluginExecutionContext;
                ITracingService         tracingService = localContext.TracingService;
                IOrganizationService    service        = localContext.OrganizationService;

                tracingService.Trace("Work Order Mapped in Agreement Booking Date");
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity agreementBooking = context.InputParameters["Target"] as Entity;
                    if (agreementBooking.GetAttributeValue <EntityReference>("msdyn_workorder") != null)
                    {
                        Entity agreementbookingrecord = service.Retrieve(agreementBooking.LogicalName, agreementBooking.Id, new ColumnSet("msdyn_bookingdate"));
                        Entity workorder = service.Retrieve(agreementBooking.GetAttributeValue <EntityReference>("msdyn_workorder").LogicalName, agreementBooking.GetAttributeValue <EntityReference>("msdyn_workorder").Id, new ColumnSet(true));

                        DateTime bookingDate = agreementbookingrecord.GetAttributeValue <DateTime>("msdyn_bookingdate");
                        //// var lastDayOfMonth = DateTime.DaysInMonth(bookingDate.Year, bookingDate.Month);
                        var      month           = bookingDate.Month;
                        var      year            = bookingDate.Year;
                        DateTime firstDayOfMonth = new DateTime(year, month, 1);
                        DateTime lastDayOfMonth  = firstDayOfMonth.AddMonths(1).AddSeconds(-1);
                        //// DateTime duedate = new DateTime(year, month, lastDayOfMonth);
                        //// workorder.Attributes.Add("smp_duedate", duedate);
                        workorder.Attributes.Add("smp_duedate", lastDayOfMonth);
                        workorder.Attributes.Add("smp_duedatebybuildingtimezone", lastDayOfMonth.ToString("MM/dd/yyyy h:mm tt"));
                        service.Update(workorder);
                        tracingService.Trace("WO Updated");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #47
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 ExecutePreValidateQuoteCabChassisDelete(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            ITracingService         trace   = localContext.TracingService;
            var    quoteCabChassisEntity    = (EntityReference)context.InputParameters["Target"];
            string message = context.MessageName;
            string error   = "";

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

            try
            {
                QuoteCabChassisHandler quoteCabChassisHandler = new QuoteCabChassisHandler(service, trace);

                EntityCollection quoteCabChassisCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_quotecabchassis", "gsc_sls_quotecabchassisid", quoteCabChassisEntity.Id, service, null, OrderType.Ascending,
                                                                                                     new[] { "gsc_quoteid", "gsc_amount", "gsc_financing" });

                if (quoteCabChassisCollection != null && quoteCabChassisCollection.Entities.Count > 0)
                {
                    Entity quoteCabChassis = quoteCabChassisCollection.Entities[0];
                    quoteCabChassisHandler.SetCCAddOnAmount(quoteCabChassis, message);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
            }
        }
コード例 #48
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 ExecuteAccountPrePlugin(LocalPluginContext localContext)
    {
      if (localContext == null)
      {
        throw new ArgumentNullException("localContext");
      }

      var eventOperation = localContext.PluginExecutionContext
                                       .MessageName
                                       .ToEventOperation();

      var isUpdate = eventOperation.HasFlag(EventOperation.Update);

      try
      {
#if DEBUG
        throw new Exception("Debug code shouldn't go to TEST/PROD");
#endif
      }
      catch (Exception ex)
      {
        throw new InvalidPluginExecutionException("Error: " + ex.Message);
      }
    }
コード例 #49
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 ExecutePaymentActioOnUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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


            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid quoteProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            var serviceContext = new OrganizationServiceContext(service);
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var quote = service.Retrieve("quote", quoteProductID, set);


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

                var customerID = (EntityReference)quote["customerid"];

                var customer = service.Retrieve(customerID.LogicalName, customerID.Id, new ColumnSet() { AllColumns = true });

                Guid userId = context.InitiatingUserId;

                if (quote.Contains("new_actionforpayment"))
                {
                    var salesorderType = (OptionSetValue)quote["new_actionforpayment"];

                    if (salesorderType.Value == 1)
                    {
                        string quoteName = "";

                        if (quote.Contains("name"))
                        {
                            quoteName = (string)quote["name"];

                        }
                        else
                        {
                            quoteName = "Ново плащане";
                        }
                        //bool isTaxed = ((OptionSetValue)quote["new_vat"]).Value == 20;

                        string orderProductName = quoteName;
                        var prepayedAmount = (Money)quote["hcr_advance"];


                        //var advanceProductId = "14";
                        var currency = (EntityReference)quote["transactioncurrencyid"];
                        //decimal taxer = new Decimal(1.20);
                        //var prepaymentwithTax = new Money(prepayedAmount.Value * taxer);
                        var payment = new Entity("hcr_payments");
                        var countOfPayments = (int)quote["hcr_countpayments"];

                        payment["hcr_contactid"] = new EntityReference(customer.LogicalName, customer.Id);
                        payment["hcr_name"] = "Авансово плащане";
                        payment["hcr_quoteid"] = new EntityReference(quote.LogicalName, quote.Id);
                        payment["transactioncurrencyid"] = new EntityReference(currency.LogicalName, currency.Id);
                        payment["hcr_paidamount"] = new Money(prepayedAmount.Value);
                        payment["hcr_paymentstatus"] = new OptionSetValue(1);
                        payment["ownerid"] = new EntityReference("systemuser", context.InitiatingUserId); 
                      
                        var orderID = (Guid)service.Create(payment);


                        for (int i = 0; i < (int)countOfPayments; i++)
                        {

                            var parachutePayment = new Entity("hcr_payments");
                            var parachutePaymentAmount = (Money)quote["hcr_amountpayment"];
                            

                            parachutePayment["hcr_contactid"] = new EntityReference(customer.LogicalName, customer.Id);
                            parachutePayment["hcr_name"] = "Вноска по разсрочено плащане";
                            parachutePayment["hcr_quoteid"] = new EntityReference(quote.LogicalName, quote.Id);
                            parachutePayment["transactioncurrencyid"] = new EntityReference(currency.LogicalName, currency.Id);
                            parachutePayment["hcr_paidamount"] = new Money(parachutePaymentAmount.Value);
                            parachutePayment["hcr_paymentstatus"] = new OptionSetValue(1);
                            parachutePayment["ownerid"] = new EntityReference("systemuser", context.InitiatingUserId);
                            

                            var parachutePaymentID = (Guid)service.Create(parachutePayment);
                            
                        }
                    }
                }
            }
        }
コード例 #50
0
ファイル: getPricingType.cs プロジェクト: borisov90/Projects
        /// <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 ExecutegetPricingType(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

            Guid quoteDetailID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var quoteDetail = service.Retrieve("quotedetail", quoteDetailID, set);

            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                //var parentQuote = (Guid)quoteDetail["quoteid"];

                //var quote = service.Retrieve("quote", parentQuote, new ColumnSet(true));

                //var pricingType = (OptionSetValue)quote["new_pricingtype"];

                //quoteDetail["new_pricingtype"] = new OptionSetValue(pricingType.Value);

                var productID = (EntityReference)quoteDetail["productid"];
                var currentProduct = service.Retrieve(productID.LogicalName, productID.Id, new ColumnSet(true));
                var productPriceId = (EntityReference)currentProduct["pricelevelid"];
                var priceListProduct = service.Retrieve(productPriceId.LogicalName, productPriceId.Id, set);
                //Quote & Currency
                var quoteId = (EntityReference)quoteDetail["quoteid"];
                var parentQuote = service.Retrieve(quoteId.LogicalName, quoteId.Id, set);
                var priceLevelId = (EntityReference)parentQuote["pricelevelid"];
                var quotePriceList = service.Retrieve(priceLevelId.LogicalName, priceLevelId.Id, set);
                var priceCurrency = (EntityReference)quotePriceList["transactioncurrencyid"];
                var currency = service.Retrieve(priceCurrency.LogicalName, priceCurrency.Id, set);
                var price = currency["currencyname"];


                //Check the productLists
                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "productid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(productID.Id);

                //Currency check

                ConditionExpression priceType = new ConditionExpression();
                priceType.AttributeName = "transactioncurrencyid";
                priceType.Operator = ConditionOperator.Equal;
                priceType.Values.Add(currency.Id);

                FilterExpression filter = new FilterExpression();
                //filter.FilterOperator = LogicalOperator.And;
                filter.AddCondition(condition);
                filter.AddCondition(priceType);

                QueryExpression query = new QueryExpression();
                query.EntityName = "productpricelevel";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection productpricelevels = service.RetrieveMultiple(query);
                var productpriceLevel = productpricelevels.Entities[0];
                //var productPricing = from c in context.ContactSetjoin a in context.AccountSet on c.ContactId equals a.PrimaryContactId.Id
                var productPrice = (Money)productpriceLevel["amount"];
                var priceperunit = (Money)quoteDetail["priceperunit"];
                if (productPrice.Value > priceperunit.Value)
                {
                    quoteDetail["priceperunit"] = new Money(productPrice.Value);
                }
                //quoteDetail["new_jobdescription"] = price;
                service.Update(quoteDetail);
            }
        }
コード例 #51
0
		protected void Execute(LocalPluginContext context)
		{
			Context = context;

			Trace("Getting Target entity");
			Entity Target = Context.GetInputParameters<CreateInputParameters>().Target;
			Trace("Validate the Entity name");
			Trace("Get Attribute List");
			List<AttributeMetadata> attributeList = GetEntityMetadata(Target.GetAttributeValue<string>("cel_entityname"));

			Trace("Validate the Attribute name");
			if (!attributeList.Select(a => a.LogicalName).Contains(Target.GetAttributeValue<string>("cel_attributename")))
			{
				throw new InvalidPluginExecutionException("Specified Attribute does not exist.");
			}

			Trace("Validate the Trigger Attribute (if any)");
			if (!String.IsNullOrEmpty(Target.GetAttributeValue<string>("cel_triggerattribute")) && !attributeList.Select(a => a.LogicalName).Contains(Target.GetAttributeValue<string>("cel_triggerattribute")))
			{
				throw new InvalidPluginExecutionException("Specified Trigger Attribute does not exist.");
			}

			Trace("Validate the Attribute type");
			if (attributeList.Single(a => a.LogicalName.Equals(Target.GetAttributeValue<string>("cel_attributename"))).AttributeType != AttributeTypeCode.String && attributeList.Single(a => a.LogicalName.Equals(Target.GetAttributeValue<string>("cel_attributename"))).AttributeType != AttributeTypeCode.Memo)
			{
				throw new InvalidPluginExecutionException("Attribute must be a text field.");
			}

			#region test parameters
#if VALIDATEPARAMETERS
			Dictionary<string, string> fields = new Dictionary<string, string>() { { "cel_prefix", "Prefix" }, { "cel_suffix", "Suffix" } };

			foreach (string field in fields.Keys)
			{
				if (Target.Contains(field) && Target.GetAttributeValue<string>(field).Contains('{'))
				{
					if (Target.GetAttributeValue<string>(field).Count(c => c.Equals('{')) != Target.GetAttributeValue<string>(field).Count(c => c.Equals('}')))
					{
						throw new InvalidPluginExecutionException(String.Format("Invalid parameter formatting in {0}", fields[field]));
					}

					foreach (string p in Regex.Matches(Target.GetAttributeValue<string>(field), @"{(.*?)}").OfType<Match>().Select(m => m.Groups[0].Value).Distinct())
					{
						if (p.Substring(1).Contains('{'))
						{
							throw new InvalidPluginExecutionException(String.Format("Invalid parameter formatting in {0}", fields[field]));
						}
					}

					try
					{
						foreach (RuntimeParameter param in RuntimeParameter.GetParametersFromString(Target.GetAttributeValue<string>(field)))
						{
							if (!param.IsParentParameter())
							{
								if (!attributeList.Select(a => a.LogicalName).Contains(param.AttributeName))
								{
									throw new InvalidPluginExecutionException(String.Format("{0} is not a valid attribute name in {1} value", param.AttributeName, fields[field]));
								}
							}
							else
							{
								if (!attributeList.Select(a => a.LogicalName).Contains(param.ParentLookupName))
								{
									throw new InvalidPluginExecutionException(String.Format("{0} is not a valid attribute name in {1} value", param.ParentLookupName, fields[field]));
								}

								if (attributeList.Single(a => a.LogicalName.Equals(param.ParentLookupName)).AttributeType != AttributeTypeCode.Lookup && attributeList.Single(a => a.LogicalName.Equals(param.ParentLookupName)).AttributeType != AttributeTypeCode.Customer && attributeList.Single(a => a.LogicalName.Equals(param.ParentLookupName)).AttributeType != AttributeTypeCode.Owner)
								{
									throw new InvalidPluginExecutionException(String.Format("{0} must be a Lookup attribute type in {1} value", param.ParentLookupName, fields[field]));
								}

								var parentLookupAttribute = (LookupAttributeMetadata)GetAttributeMetadata(Target.GetAttributeValue<string>("cel_entityname"), param.ParentLookupName);
								if (!parentLookupAttribute.Targets.Any(e => GetEntityMetadata(e).Select(a => a.LogicalName).Contains(param.AttributeName)))
								{
									throw new InvalidPluginExecutionException(String.Format("invalid attribute on {0} parent entity, in {1} value", param.ParentLookupName, fields[field]));
								}

							}
						}
					}
					catch (InvalidPluginExecutionException)
					{
						throw;
					}
					catch
					{
						throw new InvalidPluginExecutionException(String.Format("Failed to parse Runtime Parameters in {0} value.", fields[field]));
					}
				}
			}
#endif
			#endregion

			if (Target.Contains("cel_conditionaloptionset"))
			{
				Trace("Validate Conditional OptionSet");
				if (!attributeList.Select(a => a.LogicalName).Contains(Target.GetAttributeValue<string>("cel_conditionaloptionset")))
				{
					throw new InvalidPluginExecutionException("Specified Conditional OptionSet does not exist");
				}

				if (attributeList.Single(a => a.LogicalName.Equals(Target.GetAttributeValue<string>("cel_conditionaloptionset"))).AttributeType != AttributeTypeCode.Picklist)
				{
					throw new InvalidPluginExecutionException("Conditional Attribute must be an OptionSet");
				}

				Trace("Validate Conditional Value");
				PicklistAttributeMetadata optionSetMetadata = (PicklistAttributeMetadata)GetAttributeMetadata(Target.GetAttributeValue<string>("cel_entityname"), Target.GetAttributeValue<string>("cel_conditionaloptionset"));//attributeResponse.AttributeMetadata;
				if (!optionSetMetadata.OptionSet.Options.Select(o => o.Value).Contains(Target.GetAttributeValue<int>("cel_conditionalvalue")))
				{
					throw new InvalidPluginExecutionException("Conditional Value does not exist in OptionSet");
				}
			}

			#region Duplicate Check
#if DUPLICATECHECK
			Trace("Validate there are no duplicates");
			// TODO: Fix this. duplicate detection works when all fields contain data, but fails when some fields are empty
			var autoNumberList = Context.OrganizationDataContext.CreateQuery("cel_autonumber")
																.Where(a => a.GetAttributeValue<string>("cel_entityname").Equals(Target.GetAttributeValue<string>("cel_entityname")) && a.GetAttributeValue<string>("cel_attributename").Equals(Target.GetAttributeValue<string>("cel_attributename")))
																.Select(a => new { Id = a.GetAttributeValue<Guid>("cel_autonumberid"), ConditionalOption = a.GetAttributeValue<string>("cel_conditionaloptionset"), ConditionalValue = a.GetAttributeValue<int>("cel_conditionalvalue") })
																.ToList();


			if (!Target.Contains("cel_conditionaloptionset") && autoNumberList.Any())
			{
				throw new InvalidPluginExecutionException("Duplicate AutoNumber record exists.");
			}
			else if (autoNumberList.Where(a => a.ConditionalOption.Equals(Target.GetAttributeValue<string>("cel_conditionaloptionset")) && a.ConditionalValue.Equals(Target.GetAttributeValue<int>("cel_conditionalvalue"))).Any())
			{
				throw new InvalidPluginExecutionException("Duplicate AutoNumber record exists.");
			}
#endif
			#endregion

			Trace("Insert the autoNumber Name attribute");
			Target["cel_name"] = String.Format("AutoNumber for {0}, {1}", Target.GetAttributeValue<string>("cel_entityname"), Target.GetAttributeValue<string>("cel_attributename"));
		}
コード例 #52
0
        protected void Execute(LocalPluginContext Context)
        {
            Trace("Get Target record");
            Entity Target = Context.GetInputParameters<CreateInputParameters>().Target;
            string pluginName = String.Format(PLUGIN_NAME, Target.GetAttributeValue<string>("cel_entityname"));

            if (Target.GetAttributeValue<OptionSetValue>("cel_triggerevent").Value == 1)
            {
                pluginName += " Update";
            }

            Trace("Check for existing plugin step");
            if (Context.OrganizationDataContext.CreateQuery("sdkmessageprocessingstep").Where(s => s.GetAttributeValue<string>("name").Equals(pluginName)).ToList().Any())
            {
                return;  // Step already exists, nothing to do here.
            }

            Trace("Build the configuration");
            AutoNumberPluginConfig config = new AutoNumberPluginConfig()
            {
                EntityName = Target.GetAttributeValue<string>("cel_entityname"),
                EventName = Target.GetAttributeValue<OptionSetValue>("cel_triggerevent").Value == 1 ? "Update" : "Create"
            };

            Trace("Get the Id of this plugin");
            Guid PluginTypeId = Context.OrganizationDataContext.CreateQuery("plugintype")
                 											   .Where(s => s.GetAttributeValue<string>("name").Equals("Celedon.GetNextAutoNumber"))
                                                               .Select(s => s.GetAttributeValue<Guid>("plugintypeid"))
                                                               .First();

            Trace("Get the message id from this org");
            Guid messageId = Context.OrganizationDataContext.CreateQuery("sdkmessage")
                                                            .Where(s => s.GetAttributeValue<string>("name").Equals(config.EventName))
                                                            .Select(s => s.GetAttributeValue<Guid>("sdkmessageid"))
                                                            .First();

            Trace("Get the filterId for for the specific entity from this org");
            Guid filterId = Context.OrganizationDataContext.CreateQuery("sdkmessagefilter")
                                                           .Where(s => s.GetAttributeValue<string>("primaryobjecttypecode").Equals(config.EntityName)
                                                               && s.GetAttributeValue<EntityReference>("sdkmessageid").Id.Equals(messageId))
                                                           .Select(s => s.GetAttributeValue<Guid>("sdkmessagefilterid"))
                                                           .First();

            Trace("Build new plugin step");
            Entity newPluginStep = new Entity("sdkmessageprocessingstep")
            {
                Attributes = new AttributeCollection()
                {
                    { "name", pluginName },
                    { "description", pluginName },
                    { "plugintypeid", PluginTypeId.ToEntityReference("plugintype") },  // This plugin type
                    { "sdkmessageid", messageId.ToEntityReference("sdkmessage") },  // Create or Update Message
                    { "configuration", config.ToJSON() },  // EntityName and RegisteredEvent in the UnsecureConfig
                    { "stage", PREOPERATION.ToOptionSetValue() },  // Execution Stage: Pre-Operation
                    { "rank", 1 },
                    { "impersonatinguserid", Context.PluginExecutionContext.UserId.ToEntityReference("systemuser") },  // Run as SYSTEM user. Assumes we are currently running as the SYSTEM user
                    { "sdkmessagefilterid", filterId.ToEntityReference("sdkmessagefilter") },
                }
            };

            Trace("Create new plugin step");
            Guid pluginStepId = Context.OrganizationService.Create(newPluginStep);
        }
コード例 #53
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</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>
        public void Execute(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            // Construct the Local plug-in context.
            LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));

            try
            {
                // Iterate over all of the expected registered events to ensure that the plugin
                // has been invoked by an expected event
                // For any given plug-in event at an instance in time, we would expect at most 1 result to match.
                Action<LocalPluginContext> entityAction =
                    (from a in this.RegisteredEvents
                     where (
                     a.Item1 == localcontext.PluginExecutionContext.Stage &&
                     a.Item2 == localcontext.PluginExecutionContext.MessageName &&
                     (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
                     )
                     select a.Item4).FirstOrDefault();

                if (entityAction != null)
                {
                    localcontext.Trace(string.Format(
                        CultureInfo.InvariantCulture,
                        "{0} is firing for Entity: {1}, Message: {2}",
                        this.ChildClassName,
                        localcontext.PluginExecutionContext.PrimaryEntityName,
                        localcontext.PluginExecutionContext.MessageName));

                    entityAction.Invoke(localcontext);

                    ServiceContext context = new ServiceContext(localcontext.OrganizationService);

                    Contact contact = null;
                    ModificationEnumeration modification = ModificationEnumeration.Create;

                    // The InputParameters collection contains all the data passed in the message request.
                    if (localcontext.PluginExecutionContext.InputParameters.Contains("Target") &&
                        localcontext.PluginExecutionContext.InputParameters["Target"] is Entity)
                    {
                        // Obtain the target entity from the input parameters.
                        Entity entity = (Entity)localcontext.PluginExecutionContext.InputParameters["Target"];

                        contact = entity.ToEntity<Contact>();
                    }
                    else if (localcontext.PluginExecutionContext.InputParameters.Contains("Target") && localcontext.PluginExecutionContext.InputParameters["Target"] is EntityReference)
                    {
                        // Obtain the target entity from the input parameters.
                        EntityReference entity = (EntityReference)localcontext.PluginExecutionContext.InputParameters["Target"];

                        contact = (from c in context.ContactSet
                                   where c.Id == entity.Id
                                   select c).FirstOrDefault();

                        modification = ModificationEnumeration.Delete;
                    }

                    ContactServiceClient client = new ContactServiceClient();

                    client.Open();

                    try
                    {
                        client.Publish(new ContactPublishRequestMessage()
                        {
                            Contact = contact,
                            Modification = modification
                        });
                    }
                    catch
                    {
                        if(client.State == CommunicationState.Faulted)
                            client.Abort();

                        throw;
                    }
                    finally
                    {
                        if(client.State == CommunicationState.Opened)
                            client.Close();
                    }

                    // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
                    // guard against multiple executions.
                    return;
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));

                // Handle the exception.
                throw;
            }
            finally
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
            }
        }
コード例 #54
0
ファイル: InvoiceVATer.cs プロジェクト: borisov90/Projects
        /// <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 ExecuteInvoiceVATer(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid invoiceID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var invoice = service.Retrieve("invoice", invoiceID, set);


            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var totalamount = (Money)invoice["totallineitemamount"];
                var discount = (Money)invoice["totaldiscountamount"];

                var VAT = (OptionSetValue)invoice["new_vat"];
                var tax = totalamount.Value * VAT.Value / 100;

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "invoiceid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(invoiceID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "invoicedetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection invoicedetails = service.RetrieveMultiple(query);

                foreach (var detail in invoicedetails.Entities)
                {
                    bool isLocked = (bool)detail.Attributes["invoiceispricelocked"];

                    if (isLocked)
                    {
                        //It is really important to unlock both the Invoice and the Order!
                        UnlockInvoicePricingRequest unlockInvoice = new UnlockInvoicePricingRequest();
                        unlockInvoice.InvoiceId = ((EntityReference)detail.Attributes["invoiceid"]).Id;
                        UnlockInvoicePricingResponse unlockInvoiceResponse = (UnlockInvoicePricingResponse)service.Execute(unlockInvoice);
                    }

                    var quantity = (decimal)detail["quantity"];
                    var priceperunit = (Money)detail["priceperunit"];
                    var teamleader = (OptionSetValue)detail["new_tldiscount"];

                    //Then I calculate the manual discount and baseamount, for the further calculations
                    detail.Attributes["manualdiscountamount"] = new Money((priceperunit.Value * teamleader.Value / 100) * quantity);
                    var manualdiscountamount = (Money)detail.Attributes["manualdiscountamount"];
                    detail.Attributes["baseamount"] = new Money(priceperunit.Value * quantity);
                    var baseamount = (Money)detail["baseamount"];

                    //finally I calculate the tax
                    detail["new_vat"] = new OptionSetValue(VAT.Value);
                    var taxDetail = (baseamount.Value - manualdiscountamount.Value) * VAT.Value / 100;
                    detail.Attributes["tax"] = new Money(taxDetail); //tax

                    service.Update(detail);
                }

                invoice["new_totalamountincludingvat"] = new Money((totalamount.Value - discount.Value) + tax);

                service.Update(invoice);
            }
        }
コード例 #55
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 ExecutePreContactCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)localContext.PluginExecutionContext;

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

                //Organization Service
                IOrganizationService service = localContext.OrganizationService;

                //Tracing Service
                ITracingService trace = (ITracingService)localContext.TracingService;

                //Get the target entity
                Entity entity = (Entity)context.InputParameters["Target"];
                try
                {
                    //if (entity.Attributes.Contains("firstname"))
                    //{
                    //    entity.Attributes["jobtitle"] = "testing swsw";
                    //}

                    if (entity.Attributes.Contains("mobilephone"))
                    {

                        string message = "New contact added in system  for " + entity.Attributes["firstname"] + " " + entity.Attributes["lastname"];
                        SmsSender smsSender = new SmsSender();
                        string response = smsSender.SendSMS(entity.Attributes["mobilephone"].ToString(), "919460264151", "5b2a23d7", "59d9fa03",
                        Uri.EscapeUriString(message));

                  //      string fetchxmluser = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                  //          "<entity name='systemuser'>" +
                  //          "<attribute name='fullname' />" +
                  // "<attribute name='businessunitid' />" +
                  //"<attribute name='title' /> " +
                  //"<attribute name='address1_telephone1'/>" +
                  //"<attribute name='positionid' /> " +
                  //"<attribute name='systemuserid' /> " +
                  //"<attribute name='mobilephone' />" +
                  //"<attribute name='parentsystemuserid' />" +
                  //"<attribute name='firstname' />" +
                  //"<order attribute='fullname' descending= 'false' />" +
                  //"</entity>" +
                  // "</fetch>";


                        //EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchxmluser));
                        //if (result.Entities.Count > 1)
                        //{

                        //    throw new InvalidPluginExecutionException(string.Format("Contract created by  : {0} and total user {1}", entity.Attributes["createdby"], result.Entities.Count));
                        //}

                        //if (entity.Attributes["mobilephone"].ToString() != "9999")
                        //{

                        //    throw new InvalidPluginExecutionException(string.Format("An error occured in PreContactCreate plugin: {0}", "invalid no"));
                        //}
                    }

                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(string.Format("An error occured in PreContactCreate plugin: {0} {1} {2}", ex.ToString(), ex.InnerException, ex.StackTrace));
                }
            }
        }
コード例 #56
0
        private void SetOutputParameters(cielo_discountraterestriction cielo_discountraterestriction, LocalPluginContext localContext)
        {
            var defaultRateParameter = (decimal)localContext.PluginExecutionContext.InputParameters["DefaultRate"];

            // Minimum Tax = Default Tax - ((Default Tax * Discount Rate Restriction Percentage) / 100
            localContext.PluginExecutionContext.OutputParameters["MinimumRateRestrictionPercentage"] = defaultRateParameter - ((defaultRateParameter - cielo_discountraterestriction.cielo_discountraterestrictionpercentage) / 100);
            localContext.PluginExecutionContext.OutputParameters["MaximumRateRestrictionPercentage"] = cielo_discountraterestriction.cielo_discountraterestrictionpercentage;
            localContext.PluginExecutionContext.OutputParameters["DiscounRateRestrictionPercentage"] = cielo_discountraterestriction.cielo_discountraterestrictionpercentage;
        }
コード例 #57
0
ファイル: Plugin.cs プロジェクト: borisov90/Projects
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</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>
        public void Execute(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            // Construct the Local plug-in context.
            LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));

            try
            {
                // Iterate over all of the expected registered events to ensure that the plugin
                // has been invoked by an expected event
                // For any given plug-in event at an instance in time, we would expect at most 1 result to match.
                Action<LocalPluginContext> entityAction =
                    (from a in this.RegisteredEvents
                     where (
                     a.Item1 == localcontext.PluginExecutionContext.Stage &&
                     a.Item2 == localcontext.PluginExecutionContext.MessageName &&
                     (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
                     )
                     select a.Item4).FirstOrDefault();

                if (entityAction != null)
                {
                    localcontext.Trace(string.Format(
                        CultureInfo.InvariantCulture,
                        "{0} is firing for Entity: {1}, Message: {2}",
                        this.ChildClassName,
                        localcontext.PluginExecutionContext.PrimaryEntityName,
                        localcontext.PluginExecutionContext.MessageName));

                    entityAction.Invoke(localcontext);

                    // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
                    // guard against multiple executions.
                    return;
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));

                // Handle the exception.
                throw;
            }
            finally
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
            }
        }
コード例 #58
0
        protected void ExecuteCielo_PrSvDisableTypedSaleAc(LocalPluginContext localContext)
        {
            try
            {
                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }

                // Verificando se o plugin não foi chamado por outro plugin
                if (localContext.PluginExecutionContext.Depth > 1)
                    return;

                //Instancia as entidades enviadas à Action
                var entityTargetReference = GetEntityParameter<EntityReference>("Target");
                var parameterizationReference = GetEntityParameter<EntityReference>("RequestParameterization");
                var requestCase = GetEntityParameter<Entity>("RequestCase").ToEntity<Incident>();
                var productRequest = GetEntityParameter<Entity>("ProductRequest").ToEntity<cielo_productrequest>();
                var affectedProducts = GetEntityParameter<EntityCollection>("AffectedProducts");

                var entityTarget = GetEntityById(entityTargetReference.LogicalName, 
                                                entityTargetReference.Id,
                                                new ColumnSet("customerid", 
                                                            "cielo_servicecallnumber", 
                                                            "cielo_commercialestablishmentid", 
                                                            "cielo_teamid",
                                                            "cielo_contactid"))
                                                .ToEntity<Incident>();
                var parameterization = GetEntityById(parameterizationReference.LogicalName,
                                                parameterizationReference.Id,
                                                new ColumnSet("cielo_subjectid","cielo_name"))
                                                .ToEntity<cielo_requestparameter>();

                //Seta os valores da case a ser criada
                requestCase.ParentCaseId = new EntityReference(Incident.EntityLogicalName, entityTarget.Id);
                requestCase.cielo_requestparamterid = new EntityReference(cielo_requestparameter.EntityLogicalName, parameterization.Id);
                requestCase.cielo_servicechannelcode = new OptionSetValue(791880020);
                requestCase.cielo_processtypecode = new OptionSetValue(791880020);
                requestCase.CaseOriginCode = new OptionSetValue(1);
                requestCase.CaseTypeCode = new OptionSetValue(3);
                requestCase.StatusCode = requestCase.StatusCode != null? requestCase.StatusCode : new OptionSetValue(1);
                requestCase.cielo_servicecallnumber = entityTarget.cielo_servicecallnumber;
                requestCase.CustomerId = entityTarget.CustomerId;
                requestCase.cielo_commercialestablishmentid = entityTarget.cielo_commercialestablishmentid;
                requestCase.cielo_contactid = entityTarget.cielo_contactid;
                requestCase.cielo_teamid = entityTarget.cielo_teamid;
                requestCase.SubjectId = parameterization.cielo_subjectid;
                requestCase.Id = localContext.OrganizationService.Create(requestCase);
                
                //Seta os valores da solicitacao a ser criada
                productRequest.cielo_caseId = new EntityReference(Incident.EntityLogicalName, requestCase.Id);
                productRequest.cielo_name = parameterization.cielo_name;
                productRequest.OwnerId = requestCase.OwnerId;
                productRequest.cielo_requestreasoncode = requestCase.cielo_requestreasoncode;
                productRequest.cielo_requestparameterizationcode = new EntityReference(cielo_requestparameter.EntityLogicalName, parameterization.Id);
                productRequest.cielo_typedsaleindicator = false;
                productRequest.Id = localContext.OrganizationService.Create(productRequest);

                //Recupera do CRM o case que foi e criado e que teve o seu titulo atualizado via plugin
                requestCase = localContext.OrganizationService.Retrieve(Incident.EntityLogicalName, requestCase.Id, new ColumnSet("title")).ToEntity<Incident>();

                //Seta os valores e cria as entidade Produto da solicitacao
                foreach (var item in affectedProducts.Entities)
                {
                    var requestProduct = item.ToEntity<cielo_requestproduct>();
                        //
                    //requestProduct.cielo_productname = item.ToEntity<cielo_requestproduct>().cielo_productname;
                    //requestProduct.cielo_productcode = item.ToEntity<cielo_requestproduct>().cielo_productcode;
                    requestProduct.cielo_productrequestcode = new EntityReference(cielo_productrequest.EntityLogicalName, productRequest.Id);
                    requestProduct.cielo_name = string.Concat(requestCase.Title, " - ", requestProduct.cielo_productcode);
                    localContext.OrganizationService.Create(requestProduct);
                }
            }
            catch (InvalidPluginExecutionException ex)
            {
                throw ex;
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
            catch (Exception ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
        }
コード例 #59
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 ExecuteCielo_discountraterestriction(LocalPluginContext localContext)
        {
            try
            {
                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }

                // Verificando se o plugin não foi chamado por outro plugin
                if (localContext.PluginExecutionContext.Depth > 1)
                    return;

                var mccParameter = (string)localContext.PluginExecutionContext.InputParameters["BranchActivity"];
                var agentGroupParameter = (string)localContext.PluginExecutionContext.InputParameters["AgentGroup"];
                var defaultRateParameter = (decimal)localContext.PluginExecutionContext.InputParameters["DefaultRate"];
                var productCodeParameter = (string)localContext.PluginExecutionContext.InputParameters["ProductCode"];

                using (var context = new XrmServiceContext(localContext.OrganizationService))
                {
                    branchOfActivity = context.cielo_branchofactivitySet.Where(x => x.cielo_code == Int32.Parse(mccParameter)).First();
                    team = context.TeamSet.Where(x => x.Id == Guid.Parse(agentGroupParameter)).First();

                    var discountRateRestriction = context.cielo_discountraterestrictionSet.Where(x => x.cielo_agentgroupcodeId == new EntityReference(Team.EntityLogicalName, team.Id)
                                                                                                    && x.cielo_branchactivitycodeId == new EntityReference(cielo_branchofactivity.EntityLogicalName, team.Id)
                                                                                                    && x.cielo_productcode == productCodeParameter).First();
                    if (discountRateRestriction != null)
                    {
                        SetOutputParameters(discountRateRestriction, localContext);
                        return;
                    }

                    discountRateRestriction = context.cielo_discountraterestrictionSet.Where(x => x.cielo_agentgroupcodeId == new EntityReference(Team.EntityLogicalName, team.Id)
                                                                                                && x.cielo_branchactivitycodeId == new EntityReference(cielo_branchofactivity.EntityLogicalName, team.Id)).First();
                    if (discountRateRestriction != null)
                    {
                        SetOutputParameters(discountRateRestriction, localContext);
                        return;
                    }

                    discountRateRestriction = context.cielo_discountraterestrictionSet.Where(x => x.cielo_agentgroupcodeId == new EntityReference(Team.EntityLogicalName, team.Id)).First();

                    if (discountRateRestriction != null)
                        SetOutputParameters(discountRateRestriction, localContext);
                }

            }
            catch (InvalidPluginExecutionException ex)
            {
                throw ex;
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
            catch (Exception ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
        }
コード例 #60
0
        protected void ExecuteCielo_CmNeGetNegotiationDataAction(LocalPluginContext localContext)
        {
            try
            {
                if (localContext == null) throw new ArgumentNullException("localContext");

                if (localContext.PluginExecutionContext.Depth > 1) return;

                var commercialEstablishment = (EntityReference)localContext.PluginExecutionContext.InputParameters["CommercialEstablishment"];
                var agentGroup = (EntityReference)localContext.PluginExecutionContext.InputParameters["AgentGroup"];
                var requestParameterization = (EntityReference)localContext.PluginExecutionContext.InputParameters["RequestParameterization"];
                var collection = new EntityCollection();

                localContext.PluginExecutionContext.OutputParameters["DoOffersExist"] = 
                localContext
                    .OrganizationService
                    .RetrieveMultiple(
                    new FetchExpression(String.Format(@"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                        <entity name='cielo_customeroffer'>
                        <attribute name='cielo_customerofferid' />
                        <attribute name='cielo_customeroffername' />
                        <order attribute='cielo_customeroffername' descending='false' />
                        <filter type='and'>
                            <condition attribute='statecode' operator='eq' value='0' />
                            <condition attribute='cielo_responseid' operator='null' />
                            <condition attribute='cielo_commercialestablishmentid' operator='eq' value='{0}' />
                            <condition attribute='cielo_agentgroupid' operator='eq' value='{1}' />
                        </filter>
                        </entity>
                    </fetch>", commercialEstablishment.Id, agentGroup.Id)))
                    .Entities
                    .Count > 0 ? true : false;

                localContext
                    .OrganizationService
                    .RetrieveMultiple(
                    new FetchExpression(String.Format(@"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                        <entity name='cielo_requestreason'>
                        <attribute name='cielo_name' />
                        <attribute name='cielo_requestreasonid' />
                        <order attribute='cielo_name' descending='false' />
                        <filter type='and'>
                            <condition attribute='statecode' operator='eq' value='0' />
                        </filter>
                        <link-entity name='subject' from='subjectid' to='cielo_articlesubjectcodeid' alias='aa'>
                            <link-entity name='cielo_requestparameter' from='cielo_subjectid' to='subjectid' alias='ab'>
                            <filter type='and'>
                                <condition attribute='cielo_requestparameterid' operator='eq' value='{0}' />
                            </filter>
                            </link-entity>
                        </link-entity>
                        </entity>
                    </fetch>", requestParameterization.Id)))
                    .Entities
                    .ToList()
                    .ForEach(item =>
                    {
                        var entity = new Entity(cielo_requestreason.EntityLogicalName);
                        entity.Attributes.Add("cielo_name", (string)item["cielo_name"]);
                        entity.Attributes.Add("cielo_requestreasonid", (Guid)item["cielo_requestreasonid"]);
                        collection.Entities.Add(entity);
                    });
                localContext.PluginExecutionContext.OutputParameters["Reasons"] = collection;


                collection = new EntityCollection(); 
                localContext
                    .OrganizationService
                    .RetrieveMultiple(
                    new FetchExpression(@"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                        <entity name='cielo_dealitem'>
                        <attribute name='cielo_dealitem' />
                        <attribute name='cielo_dealitemid' />
                        <order attribute='cielo_dealitem' descending='false' />
                        <filter type='and'>
                            <condition attribute='statecode' operator='eq' value='0' />
                        </filter>
                        </entity>
                    </fetch>"))
                    .Entities
                    .ToList()
                    .ForEach(item =>
                    {
                        var entity = new Entity(cielo_dealitem.EntityLogicalName);
                        entity.Attributes.Add("cielo_dealitem", (string)item["cielo_dealitem"]);
                        entity.Attributes.Add("cielo_dealitemid", (Guid)item["cielo_dealitemid"]);
                        collection.Entities.Add(entity);
                    });
                localContext.PluginExecutionContext.OutputParameters["DealItems"] = collection;


                collection = new EntityCollection(); 
                localContext
                    .OrganizationService
                    .RetrieveMultiple(
                    new FetchExpression(@"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                        <entity name='competitor'>
                        <attribute name='name' />
                        <attribute name='competitorid' />
                        <order attribute='name' descending='false' />
                        </entity>
                    </fetch>"))
                    .Entities
                    .ToList()
                    .ForEach(item =>
                    {
                        var entity = new Entity(Competitor.EntityLogicalName);
                        entity.Attributes.Add("name", (string)item["name"]);
                        entity.Attributes.Add("competitorid", (Guid)item["competitorid"]);
                        collection.Entities.Add(entity);
                    });
                localContext.PluginExecutionContext.OutputParameters["Competitors"] = collection;

                
                /////////////////////////////////////////////////////
                //Entidades tiveram que ser adicionadas            //
                //utilizando o método acima pois estava            //
                //enfrentando problemas de desserialização         //
                //no retorno da Action na DAO GetNegotiationDataDAO//
                //                                                 //
                //Autor: Angel Ojea                                //
                /////////////////////////////////////////////////////
            }
            catch (InvalidPluginExecutionException ex)
            {
                throw ex;
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
            catch (Exception ex)
            {
                //string friendlyMessage = ExceptionManagement.LogException(ex, Entities.Exception.Priority.Medium, localContext.OrganizationService);
                //throw new InvalidPluginExecutionException(friendlyMessage);
            }
        }