Beispiel #1
0
        public override void Execute(JonasPluginBag bag)
        {
            if (bag.PluginContext.ParentContext == null)
            {
                bag.Trace("No parent, manual update is allowed.");
                return;
            }
            if (bag.PluginContext.ParentContext.PrimaryEntityName != "account")
            {
                bag.Trace("Did not originate from Account, we're good.");
                return;
            }
            var newstate = bag.TargetEntity.GetAttributeValue <string>("address1_stateorprovince") ?? string.Empty;

            bag.Trace("New state: {0}", newstate);
            var oldstate = bag.PreImage?.GetAttributeValue <string>("address1_stateorprovince") ?? string.Empty;

            bag.Trace("Old state: {0}", oldstate);
            if (!newstate.Equals(oldstate) && !oldstate.Equals(string.Empty))
            {
                var contactname = bag.CompleteEntity.Name(bag, false);
                throw new InvalidPluginExecutionException($"Automatic update of State is not allowed. {contactname} must be updated manually to handle this.");
            }
            bag.Trace("State does not appear to have been changed :)");
        }
Beispiel #2
0
        public override void Execute(JonasPluginBag bag)
        {
            var pcref = bag.TargetEntity.GetAttributeValue <EntityReference>("primarycontactid");

            if (pcref == null || pcref.Id.Equals(Guid.Empty))
            {
                bag.Trace("PC is null");
                return;
            }
#if DEBUG
            // This will enable extensive details about requests and results when compiling with debug configuration
            bag.TracingService.Verbose = true;
#endif
            bag.TraceBlockStart("Check other accounts");
            bag.Trace("Looking for other accounts with Primary Contact {0}", pcref.Id);
            var qry = new QueryExpression("account");
            qry.ColumnSet.AddColumn("name");
            qry.Criteria.AddCondition("accountid", ConditionOperator.NotEqual, bag.PluginContext.PrimaryEntityId);
            qry.Criteria.AddCondition("primarycontactid", ConditionOperator.Equal, pcref.Id);
            var otheraccounts = bag.Service.RetrieveMultiple(qry);
            bag.TraceBlockEnd();
            if (otheraccounts.Entities.Count > 0)
            {
                bag.TraceBlockStart("Throwing up");
                var acctnames = string.Join(", ", otheraccounts.Entities.Select(e => e.GetAttributeValue <string>("name") ?? "?"));
                bag.Trace("Other account(s): {0}", acctnames);
                var contact = bag.Service.Retrieve("contact", pcref.Id, new ColumnSet("fullname"));
                throw new InvalidPluginExecutionException($"{contact.Name(bag, false)} is already primary contact for account(s) :\n{acctnames}");
                bag.TraceBlockEnd();
            }
        }
Beispiel #3
0
        public override void Execute(JonasPluginBag bag)
        {
            if (!bag.PluginContext.ContactTriggered())
            {
                bag.Trace("Context not satisfying");
                return;
            }
            var accountid = bag.TargetEntity.GetAccountIdFromContact();

            bag.Trace("Accountid from target: {0}", accountid);
            if (accountid.Equals(Guid.Empty))
            {
                accountid = bag.PostImage.GetAccountIdFromContact();
                bag.Trace("Accountid from postimage: {0}", accountid);
            }
            if (!accountid.Equals(Guid.Empty))
            {
                bag.AccountUpdateStats(accountid);
            }
            var preaccountid = bag.PreImage.GetAccountIdFromContact();

            bag.Trace("Accountid from preimage: {0}", preaccountid);
            if (!preaccountid.Equals(Guid.Empty) && !preaccountid.Equals(accountid))
            {
                bag.AccountUpdateStats(preaccountid);
            }
        }
Beispiel #4
0
        public override void Execute(JonasPluginBag bag)
        {
            var error = GetCodeActivityParameter(Error);
            var code  = GetCodeActivityParameter(Code);

            throw new InvalidPluginExecutionException(OperationStatus.Failed, code, error);
        }
Beispiel #5
0
 public override void Execute(JonasPluginBag bag)
 {
     if (bag.TargetEntity == null)
     {
         bag.Trace("No target entity - nothing to do.");
         return;
     }
     VerifyFaxNotUsed(bag);
 }
        public override void Execute(JonasPluginBag bag)
        {
            var mobilephone = bag.CompleteEntity.GetAttributeValue <string>("mobilephone") ?? string.Empty;

            bag.Trace("Mobilephone was: {0}", mobilephone);
            mobilephone = mobilephone.PadRight(500, '.');
            bag.Trace("Setting mobilephone={0}", mobilephone);
            bag.TargetEntity["mobilephone"] = mobilephone;
        }
Beispiel #7
0
        public override void Execute(JonasPluginBag bag)
        {
            var s = GetCodeActivityParameter(SomeString);

            bag.Trace("SomeString: {0}", s);
            var n = GetCodeActivityParameter(SomeNumber);

            bag.Trace("SomeNumber: {0}", n);

            bag.Trace("CompleteEntity:\n{0}", bag.CompleteEntity.ExtractAttributes(null));

            SetCodeActivityParameter(ResultingUser, new EntityReference("systemuser", bag.WorkflowContext.UserId));
        }
Beispiel #8
0
        public override void Execute(JonasPluginBag bag)
        {
            var jonas = (WhoAmIResponse)bag.Service.Execute(new WhoAmIRequest());

            bag.Trace("I am: {0}", jonas.UserId);

            var    entity = bag.TargetEntity;
            string name   = entity.Name(bag, true);

            bag.Trace("Triggered by record: {0}", name);

            bag.Trace("I'm done now: {0}", DateTime.Now);
        }
 public static Entity GetParent(this Entity entity, JonasPluginBag bag, string lookupattribute, params string[] attributes)
 {
     if (!entity.Contains(lookupattribute))
     {
         bag.Trace($"Missing lookup attribute {lookupattribute}");
         return(null);
     }
     if (!(entity[lookupattribute] is EntityReference parentref))
     {
         bag.Trace($"{lookupattribute} is not EntityReference");
         return(null);
     }
     return(bag.Service.Retrieve(parentref.LogicalName, parentref.Id, new ColumnSet(attributes)));
 }
Beispiel #10
0
        public override void Execute(JonasPluginBag bag)
        {
            try
            {
                if (bag.PluginContext.MessageName != "RetrieveMultiple" || bag.PluginContext.Stage != 20 || bag.PluginContext.Mode != 0 ||
                    !bag.PluginContext.InputParameters.Contains("Query"))
                {
                    bag.Trace("Not expected context");
                    return;
                }

                if (bag.PluginContext.InputParameters["Query"] is QueryExpression query)
                {
                    bag.trace("Checking QueryExpression");
#if DEBUG
                    var fetch1 = ((QueryExpressionToFetchXmlResponse)bag.Service.Execute(new QueryExpressionToFetchXmlRequest()
                    {
                        Query = query
                    })).FetchXml;
                    bag.Trace($"Query before:\n{fetch1}");
#endif
                    if (query.ReplaceRegardingCondition(bag, distinct))
                    {
#if DEBUG
                        var fetch2 = ((QueryExpressionToFetchXmlResponse)bag.Service.Execute(new QueryExpressionToFetchXmlRequest()
                        {
                            Query = query
                        })).FetchXml;
                        bag.Trace($"Query after:\n{fetch2}");
#endif
                        bag.PluginContext.InputParameters["Query"] = query;
                    }
                }
                else if (bag.PluginContext.InputParameters["Query"] is FetchExpression fetch)
                {
                    bag.trace("Checking FetchExpression");
                    bag.Trace($"Query before:\n{fetch.Query}");
                    if (fetch.ReplaceRegardingCondition(bag, distinct))
                    {
                        bag.Trace($"Query after:\n{fetch.Query}");
                        bag.PluginContext.InputParameters["Query"] = fetch;
                    }
                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Beispiel #11
0
        public override void Execute(JonasPluginBag bag)
        {
            // Read updated value for Fax from Target entity
            string fax = bag.TargetEntity.GetAttributeValue <string>("fax");

            if (!string.IsNullOrWhiteSpace(fax))
            {
                throw new InvalidPluginExecutionException($"Fax? Really? This is {DateTime.Now.Year}, you know... ");
            }

            // Get name of the record that triggered the plugin
            string recordName = bag.CompleteEntity.Name(bag, false);

            bag.Trace("No fax for {0}, this {1} is ready for the future.", recordName, bag.PluginContext.PrimaryEntityName);
        }
Beispiel #12
0
 // Update contacts with the address information of the account that triggered the plugin
 private static void UpdateContacts(JonasPluginBag bag, EntityCollection contacts)
 {
     bag.TraceBlockStart();
     foreach (var contact in contacts.Entities)
     {
         bag.TraceBlockStart($"Updating contact: {contact.Name(bag, false)}");
         foreach (var attr in addressAttributes)
         {
             UpdateAttribute(bag, contact, attr);
         }
         bag.Service.Update(contact);
         bag.TraceBlockEnd();
     }
     bag.TraceBlockEnd();
 }
Beispiel #13
0
        public override void Execute(JonasPluginBag bag)
        {
            var json  = bag.PluginContext.GetInputParameterForgiving <string>("SomeJSON");
            var extra = bag.PluginContext.GetInputParameterForgiving <bool>("ExtraMagic");

            if (string.IsNullOrWhiteSpace(json))
            {
                bag.PluginContext.OutputParameters.AddOrUpdateIfNotNull("ErrorCode", 1);
                bag.PluginContext.OutputParameters.AddOrUpdateIfNotNull("ErrorMessage", "JSON is empty");
                return;
            }
            var result = json.DoTheFancyMagicStuff(extra);

            bag.PluginContext.OutputParameters.AddOrUpdateIfNotNull("ResultJSON", result);
        }
Beispiel #14
0
        public static bool ReplaceRegardingCondition(this FetchExpression fetch, JonasPluginBag bag, bool makeDistinct)
        {
            bag.TraceBlockStart();
            var query = (bag.Service.Execute(new FetchXmlToQueryExpressionRequest {
                FetchXml = fetch.Query
            }) as FetchXmlToQueryExpressionResponse)?.Query;

            if (query.ReplaceRegardingCondition(bag, makeDistinct))
            {
                fetch.Query = (bag.Service.Execute(new QueryExpressionToFetchXmlRequest {
                    Query = query
                }) as QueryExpressionToFetchXmlResponse)?.FetchXml;
                return(true);
            }
            bag.TraceBlockEnd();
            return(false);
        }
        public override void Execute(JonasPluginBag bag)
        {
            if (bag == null)
            {
                throw new ArgumentNullException(nameof(bag));
            }

            bag.Trace("Hello world");

            if (bag.PluginContext.PrimaryEntityName != "contact")
            {
                bag.Trace($"Triggered incorrectly for {bag.PluginContext.PrimaryEntityName}");
                return;
            }
            bag.TraceBlockStart("Checking images");
            bag.Trace($"PreImage count: {bag.PluginContext.PreEntityImages.Count}");
            bag.Trace($"PostImage count: {bag.PluginContext.PostEntityImages.Count}");
            bag.TraceBlockEnd();
            if (!(bag.PostImage is Entity contact))
            {
                return;
            }
            bag.TraceBlockStart("Doing the things");
            bag.Trace($"Entity is {contact.LogicalName} {contact.Id}");

            if (!(contact.GetParent(bag, Contact.CompanyName, Account.PrimaryName, Account.AccountNumber) is Entity account))
            {
                return;
            }
            bag.Trace($"Parent is {account.LogicalName} {account[Account.PrimaryName]}");

            var cases = account.GetChildren(bag, Case.EntityName, Case.Customer, Case.Subject, Case.CaseNumber);

            bag.Trace($"Found {cases.Count()} cases: {string.Join(", ", cases.Select(c => c[Case.CaseNumber]))}");

            bag.TraceBlockStart("Looping cases");
            foreach (var acase in cases)
            {
                acase[Case.Description]  = null;
                acase[Case.Satisfaction] = new OptionSetValue((int)Case.Satisfaction_OptionSet.VerySatisfied);
                acase.Save(bag);
            }
            bag.TraceBlockEnd();
            bag.TraceBlockEnd();
        }
Beispiel #16
0
        private static void UpdateAttribute(JonasPluginBag bag, Entity contact, string attr)
        {
            bag.TraceBlockStart($"Checking: {attr}");
            var newvalue = bag.CompleteEntity.GetAttributeValue <string>(attr) ?? string.Empty;
            var oldvalue = contact.GetAttributeValue <string>(attr) ?? string.Empty;

            if (!oldvalue.Equals(newvalue))
            {
                bag.Trace("Setting {0} = {1}", attr, newvalue);
                contact[attr] = newvalue.Equals(string.Empty) ? null : newvalue;
            }
            else if (contact.Contains(attr))
            {
                bag.Trace("Attribute {0} not changed, removing from entity to update", attr);
                contact.Attributes.Remove(attr);
            }
            bag.TraceBlockEnd();
        }
        internal static void AccountUpdateStats(this JonasPluginBag bag, Guid accountid)
        {
            var fetchexpr = new FetchExpression(string.Format(fetch, accountid));
            var results   = bag.Service.RetrieveMultiple(fetchexpr);

            var descr = new StringBuilder();

            foreach (var familystatus in results.Entities)
            {
                var status = bag.GetOptionsetLabel("contact", "familystatuscode", (int)familystatus.AttributeToBaseType("Status"));
                var count  = familystatus.AttributeToBaseType("Count");
                descr.AppendLine($"{count} {status}");
            }
            bag.Trace("Description:\n{0}", descr.ToString().Trim());
            var account = new Entity("account", accountid);

            account["description"] = descr.ToString();
            bag.Service.Update(account);
        }
Beispiel #18
0
        public override void Execute(JonasPluginBag bag)
        {
            if (!bag.PluginContext.PrimaryEntityName.Equals("account"))
            {
                bag.Trace("Expected entity account, got {0}", bag.PluginContext.PrimaryEntityName);
                return;
            }
            if (!bag.PluginContext.MessageName.Equals("Update"))
            {
                bag.Trace("Expected Update message, got {0}", bag.PluginContext.MessageName);
                return;
            }
#if DEBUG
            // This will enable extensive details about requests and results when compiling with debug configuration
            bag.TracingService.Verbose = true;
#endif
            var contacts = GetContactsInheritingAddress(bag);
            UpdateContacts(bag, contacts);
        }
Beispiel #19
0
        public static Guid Save(this Entity entity, JonasPluginBag bag)
        {
            var result = entity.Id;
            var sw     = Stopwatch.StartNew();

            if (entity.Id.Equals(Guid.Empty))
            {
                bag.Trace("Saving entity");
                result = bag.Service.Create(entity);
            }
            else
            {
                bag.Trace("Updating entity");
                bag.Service.Update(entity);
            }
            sw.Stop();
            bag.Trace($"Saved record in {sw.ElapsedMilliseconds} ms");
            return(result);
        }
Beispiel #20
0
 private static void VerifyFaxNotUsed(JonasPluginBag bag)
 {
     if (!bag.TargetEntity.Contains("fax"))
     {
         if (bag.PostImage != null && bag.PostImage.Contains("fax"))
         {
             throw new InvalidPluginExecutionException("You really should remove Fax no before continuing");
         }
         bag.Trace("Fax was not touched, keep moving.");
         return;
     }
     if (!string.IsNullOrEmpty(bag.TargetEntity["fax"].ToString()))
     {
         throw new InvalidPluginExecutionException("Fax?? Get outta here!");
     }
     else
     {
         bag.Trace("Clearing fax - welcome to the future!");
     }
 }
        public override void Execute(JonasPluginBag bag)
        {
            var length  = GetCodeActivityParameter <int>(Length);
            var charset = GetCodeActivityParameter <string>(CharacterSet);

            bag.Trace("Generating random text with {0} characters from {1}", length, charset);

            var result = new StringBuilder();

            while (result.Length < length)
            {
                var pos = random.Next(charset.Length);
                bag.Trace("Got random position: {0}", pos);
                var chr = charset[pos];
                bag.Trace("That is character:   {0}", chr);
                result.Append(chr);
            }
            SetCodeActivityParameter <string>(RandomText, result.ToString());
            bag.Trace("Returning: {0}", result);
        }
Beispiel #22
0
        // Retrieve all contacts of the triggering account, that have the old address of the account or no address at all.
        private static EntityCollection GetContactsInheritingAddress(JonasPluginBag bag)
        {
            bag.TraceBlockStart();
            var qry = new QueryExpression("contact");

            qry.ColumnSet.AddColumn("fullname");
            qry.ColumnSet.AddColumns(addressAttributes.ToArray());

            qry.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, bag.PluginContext.PrimaryEntityId);

            var fltAddress     = qry.Criteria.AddFilter(LogicalOperator.Or);
            var fltNoAddress   = fltAddress.AddFilter(LogicalOperator.And);
            var fltSameAddress = fltAddress.AddFilter(LogicalOperator.And);

            foreach (var attr in addressAttributes)
            {
                fltNoAddress.AddCondition(attr, ConditionOperator.Null);
            }

            foreach (var attr in addressAttributes)
            {
                var prevalue = bag.PreImage.GetAttributeValue <string>(attr);
                bag.Trace("Adding filter for {0} = {1}", attr, prevalue);
                if (prevalue == null)
                {
                    fltSameAddress.AddCondition(attr, ConditionOperator.Null);
                }
                else
                {
                    fltSameAddress.AddCondition(attr, ConditionOperator.Equal, prevalue);
                }
            }
            var contacts = bag.Service.RetrieveMultiple(qry);

            bag.TraceBlockEnd();
            return(contacts);
        }
Beispiel #23
0
        public static bool ReplaceRegardingCondition(this QueryExpression query, JonasPluginBag bag, bool makeDistinct)
        {
            bag.TraceBlockStart();
            if (query.EntityName != "activitypointer")
            {
                bag.Trace($"Wrong entity: {query.EntityName}");
                bag.TraceBlockEnd();
                return(false);
            }
            var nullCondition = query.GetCondition("activityid", ConditionOperator.Null, bag.TracingService);

            if (nullCondition == null)
            {
                bag.Trace("No null condition for activityid");
                bag.TraceBlockEnd();
                return(false);
            }
            Guid contactId;
            var  regardingCondition = query.GetCondition("regardingobjectid", ConditionOperator.Equal, bag.TracingService);

            if (regardingCondition != null &&
                regardingCondition.Operator.Equals(ConditionOperator.Equal) &&
                regardingCondition.Values.Count == 1 &&
                regardingCondition.Values[0] is Guid regardingConditionId)
            {
                contactId = regardingConditionId;
                query.RemoveCondition(regardingCondition, bag.TracingService);
            }
            else
            {
                bag.Trace("No condition for regardingobjectid");
                var contactCondition = query.GetCondition("contactid", ConditionOperator.Equal, bag.TracingService);
                if (contactCondition != null &&
                    contactCondition.Operator.Equals(ConditionOperator.Equal) &&
                    contactCondition.Values.Count == 1 &&
                    contactCondition.Values[0] is Guid contactConditionId)
                {
                    contactId = contactConditionId;
                    query.RemoveCondition(contactCondition, bag.TracingService);
                }
                else
                {
                    bag.Trace("No condition for contactid");
                    bag.TraceBlockEnd();
                    return(false);
                }
            }
            if (contactId.Equals(Guid.Empty))
            {
                bag.Trace("No contactid identified in query");
                bag.TraceBlockEnd();
                return(false);
            }

            query.RemoveCondition(nullCondition, bag.TracingService);

            bag.Trace("Adding link-entity and condition for activity party");
            var leActivityparty = query.AddLink("activityparty", "activityid", "activityid");

            leActivityparty.LinkCriteria.AddCondition("partyid", ConditionOperator.Equal, contactId);

            if (makeDistinct)
            {
                query.Distinct = true;
            }
            bag.TraceBlockEnd();
            return(true);
        }
Beispiel #24
0
 public override void Execute(JonasPluginBag bag)
 {
     // noop
 }
Beispiel #25
0
        public static IEnumerable <Entity> GetChildren(this Entity entity, JonasPluginBag bag, string childname, string lookupattribute, params string[] attributes)
        {
            var qx = QueryExpressionFactory.Create(childname, true, new ColumnSet(attributes), false, new object[] { lookupattribute, entity.Id });

            return(bag.Service.RetrieveMultiple(qx).Entities);
        }