void bgwRelationKeyMappingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            OneToManyRelationshipMetadata relationShipMetadata = e.Argument as OneToManyRelationshipMetadata;
            EntityMetadata entityMetadata = Crm2013Wrapper.Crm2013Wrapper.GetEntityMetadata(service, relationShipMetadata.ReferencedEntity);

            e.Result = new object [] { relationShipMetadata, entityMetadata };
        }
        public void SetSealedPropertyValue_should_update_onetomanyrelationship_metadata()
        {
            var fakeRelationship = new OneToManyRelationshipMetadata();

            fakeRelationship.SetSealedPropertyValue("ReferencingEntity", "account");
            Assert.Equal("account", fakeRelationship.ReferencingEntity);
        }
Exemple #3
0
        public void GetNameForRelationship_LooksUpReferencingEntityAttribute()
        {
            organizationMetadata.Entities.Returns(new[] {
                new EntityMetadata {
                    LogicalName = "ee_testprop", DisplayName = new Label("Test Prop", 1033)
                }
            });

            var relationship = new OneToManyRelationshipMetadata {
                ReferencingEntity = "ee_test", ReferencingAttribute = "ee_testid",
                ReferencedEntity  = "ee_testprop"
            };
            var attMetadata = new StringAttributeMetadata {
                LogicalName = "ee_testid", DisplayName = new Label("Test Id", 1033)
            };
            var metadata = new EntityMetadata {
                LogicalName = "ee_test"
            }
            .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata })
            .Set(x => x.ManyToOneRelationships, new OneToManyRelationshipMetadata[]
            {
                relationship,
                new OneToManyRelationshipMetadata {
                    ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid"
                }
            });

            var output = sut.GetNameForRelationship(metadata, relationship, null, serviceProvider);

            Assert.AreEqual("TestId_TestProp", output);
        }
        private void lbRelationAttributes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBoxItem listboxItem = lbRelationAttributes.SelectedItem as ListBoxItem;

            if (listboxItem == null)
            {
                RelationMappingContent.Content = null;
                return;
            }

            var relations = entityMetadata.ManyToOneRelationships.Where(t => t.ReferencingAttribute == listboxItem.Content.ToString());
            IEnumerable <SDK.RelationMapping> relationMappings = Configuration.RelationMapping.Where(t => t.LogicalName == relations.First().ReferencingAttribute);

            // Is it a new relationmapping?
            if (relationMappings.Count() == 0 || relations.Count() > 1)
            {
                Relation.RelationMappingCreation relationMappingCreation = new Relation.RelationMappingCreation(relationMappings.ToList(), relations.ToList());
                relationMappingCreation.NewRelationCreated += relationMappingCreation_NewRelationCreated;
                RelationMappingContent.Content              = relationMappingCreation;
            }
            else
            {
                OneToManyRelationshipMetadata relationShip = relations.First();
                if (relationShip.ReferencingAttribute == "ownerid")
                {
                    relationShip.ReferencedEntity = relationMappings.First().EntityName;
                }
                ShowRelationMapping(relationShip);
            }
        }
        public void GenerateN1RelationshipIfAllRelationshipsParameterIsSpecified()
        {
            var fakeFilterService = new Fake <ICodeWriterFilterService>();

            fakeFilterService.AnyCall().WithReturnType <bool>().Returns(true);

            var fakeServiceProvider = new Fake <IServiceProvider>();

            Environment.SetEnvironmentVariable(Constants.ENVIRONMENT_ENTITIES, "account");
            Environment.SetEnvironmentVariable(Constants.ENVIRONMENT_ALL_RELATIONSHIPS, "account");

            var metadata = new OneToManyRelationshipMetadata()
            {
                MetadataId           = Guid.NewGuid(),
                SchemaName           = "account_primary_contact",
                ReferencingEntity    = "account",
                ReferencingAttribute = "primarycontactid",
                ReferencedEntity     = "contact",
                ReferencedAttribute  = "contactid"
            };

            var otherEntity = new EntityMetadata()
            {
                LogicalName = "contact"
            };

            var filteringService           = new FilteringService(fakeFilterService.FakedObject);
            var shouldGenerateRelationship = (filteringService as ICodeWriterFilterService).GenerateRelationship(metadata, otherEntity, fakeServiceProvider.FakedObject);

            Environment.SetEnvironmentVariable(Constants.ENVIRONMENT_ENTITIES, null);
            Environment.SetEnvironmentVariable(Constants.ENVIRONMENT_ALL_RELATIONSHIPS, null);

            A.CallTo(() => fakeFilterService.FakedObject.GenerateRelationship(A <RelationshipMetadataBase> .Ignored, A <EntityMetadata> .Ignored, A <IServiceProvider> .Ignored)).MustHaveHappenedOnceExactly();
            Assert.True(shouldGenerateRelationship);
        }
        public static IList <Guid> GatherOneToManyKeys(IOrganizationService service, OneToManyRelationshipMetadata relationship, Guid currentRecordId)
        {
            var query = new QueryByAttribute()
            {
                EntityName = relationship.ReferencingEntity
            };

            query.Attributes.Add(relationship.ReferencingAttribute);
            query.Values.Add(currentRecordId.ToString());

            var retrieveRequest = new RetrieveMultipleRequest()
            {
                Query = query
            };

            // Foreach object just get the primary key
            var retrieveResponse = (RetrieveMultipleResponse)service.Execute(retrieveRequest);
            var keyList          = new List <Guid>();

            foreach (var entity in retrieveResponse.EntityCollection.Entities)
            {
                keyList.Add(entity.Id);
            }

            return(keyList);
        }
Exemple #7
0
        public void LoadData(OneToManyRelationshipMetadata item)
        {
            if (item.MetadataId.HasValue)
            {
                this.MetadataId = item.MetadataId;
            }

            if (!string.IsNullOrEmpty(item.SchemaName))
            {
                this.SchemaName = item.SchemaName;
            }

            if (!string.IsNullOrEmpty(item.ReferencingAttribute))
            {
                this.BaseAttributeName = item.ReferencingAttribute;
            }

            if (!string.IsNullOrEmpty(item.ReferencedEntity))
            {
                this.TargetEntityName = item.ReferencedEntity;
            }
            if (!string.IsNullOrEmpty(item.ReferencedAttribute))
            {
                this.TargetAttributeName = item.ReferencedAttribute;
            }
        }
        public static ViewsRelationsObj getRelationObj(ViewExcelSheetsInfo sheetView, string entity, string fromAttribute)
        {
            ViewsRelationsObj obj = sheetView.relationsList.Where(x => x.relationFrom != null && x.entity.Equals(entity, StringComparison.InvariantCultureIgnoreCase) &&
                                                                  x.relationFrom.Equals(fromAttribute, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (obj == null)
            {
                ViewsRelationsObj             mainobj = sheetView.relationsList.Where(x => x.relationAlias == null).FirstOrDefault();
                OneToManyRelationshipMetadata rel     = mainobj.entityMetadata.ManyToOneRelationships
                                                        .Where(x => x.ReferencedEntity.Equals(entity, StringComparison.InvariantCultureIgnoreCase) &&
                                                               x.ReferencingAttribute.Equals(fromAttribute, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (rel != null)
                {
                    obj = new ViewsRelationsObj()
                    {
                        entity         = entity.ToLower(),
                        entityMetadata = GlobalOperations.Instance.CRMOpHelper.RetriveEntityAtrribute(entity),
                        relationAlias  = string.Concat("a_", Guid.NewGuid().ToString().Replace("-", "")).ToLower(),
                        relationFrom   = rel.ReferencedAttribute.ToLower(),
                        relationTo     = fromAttribute.ToLower()
                    };
                    sheetView.relationsList.Add(obj);
                }
            }
            return(obj);
        }
Exemple #9
0
        public static MappingRelationship1N Parse(OneToManyRelationshipMetadata rel, MappingField[] properties)
        {
            var propertyName =
                properties.First(p => p.Attribute.LogicalName.ToLower() == rel.ReferencedAttribute.ToLower()).DisplayName;

            var result = new MappingRelationship1N
            {
                Attribute = new CrmRelationshipAttribute
                {
                    FromEntity         = rel.ReferencedEntity,
                    FromKey            = rel.ReferencedAttribute,
                    ToEntity           = rel.ReferencingEntity,
                    ToKey              = rel.ReferencingAttribute,
                    IntersectingEntity = ""
                },
                ForeignKey  = propertyName,
                DisplayName = Naming.GetProperVariableName(rel.SchemaName),
                SchemaName  = Naming.GetProperVariableName(rel.SchemaName),
                LogicalName = rel.ReferencingAttribute,
                PrivateName = Naming.GetEntityPropertyPrivateName(rel.SchemaName),
                HybridName  = Naming.GetPluralName(Naming.GetProperVariableName(rel.SchemaName)),
                EntityRole  = "null",
                Type        = Naming.GetProperVariableName(rel.ReferencingEntity),
            };

            if (rel.ReferencedEntity == rel.ReferencingEntity)
            {
                result.DisplayName = "Referenced" + result.DisplayName;
                result.EntityRole  = "Microsoft.Xrm.Sdk.EntityRole.Referenced";
            }

            return(result);
        }
Exemple #10
0
 private void SetRelationChosen(OneToManyRelationshipMetadata selectedRelation)
 {
     if (NewRelationCreated != null)
     {
         NewRelationCreated(selectedRelation, new EventArgs());
     }
 }
Exemple #11
0
        public Guid AddRelationship(OneToManyRelationshipMetadata relationship, LookupAttributeMetadata lookup)
        {
            bool isReferencingEligible = EligibleForRelationship(relationship.ReferencingEntity, "CanBeReferencing");
            bool isReferencedEligible  = EligibleForRelationship(relationship.ReferencedEntity, "CanBeReferenced");

            if (!(isReferencedEligible && isReferencingEligible))
            {
                throw new Exception(string.Format("One-to-Many relationship between '{0}' and '{1}' is not allowed.",
                                                  relationship.ReferencingEntity, relationship.ReferencedEntity));
            }

            OrganizationRequest request = new OrganizationRequest("CreateOneToMany")
            {
                Parameters = new ParameterCollection
                {
                    { "OneToManyRelationship", relationship },
                    { "Lookup", lookup }
                }
            };

            if (CrmContext.ActiveSolution != null)
            {
                request.Parameters.Add("SolutionUniqueName", CrmContext.ActiveSolution);
            }

            OrganizationResponse response = CrmContext.OrganizationProxy.Execute(request);

            return((Guid)response.Results["RelationshipId"]);
        }
Exemple #12
0
 public OneToManyRelationshipComponent(OneToManyRelationshipMetadata otmmd)
 {
     this.otmmd    = otmmd;
     Id            = otmmd.MetadataId;
     ComponentType = EnumTypes.ComponentType.Relationship;
     Name          = otmmd.SchemaName;
     DisplayName   = Name;
 }
        private CreateOneToManyRequest BuildCreateOneToManyRequest(OneToManyRelationshipMetadata relationship, LookupAttributeMetadata lookup)
        {
            var createOneToManyRequest = new CreateOneToManyRequest();

            createOneToManyRequest.OneToManyRelationship = relationship;
            createOneToManyRequest.Lookup = lookup;
            return(createOneToManyRequest);
        }
Exemple #14
0
        public void UpdateChildRecords(string relationshipName, string parentEntityType, string parentEntityId, string parentFieldNameToUpdate, string setValueToUpdate, string childFieldNameToUpdate)
        {
            //1) Get child lookup field name
            RetrieveRelationshipRequest req = new RetrieveRelationshipRequest()
            {
                Name = relationshipName
            };
            RetrieveRelationshipResponse  res = (RetrieveRelationshipResponse)service.Execute(req);
            OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)res.RelationshipMetadata;
            string childEntityType            = rel.ReferencingEntity;
            string childEntityFieldName       = rel.ReferencingAttribute;

            //2) retrieve all child records
            QueryByAttribute querybyattribute = new QueryByAttribute(childEntityType);

            querybyattribute.ColumnSet = new ColumnSet(childEntityFieldName);
            querybyattribute.Attributes.AddRange(childEntityFieldName);
            querybyattribute.Values.AddRange(new Guid(parentEntityId));
            EntityCollection retrieved = service.RetrieveMultiple(querybyattribute);

            //2') retrieve parent fielv value
            var valueToUpdate = new object();

            if (parentFieldNameToUpdate != null && parentFieldNameToUpdate != "")
            {
                Entity retrievedEntity = (Entity)service.Retrieve(parentEntityType, new Guid(parentEntityId), new ColumnSet(parentFieldNameToUpdate));
                if (retrievedEntity.Attributes.Contains(parentFieldNameToUpdate))
                {
                    valueToUpdate = retrievedEntity.Attributes[parentFieldNameToUpdate];
                }
                else
                {
                    valueToUpdate = null;
                }
            }
            else
            {
                valueToUpdate = setValueToUpdate;
            }

            //3) update each child record

            foreach (Entity child in retrieved.Entities)
            {
                if (childEntityType.ToLower() == "dynamicpropertyinstance")
                {
                    //pending...
                    UpdateProductPropertiesRequest req2 = new UpdateProductPropertiesRequest();
                    // req2.
                    break;
                }

                Entity entUpdate = new Entity(childEntityType);
                entUpdate.Id = child.Id;
                entUpdate.Attributes.Add(childFieldNameToUpdate, valueToUpdate);
                service.Update(entUpdate);
            }
        }
Exemple #15
0
        public void ParentChildRelationshipBuiltAsExpected()
        {
            var entity = new EntityMetadata {
                LogicalName = "ee_test",
                DisplayName = new Label("Test", 1033)
            }
            .Set(x => x.ManyToManyRelationships, Array.Empty <ManyToManyRelationshipMetadata>());
            var manyToOne = new OneToManyRelationshipMetadata
            {
                ReferencedEntity = entity.LogicalName
            };

            organizationMetadata.Entities.Returns(new[] {
                entity.Set(x => x.OneToManyRelationships, new[] { manyToOne })
            });
            parameters["UseDisplayNames"] = true.ToString();
            var sut             = new CodeCustomistationService(parameters);
            var codeCompileUnit = new CodeCompileUnit
            {
                Namespaces =
                {
                    new CodeNamespace("EarlyTest")
                    {
                        Types =
                        {
                            new CodeTypeDeclaration {
                                CustomAttributes =  { Build <EntityLogicalNameAttribute>("ee_test")},
                                Members          =
                                {
                                    new CodeMemberProperty
                                    {
                                        HasSet           = true,
                                        Type             = new CodeTypeReference("System.Collections.Generic.IEnumerable", new CodeTypeReference("TestProp")),
                                        Name             = "Relationship",
                                        CustomAttributes ={ Build <RelationshipSchemaNameAttribute>(
                                                          new CodePrimitiveExpression("ee_relationship"),
                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("EntityRole"), EntityRole.Referenced.ToString())) }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            sut.CustomizeCodeDom(codeCompileUnit, serviceProvider);

            var ns       = codeCompileUnit.Namespaces.Cast <CodeNamespace>().First();
            var @class   = ns.Types.OfType <CodeTypeDeclaration>().First();
            var property = @class.Members.OfType <CodeMemberProperty>().First();

            Assert.AreEqual("IEnumerable`1", property.Type.BaseType);
            Assert.AreEqual("TestProp", property.Type.TypeArguments.Cast <CodeTypeReference>().First().BaseType);
            Assert.AreEqual("Referenced", (property.CustomAttributes.Cast <CodeAttributeDeclaration>().First().Arguments.Cast <CodeAttributeArgument>().Last().Value as CodeFieldReferenceExpression).FieldName);
            var getStatement = property.GetStatements.Cast <CodeSnippetStatement>().First();

            Assert.IsTrue(getStatement.Value.Contains("EntityRole.Referenced"));
        }
        private void ShowRelationMapping(OneToManyRelationshipMetadata relationMetadata)
        {
            RelationMappingContent.Content = new LoadingControl();
            BackgroundWorker bgwRelationKeyMappingWorker = new BackgroundWorker();

            bgwRelationKeyMappingWorker.DoWork             += bgwRelationKeyMappingWorker_DoWork;
            bgwRelationKeyMappingWorker.RunWorkerCompleted += bgwRelationKeyMappingWorker_RunWorkerCompleted;
            bgwRelationKeyMappingWorker.RunWorkerAsync(relationMetadata);
        }
Exemple #17
0
 private void btnCreateRelation_Click(object sender, RoutedEventArgs e)
 {
     if (ddEntities.SelectedItem != null)
     {
         OneToManyRelationshipMetadata relationMetadata = ((ComboBoxItem)ddEntities.SelectedItem).Tag as OneToManyRelationshipMetadata;
         relationMetadata.ReferencedEntity = ((ComboBoxItem)ddEntities.SelectedItem).Content.ToString();
         SetRelationChosen(relationMetadata);
     }
 }
Exemple #18
0
 private void lbExistingMappings_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     if (lbExistingMappings.SelectedItem != null)
     {
         SDK.RelationMapping           relMapping  = ((ListBoxItem)lbExistingMappings.SelectedItem).Tag as SDK.RelationMapping;
         OneToManyRelationshipMetadata relMetadata = relationsMetadata.Where(t => t.ReferencingAttribute == relMapping.LogicalName && t.ReferencedEntity == relMapping.EntityName).First();
         SetRelationChosen(relMetadata);
     }
 }
Exemple #19
0
        public static MappingRelationship1N Parse(OneToManyRelationshipMetadata rel,
                                                  MappingRelationship1N relationshipOneToMany,
                                                  MappingField[] properties)
        {
            string propertyName = null;

            if (relationshipOneToMany != null)
            {
                propertyName = relationshipOneToMany.ForeignKey;
            }

            if (rel.ReferencedAttribute != null)
            {
                propertyName = properties.First(p => string.Equals(p.Attribute.LogicalName, rel.ReferencedAttribute,
                                                                   StringComparison.CurrentCultureIgnoreCase)).DisplayName;
            }

            relationshipOneToMany = relationshipOneToMany
                                    ?? new MappingRelationship1N
            {
                Attribute = new CrmRelationshipAttribute(),
            };

            relationshipOneToMany.Attribute.FromEntity         = rel.ReferencedEntity ?? relationshipOneToMany.Attribute.FromEntity;
            relationshipOneToMany.Attribute.FromKey            = rel.ReferencedAttribute ?? relationshipOneToMany.Attribute.FromKey;
            relationshipOneToMany.Attribute.ToEntity           = rel.ReferencingEntity ?? relationshipOneToMany.Attribute.ToEntity;
            relationshipOneToMany.Attribute.ToKey              = rel.ReferencingAttribute ?? relationshipOneToMany.Attribute.ToKey;
            relationshipOneToMany.Attribute.IntersectingEntity = "";
            relationshipOneToMany.ForeignKey = propertyName ?? "_MISSING_KEY";

            if (rel.SchemaName != null)
            {
                relationshipOneToMany.SchemaName  = rel.SchemaName;
                relationshipOneToMany.DisplayName = rel.SchemaName;
                relationshipOneToMany.PrivateName = Naming.GetEntityPropertyPrivateName(rel.SchemaName);
                relationshipOneToMany.HybridName  = Naming.GetPluralName(Naming.GetProperVariableName(rel.SchemaName, false));
            }

            relationshipOneToMany.LogicalName = rel.ReferencingAttribute ?? relationshipOneToMany.LogicalName;

            relationshipOneToMany.EntityRole = "null";
            relationshipOneToMany.Type       = rel.ReferencingEntity;

            relationshipOneToMany.MetadataId = rel.MetadataId;

            if (rel.ReferencedEntity != null && rel.ReferencingEntity != null &&
                rel.ReferencedEntity == rel.ReferencingEntity)
            {
                relationshipOneToMany.DisplayName = "Referenced_" + relationshipOneToMany.DisplayName;
                relationshipOneToMany.EntityRole  = "Microsoft.Xrm.Sdk.EntityRole.Referenced";
            }

            return(relationshipOneToMany);
        }
Exemple #20
0
        public void GetNameForRelationship_ManyToMany()
        {
            organizationMetadata.Entities.Returns(new[] {
                new EntityMetadata {
                    LogicalName           = "ee_testprop",
                    DisplayCollectionName = new Label("Test Props", 1033)
                }
                .Set(x => x.Attributes, new AttributeMetadata[]
                {
                    new StringAttributeMetadata {
                        LogicalName = "ee_testid",
                        DisplayName = "Test Id".AsLabel()
                    }
                })
            });

            var relationship = new OneToManyRelationshipMetadata
            {
                ReferencingEntity    = "ee_testprop",
                ReferencingAttribute = "ee_testid",
                ReferencedEntity     = "ee_test",
                SchemaName           = "ee_two"
            };
            var many2Many = new ManyToManyRelationshipMetadata
            {
                Entity1LogicalName = "ee_test",
                Entity2LogicalName = "ee_testprop",
                SchemaName         = "ee_testProp_association"
            };
            var attMetadata = new StringAttributeMetadata {
                LogicalName = "ee_testid", DisplayName = "Test Id".AsLabel()
            };
            var metadata = new EntityMetadata {
                LogicalName = "ee_test"
            }
            .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata })
            .Set(x => x.OneToManyRelationships, new OneToManyRelationshipMetadata[]
            {
                relationship,
                new OneToManyRelationshipMetadata {
                    ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid", SchemaName = "ee_one"
                }
            })
            .Set(x => x.ManyToManyRelationships, new[] { many2Many });

            var output = sut.GetNameForRelationship(metadata, many2Many, null, serviceProvider);

            Assert.AreEqual("TestProps", output);
        }
        private OneToManyRelationshipMetadata RetrieveRelationshipInfo(IOrganizationService service, EntityReference primaryEntity, string relationshipName)
        {
            Relationship          relationship = new Relationship(relationshipName);
            RetrieveEntityRequest request      = new RetrieveEntityRequest()
            {
                LogicalName           = primaryEntity.LogicalName,
                EntityFilters         = EntityFilters.Relationships,
                RetrieveAsIfPublished = true
            };
            RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);

            OneToManyRelationshipMetadata oneToNRelationship = response.EntityMetadata.OneToManyRelationships.FirstOrDefault(r => r.SchemaName == relationshipName);

            return(oneToNRelationship);
        }
Exemple #22
0
        public bool QueryOneToManyRelationship()
        {
            RetrieveRelationshipRequest request = new RetrieveRelationshipRequest();

            request.Name = "contact_customer_accounts";
            request.RetrieveAsIfPublished = true;

            RetrieveRelationshipResponse  response     = (RetrieveRelationshipResponse)OrganizationServiceProxy.Execute(request);
            OneToManyRelationshipMetadata relationship = (OneToManyRelationshipMetadata)response.RelationshipMetadata;

            Assert.AreEqual(relationship.IsCustomRelationship, false);
            Assert.AreEqual(relationship.SchemaName, "contact_customer_accounts");
            Assert.AreEqual(relationship.ReferencedAttribute, "accountid");
            return(true);
        }
Exemple #23
0
        private static void AddOneToManyRelationshipMetadata(Type referencingEntity, PropertyInfo referencingAttribute, Type referencedEntity, PropertyInfo referencedAttribute, List <OneToManyRelationshipMetadata> relationshipMetadatas)
        {
            if (referencingEntity == null || referencingAttribute == null || referencedEntity == null || referencedAttribute == null)
            {
                return;
            }
            OneToManyRelationshipMetadata relationshipMetadata = new OneToManyRelationshipMetadata();

            relationshipMetadata.SchemaName           = GetCustomAttribute <RelationshipSchemaNameAttribute>(referencingAttribute).SchemaName;
            relationshipMetadata.ReferencingEntity    = GetCustomAttribute <EntityLogicalNameAttribute>(referencingEntity).LogicalName;
            relationshipMetadata.ReferencingAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(referencingAttribute)?.LogicalName;
            relationshipMetadata.ReferencedEntity     = GetCustomAttribute <EntityLogicalNameAttribute>(referencedEntity).LogicalName;
            relationshipMetadata.ReferencedAttribute  = GetCustomAttribute <AttributeLogicalNameAttribute>(referencedAttribute).LogicalName;

            relationshipMetadatas.Add(relationshipMetadata);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Extract the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            try
            {
                //Create the context
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                DynamicUrlParser parser           = new DynamicUrlParser();
                EntityReference  primaryEntity    = parser.ConvertToEntityReference(service, RecordUrl.Get <string>(executionContext));
                string           relationshipName = RelationshipName.Get <string>(executionContext);

                string childEntityName = null, childEntityAttribute = null;
                if (relationshipName.Contains(';'))
                {
                    string[] relationshipNames = relationshipName.Split(';');
                    foreach (string rel in relationshipNames)
                    {
                        OneToManyRelationshipMetadata oneToNRelationship = RetrieveRelationshipInfo(service, primaryEntity, relationshipName);
                        if (oneToNRelationship != null)
                        {
                            childEntityName      = oneToNRelationship.ReferencingEntity;
                            childEntityAttribute = oneToNRelationship.ReferencingAttribute;
                            RetrieveAndUpdateRelatedRecords(service, primaryEntity, childEntityName, childEntityAttribute, StateCode.Get <int>(executionContext), StatusCode.Get <int>(executionContext));
                        }
                    }
                }
                else
                {
                    OneToManyRelationshipMetadata oneToNRelationship = RetrieveRelationshipInfo(service, primaryEntity, relationshipName);
                    if (oneToNRelationship != null)
                    {
                        childEntityName      = oneToNRelationship.ReferencingEntity;
                        childEntityAttribute = oneToNRelationship.ReferencingAttribute;
                        RetrieveAndUpdateRelatedRecords(service, primaryEntity, childEntityName, childEntityAttribute, StateCode.Get <int>(executionContext), StatusCode.Get <int>(executionContext));
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new Exception("XrmWorkflowTools.SetStateChildRecords: " + ex.Message);
            }
        }
Exemple #25
0
        public bool TryGetOneToManyRelationshipMetadata(Relationship relationship, out OneToManyRelationshipMetadata relationshipMetadata)
        {
            if (relationship == null)
            {
                throw new ArgumentNullException("relationship");
            }

            if (relationship.PrimaryEntityRole.HasValue && relationship.PrimaryEntityRole.Value == EntityRole.Referencing)
            {
                throw new ArgumentException("Primary entity role on many-to-one relationship must be Referencing, not Referenced.", "relationship");
            }

            relationshipMetadata = _entityMetadata.Value.OneToManyRelationships
                                   .FirstOrDefault(r => r.SchemaName == relationship.SchemaName);

            return(relationshipMetadata != null);
        }
        private List <string> GetDifferenceOneToMany(OneToManyRelationshipMetadata rel1, OneToManyRelationshipMetadata rel2)
        {
            var table = new FormatTextTableHandler(true);

            table.SetHeader("Property", _connectionName1, _connectionName2);

            AddAssociatedMenuConfigurationDifference(table, "AssociatedMenuConfiguration", rel1.AssociatedMenuConfiguration, rel2.AssociatedMenuConfiguration);

            List <string> result = new List <string>();

            if (table.Count > 0)
            {
                result.AddRange(table.GetFormatedLines(false));
            }

            return(result);
        }
        private OneToManyRelationshipMetadata BuildOneToManyRelationshipMetadata(ForeignKeyConstraint fkConstraint)
        {
            var oneToManyRelationship = new OneToManyRelationshipMetadata();

            oneToManyRelationship.ReferencedEntity = fkConstraint.ReferencedTable.Name.ToLower();
            if (!string.IsNullOrWhiteSpace(fkConstraint.ReferencedColumn))
            {
                oneToManyRelationship.ReferencedAttribute = fkConstraint.ReferencedColumn.ToLower();
            }
            var referencingAttributeName = this.CurrentColumnDefinition.Name.ToLower();

            oneToManyRelationship.ReferencingEntity = this.AlterTableName.ToLower();
            // oneToManyRelationship.ReferencingAttribute = this.CurrentColumnDefinition.Name.ToLower();

            oneToManyRelationship.CascadeConfiguration = new CascadeConfiguration();

            oneToManyRelationship.CascadeConfiguration.Assign   = CascadeType.NoCascade;
            oneToManyRelationship.CascadeConfiguration.Delete   = CascadeType.Restrict;
            oneToManyRelationship.CascadeConfiguration.Merge    = CascadeType.NoCascade;
            oneToManyRelationship.CascadeConfiguration.Reparent = CascadeType.NoCascade;
            oneToManyRelationship.CascadeConfiguration.Share    = CascadeType.NoCascade;
            oneToManyRelationship.CascadeConfiguration.Unshare  = CascadeType.NoCascade;

            this.CurrentCascadeConfiguration = oneToManyRelationship.CascadeConfiguration;
            if (fkConstraint.OnDeleteAction != null)
            {
                fkConstraint.OnDeleteAction.Accept(this);
            }
            if (fkConstraint.OnUpdateAction != null)
            {
                fkConstraint.OnUpdateAction.Accept(this);
            }

            if (!string.IsNullOrWhiteSpace(fkConstraint.ConstraintName))
            {
                oneToManyRelationship.SchemaName = fkConstraint.ConstraintName;
            }
            else
            {
                // generate schema name.
                oneToManyRelationship.SchemaName = string.Format("{0}_{1}_{2}", oneToManyRelationship.ReferencedEntity, oneToManyRelationship.ReferencingEntity, referencingAttributeName);
                //   throw new NotSupportedException("You must specify a constraint name for the foregin key constraint. This should be prefixed with the crm publisher prefix, e.g 'new_entity1_entity2'");
            }
            return(oneToManyRelationship);
        }
        private static void setAttributesObj(ViewFeo viewFeo, List <ViewsRelationsObj> relObj)
        {
            ViewsRelationsObj             mainobj = relObj.Where(x => x.relationAlias == null).FirstOrDefault();
            OneToManyRelationshipMetadata rel     = mainobj.entityMetadata.ManyToOneRelationships.Where(x => x.ReferencedEntity.Equals(viewFeo.AttributeEntity, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (rel != null)
            {
                viewFeo.AttributeObj = new ViewsRelationsObj()
                {
                    entity         = viewFeo.AttributeEntity.ToLower(),
                    entityMetadata = GlobalOperations.Instance.CRMOpHelper.RetriveEntityAtrribute(viewFeo.AttributeEntity),
                    relationAlias  = string.Concat("a_", Guid.NewGuid().ToString().Replace("-", "")).ToLower(),
                    relationFrom   = rel.ReferencedAttribute.ToLower(),
                    relationTo     = rel.ReferencingAttribute.ToLower()
                };
                relObj.Add(viewFeo.AttributeObj);
            }
        }
        private IExtensibleDataObject lookUpFieldCreation(string[] row)
        {
            LookupAttributeMetadata attrMetadata = new LookupAttributeMetadata();

            generalFieldCreation(row, attrMetadata);
            OneToManyRelationshipMetadata oneToManyRelationship = new OneToManyRelationshipMetadata();

            oneToManyRelationship.ReferencingEntity = entityLocialName;
            string relatiosshipName    = row[ExcelColumsDefinition.LOOKUPRELATIONSHIPNAME] != string.Empty ? row[ExcelColumsDefinition.LOOKUPRELATIONSHIPNAME] : string.Empty;
            string relashionshiptarget = row[ExcelColumsDefinition.LOOKUPTARGET] != string.Empty ? row[ExcelColumsDefinition.LOOKUPTARGET] : string.Empty;

            oneToManyRelationship.ReferencedEntity = relashionshiptarget;
            oneToManyRelationship.SchemaName       = Utils.addOrgPrefix(relatiosshipName, organizationPrefix, currentOperationCreate);
            CreateOneToManyRequest createRelationship = new CreateOneToManyRequest();

            createRelationship.Lookup = attrMetadata;
            createRelationship.OneToManyRelationship = oneToManyRelationship;
            return(createRelationship);
        }
Exemple #30
0
        private void AddOneToMany()
        {
            OneToManyRelationshipMetadata relationship = new OneToManyRelationshipMetadata
            {
                ReferencedEntity  = ToEntity,
                ReferencingEntity = Entity,
                SchemaName        = Name
            };

            if (_context != null)
            {
                _context.SetParametersOnRelationship(relationship);
            }

            LookupAttributeMetadata lookup = new LookupAttributeMetadata
            {
                SchemaName  = AttributeName,
                DisplayName = new Label(AttributeDisplayName, CrmContext.Language),
                Description = new Label(AttributeDescription ?? string.Empty, CrmContext.Language)
            };
            AttributeRequiredLevel requiredLevel = AttributeRequiredLevel.ApplicationRequired;

            if (AttributeRequired == CrmRequiredLevel.Required)
            {
                requiredLevel = AttributeRequiredLevel.ApplicationRequired;
            }
            if (AttributeRequired == CrmRequiredLevel.Recommended)
            {
                requiredLevel = AttributeRequiredLevel.Recommended;
            }
            if (AttributeRequired == CrmRequiredLevel.Optional)
            {
                requiredLevel = AttributeRequiredLevel.None;
            }
            lookup.RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel);

            Guid result = _repository.AddRelationship(relationship, lookup);

            if (PassThru)
            {
                WriteObject(_repository.GetRelationship(result));
            }
        }
 static CodeTypeMember BuildManyToOne(EntityMetadata entity, EntityMetadata otherEntity, OneToManyRelationshipMetadata manyToOne, ServiceProvider serviceProvider)
 {
     Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name});
     var type = serviceProvider.TypeMappingService.GetTypeForRelationship(manyToOne, otherEntity, serviceProvider);
     var reflexiveRole = (otherEntity.LogicalName == entity.LogicalName) ? ((EntityRole?) 0) : null;
     var property = PropertyGet(type, serviceProvider.NamingService.GetNameForRelationship(entity, manyToOne, reflexiveRole, serviceProvider), new CodeStatement[0]);
     property.GetStatements.Add(BuildRelationshipGet("GetRelatedEntity", manyToOne, type, reflexiveRole));
     var metadata = entity.Attributes.Single(attribute => attribute.LogicalName == manyToOne.ReferencingAttribute);
     if (metadata.IsValidForCreate.GetValueOrDefault() || metadata.IsValidForUpdate.GetValueOrDefault())
     {
         property.SetStatements.AddRange(BuildRelationshipSet("SetRelatedEntity", manyToOne, type, reflexiveRole));
     }
     property.CustomAttributes.Add(Attribute(AttributeLogicalNameAttribute, new[] {AttributeArg(manyToOne.ReferencingAttribute)}));
     property.CustomAttributes.Add(BuildRelationshipSchemaNameAttribute(manyToOne.SchemaName, reflexiveRole));
     property.Comments.AddRange(CommentSummary("N:1 " + manyToOne.SchemaName));
     Trace.TraceInformation("Exiting {0}: {1}.ManyToOne {2} defined", new object[] {MethodBase.GetCurrentMethod().Name, entity.LogicalName, property.Name});
     return property;
 }
 public OneToManyRelationshipMetadataInfo(OneToManyRelationshipMetadata otmmd)
 {
     this.otmmd = otmmd;
 }
        private void UpdateRelationshipSchemaName(OneToManyRelationshipMetadata relationship, string newSchemaName)
        {
            // Add or Remove Temp Post Fix or update last index of existing Att Schema to newSchema
            if (relationship.SchemaName.EndsWith(TempPostfix))
            {
                relationship.SchemaName = relationship.SchemaName.Remove(relationship.SchemaName.LastIndexOf(TempPostfix, StringComparison.Ordinal));
            }
            else if (newSchemaName.EndsWith(TempPostfix))
            {
                relationship.SchemaName = relationship.SchemaName + TempPostfix;
            }
            else
            {
                // Format {Prefix of SchemaName} + {Referenced Entity} + "_" + {Referencing Entity} + "_" + {End of SchemaName}
                var index = newSchemaName.IndexOf("_", StringComparison.Ordinal) + 1;
                var prefix = newSchemaName.Substring(0, index);
                var postFix = newSchemaName.Substring(index, newSchemaName.Length - index);

                relationship.SchemaName = string.Format("{0}{1}_{2}_{3}", prefix, relationship.ReferencedEntity, relationship.ReferencingEntity, postFix);
            }
        }
 static CodeTypeMember BuildCalendarRuleAttribute(EntityMetadata entity, EntityMetadata otherEntity, OneToManyRelationshipMetadata oneToMany, ServiceProvider serviceProvider)
 {
     Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name});
     var property = PropertyGet(IEnumerable(serviceProvider.TypeMappingService.GetTypeForRelationship(oneToMany, otherEntity, serviceProvider)), "CalendarRules", new CodeStatement[0]);
     property.GetStatements.AddRange(BuildEntityCollectionAttributeGet("calendarrules", property.Type));
     property.SetStatements.Add(BuildEntityCollectionAttributeSet("calendarrules"));
     property.CustomAttributes.Add(Attribute(AttributeLogicalNameAttribute, new[] {AttributeArg("calendarrules")}));
     property.Comments.AddRange(CommentSummary("1:N " + oneToMany.SchemaName));
     Trace.TraceInformation("Exiting {0}: {1}.Attribute {2} defined", new object[] {MethodBase.GetCurrentMethod().Name, entity.LogicalName, property.Name});
     return property;
 }
Exemple #35
0
 protected static int CompareRelationshipBySchemaName(OneToManyRelationshipMetadata x, OneToManyRelationshipMetadata y)
 {
     return x.SchemaName.CompareTo(y.SchemaName);
 }
 static CodeTypeMember BuildOneToMany(EntityMetadata entity, EntityMetadata otherEntity, OneToManyRelationshipMetadata oneToMany, ServiceProvider serviceProvider)
 {
     Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name});
     var typeParameter = serviceProvider.TypeMappingService.GetTypeForRelationship(oneToMany, otherEntity, serviceProvider);
     var reflexiveRole = (oneToMany.ReferencingEntity == entity.LogicalName) ? ((EntityRole?) 1) : null;
     var property = PropertyGet(IEnumerable(typeParameter), serviceProvider.NamingService.GetNameForRelationship(entity, oneToMany, reflexiveRole, serviceProvider), new CodeStatement[0]);
     property.GetStatements.Add(BuildRelationshipGet("GetRelatedEntities", oneToMany, typeParameter, reflexiveRole));
     property.SetStatements.AddRange(BuildRelationshipSet("SetRelatedEntities", oneToMany, typeParameter, reflexiveRole));
     property.CustomAttributes.Add(BuildRelationshipSchemaNameAttribute(oneToMany.SchemaName, reflexiveRole));
     property.Comments.AddRange(CommentSummary("1:N " + oneToMany.SchemaName));
     Trace.TraceInformation("Exiting {0}: {1}.OneToMany {2} defined", new object[] {MethodBase.GetCurrentMethod().Name, entity.LogicalName, property.Name});
     return property;
 }