Exemple #1
0
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            QueryResult queryResult = ExecuteQueryForRecords(context);

            Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest metadataRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                LogicalName = workflowContext.PrimaryEntityName, EntityFilters = EntityFilters.Relationships
            };
            var metadataResponse = service.Execute(metadataRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
            var relationship     = metadataResponse.EntityMetadata.ManyToManyRelationships.FirstOrDefault(m =>
                                                                                                          m.SchemaName.Equals(RelationshipName.Get(context), StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                          m.IntersectEntityName.Equals(RelationshipName.Get(context), StringComparison.InvariantCultureIgnoreCase));

            if (relationship == null)
            {
                throw new Exception($"Entity '{workflowContext.PrimaryEntityName}' does not have relationship with schema name or relationship entity name '{RelationshipName.Get(context)}'");
            }

            QueryExpression qe = new QueryExpression(relationship.IntersectEntityName);

            qe.Criteria.AddCondition(relationship.Entity1IntersectAttribute, ConditionOperator.Equal, workflowContext.PrimaryEntityId);
            qe.ColumnSet = new ColumnSet(relationship.Entity2IntersectAttribute);
            var alreadyAssociated = service.RetrieveMultiple(qe).Entities.Select(e => (Guid)e[relationship.Entity2IntersectAttribute]);

            var delta = queryResult.RecordIds.Except(alreadyAssociated).Select(id => new EntityReference(relationship.Entity2LogicalName, id)).ToList();

            service.Associate(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId, new Relationship(relationship.SchemaName), new EntityReferenceCollection(delta));

            NumberOfRelationshipChanges.Set(context, delta.Count);
        }
        public static EntityReference RetrieveWorkflowRecordOwner(IWorkflowContext workflowContext, IOrganizationService service)
        {
            EntityReference       recordOwner = null;
            RetrieveEntityRequest request     = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName   = workflowContext.PrimaryEntityName
            };

            RetrieveEntityResponse  metadataResponse = service.Execute(request) as RetrieveEntityResponse;
            LookupAttributeMetadata ownerAttribute   = metadataResponse.EntityMetadata.Attributes.FirstOrDefault(att => att.AttributeType != null && (int)att.AttributeType.Value == 9) as LookupAttributeMetadata;

            if (ownerAttribute != null)
            {
                Entity entity = workflowContext.PostEntityImages.Values.FirstOrDefault();
                if (entity == null)
                {
                    entity = workflowContext.PreEntityImages.Values.FirstOrDefault();
                    if (entity == null)
                    {
                        entity = service.Retrieve(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId, new ColumnSet(ownerAttribute.LogicalName));
                    }
                }

                if (entity != null && entity.Contains(ownerAttribute.LogicalName))
                {
                    recordOwner = entity[ownerAttribute.LogicalName] as EntityReference;
                }
            }

            return(recordOwner);
        }
Exemple #3
0
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            QueryResult result = ExecuteQueryForRecords(context);

            if (!result.EntityName.Equals("systemuser", StringComparison.InvariantCultureIgnoreCase) &&
                !result.EntityName.Equals("team", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Query must return a User or Team record");
            }

            // Ensure the record has an owner field
            RetrieveEntityRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity,
                LogicalName   = workflowContext.PrimaryEntityName
            };
            RetrieveEntityResponse metadataResponse = service.Execute(request) as RetrieveEntityResponse;

            if (metadataResponse.EntityMetadata.OwnershipType == null || metadataResponse.EntityMetadata.OwnershipType.Value != OwnershipTypes.UserOwned)
            {
                throw new ArgumentException("This activity is only available for User owned records");
            }

            if (!result.RecordIds.Any())
            {
                return;
            }

            var           workflowRecord = new EntityReference(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId);
            var           assignee       = new EntityReference(result.EntityName, result.RecordIds.FirstOrDefault());
            AssignRequest assignRequest  = new AssignRequest()
            {
                Assignee = assignee,
                Target   = workflowRecord
            };

            try
            {
                AssignResponse response = service.Execute(assignRequest) as AssignResponse;
                if (assignee.LogicalName.Equals("team"))
                {
                    this.NewOwner_Team.Set(context, assignee);
                }
                else
                {
                    this.NewOwner_User.Set(context, assignee);
                }
                this.RecordReassigned.Set(context, true);
            }
            catch (Exception ex)
            {
                throw new Exception($"There was an error reassigning the record: {ex.Message}");
            }
        }
        protected void LimitQueryToCurrentRecord(IOrganizationService service, ref string fetchXml, string entityName, Guid entityId)
        {
            Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest metadataRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                LogicalName = entityName
            };
            Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse metadataResponse = service.Execute(metadataRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
            if (metadataResponse == null)
            {
                return;
            }

            XmlDocument fetchXmlDoc = new XmlDocument();

            fetchXmlDoc.LoadXml(fetchXml);
            this.UpdateConditionRecursively(fetchXmlDoc, fetchXmlDoc.FirstChild, entityId, entityName, metadataResponse.EntityMetadata.PrimaryIdAttribute);
            fetchXml = fetchXmlDoc.OuterXml;
        }
        protected List <ColumnInformation> BuildTableInformation(IOrganizationService service, string fetchXml, string layoutXml)
        {
            List <QueryAttribute> fetchXmlColumns = new List <QueryAttribute>();
            XmlDocument           doc             = new XmlDocument();

            doc.LoadXml(fetchXml);
            XmlNode entityNode = doc["fetch"]["entity"];

            string primaryEntity = entityNode.Attributes["name"].Value;

            this.RetrieveQueryAttributeRecursively(entityNode, fetchXmlColumns);

            List <QueryAttribute> layoutXmlColumns = new List <QueryAttribute>();

            if (!String.IsNullOrEmpty(layoutXml))
            {
                doc = new XmlDocument();
                doc.LoadXml(layoutXml);
                foreach (XmlNode cell in doc["grid"]["row"].ChildNodes)
                {
                    string columnPresentationValue = cell.Attributes["name"].Value;
                    if (columnPresentationValue.Contains("."))
                    {
                        layoutXmlColumns.Add(new QueryAttribute()
                        {
                            EntityAlias = columnPresentationValue.Split('.')[0],
                            Attribute   = columnPresentationValue.Split('.')[1]
                        });
                    }
                    else
                    {
                        layoutXmlColumns.Add(new QueryAttribute()
                        {
                            Attribute = columnPresentationValue, EntityName = primaryEntity
                        });
                    }
                }
                foreach (QueryAttribute attribute in layoutXmlColumns.Where(qa => !String.IsNullOrWhiteSpace(qa.EntityAlias)))
                {
                    QueryAttribute attributeFromFetch = fetchXmlColumns.FirstOrDefault(f => f.EntityAlias == attribute.EntityAlias);
                    if (attributeFromFetch != null)
                    {
                        attribute.EntityName = attributeFromFetch.EntityName;
                    }
                }
            }

            List <string> distintEntityNames = layoutXmlColumns.Select(lo => lo.EntityName).Union(fetchXmlColumns.Select(f => f.EntityName)).Distinct().ToList();

            foreach (string entityName in distintEntityNames)
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
                {
                    EntityFilters = EntityFilters.Attributes,
                    LogicalName   = entityName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse response = service.Execute(request) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
                EntityMetadata metadata = response.EntityMetadata;
                foreach (QueryAttribute queryAttribute in layoutXmlColumns.Union(fetchXmlColumns).Where(c => c.EntityName == entityName && !String.IsNullOrWhiteSpace(c.Attribute)))
                {
                    if (!String.IsNullOrWhiteSpace(queryAttribute.AttribueAlias))
                    {
                        queryAttribute.AttributeLabel = queryAttribute.AttribueAlias;
                    }
                    else
                    {
                        AttributeMetadata attributeMetadata = metadata.Attributes.FirstOrDefault(a => a.LogicalName == queryAttribute.Attribute);
                        Label             displayLabel      = attributeMetadata.DisplayName;
                        if (displayLabel != null && displayLabel.UserLocalizedLabel != null)
                        {
                            queryAttribute.AttributeLabel = displayLabel.UserLocalizedLabel.Label;
                        }
                    }
                }
            }

            List <ColumnInformation> returnColumns = new List <ColumnInformation>();
            List <QueryAttribute>    toReturn      = (layoutXmlColumns.Count > 0) ? layoutXmlColumns : fetchXmlColumns;

            foreach (QueryAttribute qa in toReturn)
            {
                ColumnInformation ci = new ColumnInformation();
                ci.Header = qa.AttributeLabel;
                if (!String.IsNullOrEmpty(qa.EntityAlias))
                {
                    ci.QueryResultAlias = String.Format("{0}.{1}", qa.EntityAlias, qa.Attribute);
                }
                else if (!String.IsNullOrEmpty(qa.AttribueAlias))
                {
                    ci.QueryResultAlias = qa.AttribueAlias;
                }
                else
                {
                    ci.QueryResultAlias = qa.Attribute;
                }
                returnColumns.Add(ci);
                returnColumns.Add(new ColumnInformation()
                {
                    Header = String.Format(MetadataHeaderFormat, ci.Header, "RawValue")
                });
            }

            return(returnColumns);
        }