Esempio n. 1
0
        public override void Execute(ILocalPluginContext context)
        {
            // only systemuser senders will be processed
            var sender = GetSender(context);

            if (sender == null || !sender.LogicalName.Equals("systemuser"))
            {
                return;
            }

            // Get Body
            var body = context.GetAttributeValue <string>("description");

            if (string.IsNullOrWhiteSpace(body))
            {
                return;
            }

            // Get Task Id from Body & verify owner of task is the sender
            var taskid = GetTaskId(context, body, sender);

            if (!taskid.HasValue)
            {
                // If there is no task id, stop work
                return;
            }

            // Update the task
            CompleteTask(context, taskid.Value);

            var attachments = GetAttachments(context);

            // TODO: process attachments
        }
        private void ResolveCase(ILocalPluginContext localContext, Incident latestCase)
        {
            // Change the case built-in status and status reason to Resolved and Problem solved respectively on the latest case created.
            // Change the Change Email Status to Approved on the latest case created.
            latestCase[ChangeEmailStatus] = new OptionSetValue(100000004); //Approved
            latestCase[SubStatusReason]   = new OptionSetValue(100000002); //Approved - Confirmed
            localContext.OrganizationService.Update(latestCase);

            // Create Incident Resolution
            var incidentResolutionResolved = new IncidentResolution
            {
                Subject    = "Case Resolved",
                IncidentId = new EntityReference(Incident.EntityLogicalName, latestCase.Id),
                ActualEnd  = DateTime.Now
            };

            // Close Incident
            var closeIncidentRequestResolved = new CloseIncidentRequest
            {
                IncidentResolution = incidentResolutionResolved,
                Status             = new OptionSetValue(5)
            };

            localContext.OrganizationService.Execute(closeIncidentRequestResolved);
            localContext.Trace($"Set case status to Approved for Case with ID {latestCase.Id}");
        }
Esempio n. 3
0
        public override void Execute(ILocalPluginContext context)
        {
            // Step 1: Get the action taken
            context.Trace($"Depth: {context.PluginExecutionContext.Depth}");
            if (context.PluginExecutionContext.Depth > 1)
            {
                return;
            }

            context.Trace("Step 1");
            var action = context.GetAttributeValue <EntityReference>("fdbzap_ar_actiontaken");

            if (action == null)
            {
                return;
            }

            // Step 2: Set action taken statuscode to run - 2
            context.Trace("Step 2");
            var actionEntity = new Entity(action.LogicalName);

            actionEntity.Id            = action.Id;
            actionEntity["statuscode"] = new OptionSetValue(2);
            context.OrganizationService.Update(actionEntity);
        }
Esempio n. 4
0
 private static OrganizationResponse UpdateRegardingObject(ILocalPluginContext context,
                                                           EntityReference approvalRequestReference) =>
 context.OrganizationService.Execute(
     new OrganizationRequest("fdbzap_ar_checkstatus")
 {
     ["Target"] = approvalRequestReference
 });
        /// <summary>
        /// Extacts the query from the plugin context Query input argument.
        /// </summary>
        /// <param name="localContext"></param>
        /// <returns></returns>
        private QueryExpression extractQueryInputFromContext(ILocalPluginContext localContext)
        {
            var inputParameters = localContext.PluginExecutionContext.InputParameters;

            if (!inputParameters.Contains("Query") || inputParameters["Query"] == null)
            {
                throw new ArgumentException("Context does not contain a valid query input argument.");
            }

            if (inputParameters["Query"] is QueryExpression)
            {
                return(inputParameters["Query"] as QueryExpression);
            }


            if (inputParameters["Query"] is FetchExpression)
            {
                var fetchExpression = inputParameters["Query"] as FetchExpression;

                var conversionRequest = new FetchXmlToQueryExpressionRequest
                {
                    FetchXml = fetchExpression.Query
                };

                var conversionResponse = (FetchXmlToQueryExpressionResponse)localContext.OrganizationService.Execute(conversionRequest);

                return(conversionResponse.Query);
            }

            throw new Exception("Could not extract a valid query expression from the plugin input parameters.");
        }
Esempio n. 6
0
        internal static Entity GetRollupAction(ILocalPluginContext context, EntityReference actionTaken)
        {
            var fetchXml = $@"
<fetch page='1' count='1' distinct='true' no-lock='true'>
  <entity name='fdbzap_ar_action'>
    <attribute name='fdbzap_ar_actionid' />
    <attribute name='fdbzap_ar_priority' />
    <attribute name='fdbzap_ar_actioncount' />
    <attribute name='fdbzap_ar_approvalrequest' />
    <order descending='false' attribute='fdbzap_ar_priority' />
    <link-entity name='fdbzap_ar_action' from='fdbzap_ar_rollupaction' to='fdbzap_ar_actionid' link-type='inner' alias='childaction'>
      <filter type='and'>
        <condition attribute='fdbzap_ar_actionid' operator='eq' value='{actionTaken.Id}'/>
      </filter>
    </link-entity>
  </entity>
</fetch>";

            var response = context.OrganizationService.RetrieveMultiple(new FetchExpression(fetchXml));

            if (response == null || response.Entities.Count == 0)
            {
                return(null);
            }

            return(response.Entities[0]);
        }
 public void ExecuteHandler(ILocalPluginContext localContext)
 {
     if (TestingDelegate != null)
     {
         TestingDelegate(localContext);
     }
 }
        private void MyUpdateEventHandler(ILocalPluginContext localContext)
        {
            // This line will write to Plugin Trace Log as well as Application Insights
            localContext.Trace("Entered MyUpdateEventHandler");

            //Track an event.
            localContext.TrackEvent("MyEventName");

            // To gain access to additional telemetry functions that are not part of the
            // ILocalPluginContext interface we need to cast into the interface that
            // provides the advanced telemetry support.
            var asInstrumentedContext = localContext as ISupportContextInstrumentation;

            if (asInstrumentedContext != null)
            {
                // add special properties to the current telemetry context to capture an
                // alternate key name and value. This is useful when using AppInsights
                // across related components that don't share the same key. The value
                // would normally come from a call to an integrated system but this example
                // just uses a random guid.
                asInstrumentedContext.SetAlternateDataKey("MySystemName", Guid.NewGuid().ToString());

                // access the TelementryFactory and TelemetryClient directly to send a message
                // to AppInsights with a severity level. Using this method you can access anything
                // that the Telemetry system offers even if that functionality is not surfaced in
                // the localContext.
                var item = asInstrumentedContext.TelemetryFactory.BuildMessageTelemetry("This is a warning message.", CCLLC.Telemetry.eSeverityLevel.Warning);
                asInstrumentedContext.TelemetryClient.Track(item);
            }
        }
Esempio n. 9
0
 private static void SetOutput(ILocalPluginContext context, bool error, string msg,
                               EntityReference result = null)
 {
     context.PluginExecutionContext.OutputParameters["result"]          = result;
     context.PluginExecutionContext.OutputParameters["errorOccurred"]   = error;
     context.PluginExecutionContext.OutputParameters["responseMessage"] = msg;
 }
        private Entity GetRegardingObjectConfig(ILocalPluginContext context)
        {
            var approvalrequestid = context.PluginExecutionContext.PrimaryEntityId;


            var fetchXml = @"<fetch top='1'>" +
                           @"<entity name='fdbzap_ar_regardingconfig'>" +
                           @"<attribute name='fdbzap_ar_entitytype' />" +
                           @"<attribute name='fdbzap_ar_completedon_fieldname' />" +
                           @"<attribute name='fdbzap_ar_lastupdatedon_fieldname' />" +
                           @"<attribute name='fdbzap_ar_status_fieldname' />" +
                           @"<link-entity name='fdbzap_ar_approvalrequest' from='fdbzap_ar_regarding_config' to='fdbzap_ar_regardingconfigid' link-type='inner'>" +
                           @"<filter>" +
                           $@"<condition attribute='fdbzap_ar_approvalrequestid' operator='eq' value='{approvalrequestid}'/>" +
                           @"</filter></link-entity></entity></fetch>";


            var response = context.OrganizationService.RetrieveMultiple(new FetchExpression(fetchXml));

            if (response == null || response.Entities.Count < 1)
            {
                return(null);
            }

            return(response.Entities[0]);
        }
        public override void Execute(ILocalPluginContext localContext)
        {
            localContext.Trace("Entered AutoNumberPlugin");

            var organizationService = localContext.OrganizationService;

            localContext.Trace("Exiting AutoNumberPlugin");
        }
Esempio n. 12
0
        private Guid?GetTaskId(ILocalPluginContext context, string body, EntityReference sender)
        {
            if (body.IndexOf("completed", StringComparison.InvariantCultureIgnoreCase) == -1)
            {
                // no completed tag
                return(null);
            }

            if (body.IndexOf("#TSK", StringComparison.InvariantCulture) == -1)
            {
                // no task tag
                return(null);
            }

            if (Regex.IsMatch(body, "^[ \r\n\t]*<"))
            {
                // treat as html
                body = Html2Text(body);
            }

            if (!Regex.IsMatch(body, "^[ \r\n\t]*completed", RegexOptions.IgnoreCase))
            {
                // completed is not at start, so stop processing email.
                return(null);
            }

            string taskidStr;

            try
            {
                taskidStr = Regex.Match(body, "#TSK-(?<taskid>...........-...........)#", RegexOptions.IgnoreCase)
                            .Groups["taskid"].Value;
            }
            catch
            {
                // Syntax error in the regular expression
                return(null);
            }

            if (String.IsNullOrEmpty(taskidStr))
            {
                // no id to handle
                return(null);
            }

            var taskid = Utilities.DecompressGuid(taskidStr);

            var fetch = @"<fetch top='1'><entity name='task'><attribute name='activityid'/><filter>" +
                        $"<condition attribute='ownerid' operator='eq' value='${sender.Id}'/>" +
                        $"<condition attribute='activityid' operator='eq' value='${taskid}'/>" +
                        @"</filter></entity></fetch>";

            var tasks = context.OrganizationService.RetrieveMultiple(new FetchExpression(fetch));

            // return result
            return(tasks == null || tasks.Entities.Count != 1 ? (Guid?)null : tasks[0].Id);
        }
Esempio n. 13
0
        public override void Execute(ILocalPluginContext localContext)
        {
            var serviceContext = new ScantegraServiceContext(localContext.OrganizationService);
            var settings       = serviceContext.scan_scantegrasettingsSet.ToList();

            if (settings.Count() > 0)
            {
                throw new InvalidPluginExecutionException("Only one finance settings entity allowed");
            }
        }
        /// <summary>
        ///     Get the target entity reference.
        /// </summary>
        /// <param name="context">
        ///     The context.
        /// </param>
        /// <returns>
        ///     The <see cref="EntityReference" /> target.
        /// </returns>
        /// <exception cref="InvalidPluginExecutionException">
        /// </exception>
        public static EntityReference GetTargetEntityReference(ILocalPluginContext context)
        {
            if (!context.PluginExecutionContext.InputParameters.ContainsKey("Target") ||
                !(context.PluginExecutionContext.InputParameters["Target"] is EntityReference target))
            { // this should not be possible.
                throw ErrorCode.Exception(ErrorCodes.NullTarget);
            }

            return(target);
        }
        private static void UpdateRegardingObject(ILocalPluginContext context, Entity config, EntityReference regarding, Entity approval)
        {
            var isChildApprovalRequest = approval.GetAttributeValue <EntityReference>("fdbzap_ar_parentid") != null;
            var entityType             = config.GetAttributeValue <string>("fdbzap_ar_entitytype");

            // validate entity type if specified
            if (!string.IsNullOrEmpty(entityType) && !entityType.Equals(regarding.LogicalName, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException(ResponseMessages.RegardingConfigMismatch);
            }

            Entity target = new Entity(regarding.LogicalName), action = null;

            target.Id = regarding.Id;

            var lastaction = approval.GetAttributeValue <DateTime>("fdbzap_ar_actiontakenon");
            var actionRef  = approval.GetAttributeValue <EntityReference>("fdbzap_ar_actiontaken");

            if (actionRef != null)
            {
                action = context.OrganizationService.Retrieve(actionRef.LogicalName, actionRef.Id, new ColumnSet("fdbzap_ar_actiontype", "fdbzap_ar_name"));
            }

            var completedon = config.GetAttributeValue <string>("fdbzap_ar_completedon_fieldname");

            if (!isChildApprovalRequest && !string.IsNullOrEmpty(completedon) && action != null)
            {
                var actionType = action.GetAttributeValue <OptionSetValue>("fdbzap_ar_actiontype");
                if (actionType != null)
                {
                    var aval = actionType.Value - 741210000 /* solution prefix */;
                    if (aval == 0 || aval == 2 || aval == 4) /* Approve, Concur, Acknowledge */
                    {
                        target[completedon] = lastaction;
                    }
                }
            }

            var modifiedon = config.GetAttributeValue <string>("fdbzap_ar_lastupdatedon_fieldname");

            if (!string.IsNullOrEmpty(modifiedon))
            {
                target[modifiedon] = lastaction;
            }

            var statusfield = config.GetAttributeValue <string>("fdbzap_ar_status_fieldname");

            if (!isChildApprovalRequest && !string.IsNullOrEmpty(statusfield) && action != null)
            {
                var actionName = action.GetAttributeValue <string>("fdbzap_ar_name");
                target[statusfield] = actionName;
            }

            context.OrganizationService.Update(target);
        }
        /// <summary>
        ///     Updates the action taken for the approval request.
        /// </summary>
        /// <param name="context">
        ///     The local plugin context.
        /// </param>
        /// <param name="target">
        ///     The target (approval request).
        /// </param>
        /// <param name="action">
        ///     The action (taken).
        /// </param>
        private static void ActionTaken(ILocalPluginContext context, EntityReference target, Entity action)
        {
            if (target != null)
            {
                var request = new OrganizationRequest("fdbzap_ar_update_regardingobject");
                request.Parameters.Add("Target", target);
                context.OrganizationService.Execute(request);
            }

            context.PluginExecutionContext.OutputParameters["ActionTaken"] = action.ToEntityReference();
        }
Esempio n. 17
0
        /// <summary>
        ///     Execute the plugin action
        /// </summary>
        /// <param name="context">
        ///     The local plugin context.
        /// </param>
        public override void Execute(ILocalPluginContext context)
        {
            // Get Input
            var groupName = context.GetInputParameter <string>("groupName");
            var ec        = context.GetInputParameter <EntityCollection>("items");

            // Validate Items
            if (ec == null || ec.Entities.Count == 0)
            {
                Fail(context, "No items were selected.  Please make a selection before creating the group.");
                return;
            }

            // Build Entity Reference Collections
            var emails = new EntityReferenceCollection(ec.Entities
                                                       .Where(i => i.LogicalName.Equals("email"))
                                                       .Select(i => i.ToEntityReference()).ToList());

            var letters = new EntityReferenceCollection(ec.Entities
                                                        .Where(i => i.LogicalName.Equals("letter"))
                                                        .Select(i => i.ToEntityReference()).ToList());

            // Validate Items
            if (emails.Count == 0 && letters.Count == 0)
            {
                Fail(context,
                     "No letters or emails were selected.  Only letters and emails can be grouped for response.");
                return;
            }

            // Create Group
            var group = new Entity("fdbzap_cor_group");

            group["fdbzap_name"] = groupName ?? "A New Group";
            group.Id             = context.OrganizationService.Create(group);

            // Associate Records

            // Associate the emails
            if (emails.Count > 0)
            {
                var emailRelationship = new Relationship("fdbzap_email_group");
                context.OrganizationService.Associate(group.LogicalName, group.Id, emailRelationship, emails);
            }

            // Associate the letters
            if (letters.Count > 0)
            {
                var emailRelationship = new Relationship("fdbzap_letter_group");
                context.OrganizationService.Associate(group.LogicalName, group.Id, emailRelationship, emails);
            }

            Done(context, group.ToEntityReference());
        }
        /// <summary>
        /// Execute the plugin action
        /// </summary>
        /// <param name="context">
        /// The local plugin context.
        /// </param>
        public override void Execute(ILocalPluginContext context)
        {
            // Step 1: Get Valid Target
            context.Trace("Step 1: Get Valid Target");
            var approvalRequestRef = GetTargetEntityReference(context);

            // Step 2: Update Target
            context.Trace("Step 2: Update Target");
            var approvalRequest = approvalRequestRef.ToEntity();

            approvalRequest["fdbzap_ar_import_actiongroup"] = null;
            context.OrganizationService.Update(approvalRequest);

            // Step 3: Get Action Group
            context.Trace("Step 3: Get Action Group");
            var actionGroup = context.GetInputParameter <EntityReference>("ApprovalActionGroup");

            // Step 4: Get Actions
            context.Trace("Step 4: Get Action Templates");
            var result = GetActionTemplates(context, actionGroup);

            if (!(result?.Entities.Count > 0))
            {
                return;
            }

            // Step 5: Loop Through Actions
            context.Trace("Step 5: Loop Through Action Templates");
            foreach (var actionTemplate in result.Entities)
            {
                context.OrganizationService.Create(CreateActionUsingTemplate(actionTemplate, approvalRequestRef));
            }

            // Step 6: Look for child approvals
            context.Trace("Step 6: Look for child approvals");
            var childresults = GetChildApprovalsThatInheritFromParent(context, approvalRequestRef);

            // Step 7: If there are child approvals, apply to inherited ones
            context.Trace("Step 7: Apply to inherited approvals");
            if (childresults != null && childresults.Entities.Count > 0)
            {
                foreach (var entity in childresults.Entities)
                {
                    var req = new OrganizationRequest("fdbzap_ar_applytemplategroup");
                    req.Parameters.Add("Target", entity.ToEntityReference());
                    req.Parameters.Add("ApprovalActionGroup", actionGroup);

                    context.OrganizationService.Execute(req);
                }
            }

            // COMPLETE
            context.Trace("Plugin Comptle.");
        }
Esempio n. 19
0
        private static void CompleteTask(ILocalPluginContext context, Guid taskid)
        {
            var task = new Entity("task")
            {
                Id             = taskid,
                ["statecode"]  = new OptionSetValue(1 /* Completed */),
                ["statuscode"] = new OptionSetValue(5 /* Completed */)
            };

            context.OrganizationService.Update(task);
        }
        /// <summary>
        /// This event handler uses the <see cref="IPluginWebRequestFactory"/> surfaced in
        /// localContext to generate and execute a GET request to download data from Google.
        /// The generated <see cref="IPluginWebRequest"/> provides basic error handling and
        /// returns a <see cref="IPluginWebResponse"/> object with headers and content. Because
        /// the plugin is based on <see cref="InstrumentedPluginBase"/>, the request will
        /// automatically use dependency telementry tracking which captures the duration of
        /// the request, and the statuscode in AppInsights.
        /// </summary>
        /// <param name="localContext"></param>
        private void EventHandler(ILocalPluginContext localContext)
        {
            using (var webRequest = localContext.CreateWebRequest(new Uri("http://www.google.com"), "Google"))
            {
                webRequest.Timeout = new TimeSpan(0, 0, 10); //change timeout from default 30 seconds to 10 seconds.

                var webResponse = webRequest.Get();          //get the response

                //log something to show it worked.
                localContext.Trace("Retrieved {0} bytes", webResponse.Content.Length);
            }
        }
Esempio n. 21
0
        /// <summary>
        ///     Update the approval request with the action that was taken.
        /// </summary>
        /// <param name="context">
        ///     The local plugin context.
        /// </param>
        /// <param name="approvalrequestReference">
        ///     The approval request <see cref="EntityReference" />.
        /// </param>
        /// <param name="actionTaken">
        ///     The action <see cref="EntityReference" />.
        /// </param>
        internal static void UpdateApprovalRequest(
            ILocalPluginContext context,
            EntityReference approvalrequestReference,
            EntityReference actionTaken)
        {
            var approvalrequest = approvalrequestReference.ToEntity();

            approvalrequest["fdbzap_ar_actiontaken"]   = actionTaken;
            approvalrequest["fdbzap_ar_actiontakenon"] = context.PluginExecutionContext.OperationCreatedOn;
            approvalrequest["statuscode"] = new OptionSetValue(4 /* Action Taken */);
            context.OrganizationService.Update(approvalrequest);
        }
        /// <summary>
        /// Execute the plugin action
        /// </summary>
        /// <param name="context">
        /// The local plugin context.
        /// </param>
        public override void Execute(ILocalPluginContext context)
        {
            // Product Backlog Item 139: Corerspondence Management
            // The plugin should verify that all child approvals are approved
            // or rejected to meet the minimum requirements, if it is and the
            // regarding object id is set, then it updates the current approval
            // request and runs the "fdbzap_ar_update_regardingobject" action on
            // the current approval request otherwise it runs the "fdbzap_ar_checkstatus"
            // action on the parent approval request.

            // This process is launched automatically by the fdbzap_ar_action PostUpdate.

            // Step 1: Get Regarding Object Config
            context.Trace($"Depth: {context.PluginExecutionContext.Depth}");
            context.Trace("Step 1");

            var appreqRef = context.GetInputParameter <EntityReference>("Target");

            if (appreqRef == null)
            {
                return;
            }

            var approval = context.OrganizationService.Retrieve(appreqRef.LogicalName, appreqRef.Id,
                                                                new ColumnSet("fdbzap_ar_parentid", "fdbzap_ar_actiontakenon",
                                                                              "fdbzap_ar_actiontaken", "fdbzap_ar_regardingobjectid", "fdbzap_ar_regardinggobjectentityname"));

            if (approval == null)
            {
                context.Trace("No Approval Request!");
                return;
            }

            // Step 2
            context.Trace("Step 2");
            var config = GetRegardingObjectConfig(context);

            if (config == null)
            {
                // nothing to do... no config
                context.Trace("Config not found.");
                return;
            }

            // Step 3: Get Regarding Object
            context.Trace("Step 3");
            var regarding = GetRegardingObject(approval);

            // Step 3: Update Regarding Object with changes.
            context.Trace("Step 3");
            UpdateRegardingObject(context, config, regarding, approval);
        }
        // Entry point for custom business logic execution
        protected override void ExecuteCdsPlugin(ILocalPluginContext localPluginContext)
        {
            if (localPluginContext == null)
            {
                throw new ArgumentNullException("localPluginContext");
            }

            IPluginExecutionContext context = localPluginContext.PluginExecutionContext;

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

                if (entity.LogicalName == "account")
                {
                    try
                    {
                        Entity followup = new Entity("task");

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

                        if (context.OutputParameters.Contains("id"))
                        {
                            Guid   regardingobjectid     = new Guid(context.OutputParameters["id"].ToString());
                            string regardingobjectidType = "account";

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

                        localPluginContext.Trace("FollowupPlugin: Creating the task activity.");
                        localPluginContext.CurrentUserService.Create(followup);
                    }

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

                    catch (Exception ex)
                    {
                        localPluginContext.Trace("FollowUpPlugin: " + ex.ToString());
                        throw;
                    }
                }
            }
        }
        // Override ConfigureTelemetrySink to include a new custom TelemetryProcessor
        public override bool ConfigureTelemetrySink(ILocalPluginContext localContext)
        {
            if (base.ConfigureTelemetrySink(localContext))
            {
                //Add our custom telemetry processor which will stamp each telemetry
                //item with datetime of when the sink was first configured.
                TelemetrySink.ProcessChain.TelemetryProcessors.Add(new Telemetry.CustomPluginPropertyProcessor("sink-config-time", DateTime.UtcNow.ToString()));

                return(true);
            }

            return(false); //telmetry sink is not configured.
        }
Esempio n. 25
0
        public override void Execute(ILocalPluginContext context)
        {
            // Try and access the file system - this isn't allowed in sandboxed plugin
            //var sw = new StreamWriter("C:\\test.txt");
            //sw.WriteLine("ouch");

            var account = context.OrganizationService.Retrieve("account", Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), new ColumnSet(true));

            var note = new Entity("annotation");

            note["description"] = "test";
            context.OrganizationService.Create(note);
        }
Esempio n. 26
0
        private static EntityReference GetSender(ILocalPluginContext context)
        {
            var             from   = context.GetAttributeValue <EntityCollection>("from");
            EntityReference sender = null;

            if (@from != null && @from.Entities.Count > 0)
            {
                var party = @from.Entities[0];
                sender = party.GetAttributeValue <EntityReference>("partyid");
            }

            return(sender);
        }
        /// <summary>
        /// Execute the plugin action
        /// </summary>
        /// <param name="context">
        /// The local plugin context.
        /// </param>
        public override void Execute(ILocalPluginContext context)
        {
            // Product Backlog Item 139
            // The plugin should verify that all child approvals are approved
            // or rejected to meet the minimum requirements, if it is and the
            // regarding object id is set, then it updates the current approval
            // request and runs the "fdbzap_ar_update_regardingobject" action on
            // the current approval request otherwise it runs the "fdbzap_ar_checkstatus"
            // action on the parent approval request.

            // Step 1: Configure Output Paramaters
            context.Trace($"Depth: {context.PluginExecutionContext.Depth}");
            context.Trace("Step 1");
            if (!context.PluginExecutionContext.OutputParameters.Keys.Contains("ActionTaken"))
            {
                context.PluginExecutionContext.OutputParameters.Add("ActionTaken", null);
            }

            // Step 2: Get Valid Target
            context.Trace("Step 2");
            var target = GetTargetEntityReference(context);

            // Step 3: Get Actions
            context.Trace("Step 3");
            var actions = GetActions(context, target);

            // Step 4: Check if there are actions to look at.
            context.Trace("Step 4");
            if (actions == null || actions.Entities.Count == 0)
            {
                return;
            }

            // Step 5: Check Action Rules
            context.Trace("Step 5");
            foreach (var action in actions.Entities)
            {
                // Rule 1: Min Action >= Count
                context.Trace("Rule 1");
                var minaction = action.GetAttributeValue <int>("fdbzap_ar_minaction");
                var count     = action.GetAttributeValue <int>("fdbzap_ar_actioncount");
                if (count >= minaction || actions.Entities.Count == 0)
                {
                    // Rule 1: Success
                    context.Trace("Rule 1 Success");
                    ActionTaken(context, target, action);
                    return; // End Processing of rules.
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Encrypts the value in the extention setting record if the encryption flag is set. Also
        /// prevents removing the encryption once it is applied.
        /// </summary>
        /// <param name="localContext"></param>
        private void ManageValueEncryption(ILocalPluginContext localContext)
        {
            var settings = Container.Resolve <IExtensionSettingsConfig>();

            if (localContext.PluginExecutionContext.MessageName == MessageNames.Update)
            {
                //validate preimage configuration
                if (localContext.PreImage == null)
                {
                    throw new Exception("Missing required preimage");
                }

                if (!localContext.PreImage.Contains(settings.EncryptionColumn))
                {
                    throw new Exception("Preimage is missing required encryption column.");
                }

                if (!localContext.PreImage.Contains(settings.ValueColumn))
                {
                    throw new Exception("Preimage is missing required value column.");
                }

                //if the record is already encrypted and the user is attempting to set to
                //unencrypted then block the update
                bool currentEncryptionStatus = localContext.PreImage.GetAttributeValue <bool>(settings.EncryptionColumn);
                if (currentEncryptionStatus && localContext.TargetEntity.Contains(settings.EncryptionColumn))
                {
                    throw new InvalidPluginExecutionException("Encryption cannot be removed once it has been applied.");
                }
            }

            Entity workingCopy = new Entity(localContext.TargetEntity.LogicalName, localContext.TargetEntity.Id);

            workingCopy.MergeWith(localContext.TargetEntity);

            //merge in any attributes from preimage that are not in the target entity.
            if (localContext.PluginExecutionContext.MessageName == MessageNames.Update)
            {
                workingCopy.MergeWith(localContext.PreImage);
            }

            //if the encrypted flag is set then encrypt the value on the way into storage.
            bool?encrypt = workingCopy.GetAttributeValue <bool?>(settings.EncryptionColumn);

            if (encrypt.HasValue && encrypt.Value)
            {
                var encryptor = Container.Resolve <IRijndaelEncryption>();
                localContext.TargetEntity[settings.ValueColumn] = encryptor.Encrypt(workingCopy[settings.ValueColumn] as string, settings.EncryptionKey);
            }
        }
        public override bool ConfigureTelemetrySink(ILocalPluginContext localContext)
        {
            var key = "7a6ecb67-6c9c-4640-81d2-80ce76c3ca34";

            if (!string.IsNullOrEmpty(key))
            {
                TelemetrySink.ProcessChain.TelemetryProcessors.Add(new SequencePropertyProcessor());
                TelemetrySink.ProcessChain.TelemetryProcessors.Add(new InstrumentationKeyPropertyProcessor(key));

                return(true); //telemetry sink is configured.
            }

            return(false);
        }
        /// <summary>
        /// Supports the Aliased Search Pattern. Examines query supplied in the plugin context query input.
        /// If query runs against an entity of type <typeparamref name="TParent"/> the generator will
        /// modify the queary to incldue any matching records found in the the related alias table
        /// defined by <typeparamref name="TAlias"/>.
        /// </summary>
        public AliasedSearchQueryGenerator(ILocalPluginContext localContext)
        {
            this.localContext = localContext;

            TParent parent = new TParent();

            parentEntityName      = parent.LogicalName;
            parentIdAttributeName = parent.LogicalName + "id";

            TAlias alias = new TAlias();

            aliasEntityName = alias.LogicalName;

            linkingAttributeName = parentIdAttributeName;
        }
Esempio n. 31
0
        private static EntityCollection GetAttachments(ILocalPluginContext context)
        {
            var mfetch = @"<fetch top='100'><entity name='activitymimeattachment'>" +
                         @"<attribute name='body'/>" +
                         @"<attribute name='filename'/>" +
                         @"<attribute name='filesize'/>" +
                         @"<attribute name='mimetype'/>" +
                         @"<filter>" +
                         $"<condition attribute='activityid' operator='eq' value='${context.PluginExecutionContext.PrimaryEntityId}'/>" +
                         @"</filter></entity></fetch>";

            var attachments = context.OrganizationService.RetrieveMultiple(new FetchExpression(mfetch));

            return(attachments);
        }
 public abstract void Execute(ILocalPluginContext localContext);