public static MappingRelationshipN1 Parse(OneToManyRelationshipMetadata rel,
                                                  MappingRelationshipN1 relationshipOneToMany,
                                                  MappingField[] properties)
        {
            relationshipOneToMany = relationshipOneToMany
                                    ?? new MappingRelationshipN1
            {
                Attribute = new CrmRelationshipAttribute(),
            };

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

            if (rel.ReferencingAttribute != null)
            {
                relationshipOneToMany.Property = properties.FirstOrDefault(p => string.Equals(p.Attribute.LogicalName, rel.ReferencingAttribute,
                                                                                              StringComparison.CurrentCultureIgnoreCase));

                if (relationshipOneToMany.Property != null)
                {
                    relationshipOneToMany.ForeignKey = relationshipOneToMany.Property.DisplayName ?? "_MISSING_KEY";
                }
            }

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

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

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

            relationshipOneToMany.MetadataId = rel.MetadataId;

            if (rel.ReferencedEntity == rel.ReferencingEntity)
            {
                relationshipOneToMany.EntityRole  = "Microsoft.Xrm.Sdk.EntityRole.Referencing";
                relationshipOneToMany.DisplayName = "Referencing_" + relationshipOneToMany.DisplayName;
            }

            return(relationshipOneToMany);
        }
        public static MappingRelationshipN1 Parse(OneToManyRelationshipMetadata rel, MappingField[] properties)
        {
            var property = properties.First(p => p.Attribute.LogicalName.ToLower() == rel.ReferencingAttribute.ToLower());

            var propertyName = property.DisplayName;

            var result = new MappingRelationshipN1
            {
                Attribute = new CrmRelationshipAttribute
                {
                    ToEntity           = rel.ReferencedEntity,
                    ToKey              = rel.ReferencedAttribute,
                    FromEntity         = rel.ReferencingEntity,
                    FromKey            = rel.ReferencingAttribute,
                    IntersectingEntity = ""
                },

                DisplayName = Naming.GetProperVariableName(rel.SchemaName),
                SchemaName  = Naming.GetProperVariableName(rel.SchemaName),
                LogicalName = rel.ReferencingAttribute,
                HybridName  = Naming.GetProperVariableName(rel.SchemaName) + "_N1",
                PrivateName = "_n1" + Naming.GetEntityPropertyPrivateName(rel.SchemaName),
                ForeignKey  = propertyName,
                Type        = Naming.GetProperVariableName(rel.ReferencedEntity),
                Property    = property,
                EntityRole  = "null"
            };

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

            return(result);
        }
        private static MappingEntity GetMappingEntity(EntityMetadata entityMetadata, string serverStamp,
                                                      MappingEntity entity, bool isTitleCaseLogicalName)
        {
            entity = entity ?? new MappingEntity();

            entity.MetadataId  = entityMetadata.MetadataId;
            entity.ServerStamp = serverStamp;

            entity.Attribute             = entity.Attribute ?? new CrmEntityAttribute();
            entity.TypeCode              = entityMetadata.ObjectTypeCode ?? entity.TypeCode;
            entity.Attribute.LogicalName = entityMetadata.LogicalName ?? entity.Attribute.LogicalName;
            entity.IsIntersect           = (entityMetadata.IsIntersect ?? entity.IsIntersect);
            entity.Attribute.PrimaryKey  = entityMetadata.PrimaryIdAttribute ?? entity.Attribute.PrimaryKey;

            if (entityMetadata.DisplayName?.UserLocalizedLabel != null)
            {
                entity.Label = entityMetadata.DisplayName.UserLocalizedLabel.Label;
            }

            if (entityMetadata.SchemaName != null)
            {
                entity.DisplayName = Naming.GetProperEntityName(entityMetadata.SchemaName);
                entity.SchemaName  = entityMetadata.SchemaName;

                if (entityMetadata.LogicalName != null)
                {
                    entity.HybridName = Naming.GetProperHybridName(entityMetadata.SchemaName, entityMetadata.LogicalName);
                }
            }

            entity.StateName = entity.HybridName + "State";

            if (entityMetadata.Description != null &&
                entityMetadata.Description.UserLocalizedLabel != null)
            {
                entity.Description = entityMetadata.Description.UserLocalizedLabel.Label;
            }

            var fields = (entity.Fields ?? new MappingField[0]).ToList();

            foreach (var field in entityMetadata.Attributes.Where(a => a.AttributeOf == null))
            {
                var existingField = fields.FirstOrDefault(fieldQ => fieldQ.MetadataId == field.MetadataId);

                // if it exists, remove it from the list
                if (existingField != null)
                {
                    fields.RemoveAll(fieldQ => fieldQ.MetadataId == field.MetadataId);
                }

                // update/create and add to list
                fields.Add(MappingField.GetMappingField(field, entity, existingField, isTitleCaseLogicalName));
            }

            fields.ForEach(f =>
            {
                if (f.DisplayName == entity.DisplayName)
                {
                    f.DisplayName += "1";
                }

                if (f.HybridName == entity.HybridName)
                {
                    f.HybridName += "1";
                }
            }
                           );

            AddEntityImageCrm2013(fields);
            AddLookupFields(fields);

            entity.Fields = fields.ToArray();

            if (entityMetadata.Attributes != null)
            {
                // get the states enum from the metadata
                entity.States = entityMetadata.Attributes.Where(a => a is StateAttributeMetadata && a.AttributeOf == null)
                                .Select(a => MappingEnum.GetMappingEnum(a as EnumAttributeMetadata, null, isTitleCaseLogicalName))
                                .FirstOrDefault() ?? entity.States;

                // get all optionsets from the metadata
                var newEnums = entityMetadata.Attributes
                               .Where(a => (a is EnumAttributeMetadata || a is BooleanAttributeMetadata) &&
                                      a.AttributeOf == null);

                // if there was never any enums previously, then just take the ones sent
                if (entity.Enums == null)
                {
                    entity.Enums = newEnums.Select(newEnum => MappingEnum.GetMappingEnum(newEnum, null, isTitleCaseLogicalName)).ToArray();
                }
                else
                {
                    var existingEnums = entity.Enums.ToList();

                    // else, update the changed ones
                    newEnums.AsParallel()
                    .ForAll(newEnum =>
                    {
                        // has this enum been updated?
                        var existingEnum = existingEnums.Find(existingEnumQ => existingEnumQ.MetadataId == newEnum.MetadataId);

                        if (existingEnum != null)
                        {
                            // update it here
                            entity.Enums[existingEnums.IndexOf(existingEnum)] =
                                MappingEnum.GetMappingEnum(newEnum, existingEnum, isTitleCaseLogicalName);
                        }
                        else
                        {
                            // add new
                            existingEnums.Add(MappingEnum.GetMappingEnum(newEnum, null, isTitleCaseLogicalName));
                        }
                    });

                    entity.Enums = existingEnums.ToArray();
                }
            }

            entity.PrimaryKey           = entity.Fields.First(f => f.Attribute.LogicalName == entity.Attribute.PrimaryKey);
            entity.PrimaryKeyProperty   = entity.PrimaryKey.DisplayName;
            entity.PrimaryNameAttribute = entityMetadata.PrimaryNameAttribute ?? entity.PrimaryNameAttribute;

            MappingRelationship1N.UpdateCache(entityMetadata.OneToManyRelationships.ToList(), entity, entity.Fields);
            MappingRelationshipN1.UpdateCache(entityMetadata.ManyToOneRelationships.ToList(), entity, entity.Fields);
            MappingRelationshipMN.UpdateCache(entityMetadata.ManyToManyRelationships.ToList(), entity, entity.LogicalName);

            // add a clone for self-referenced relation
            var relationshipsManyToMany = entity.RelationshipsManyToMany.ToList();
            var selfReferenced          = relationshipsManyToMany.Where(r => r.IsSelfReferenced).ToList();

            foreach (var referenced in selfReferenced)
            {
                if (relationshipsManyToMany.All(
                        rel => rel.DisplayName != "Referencing" + Naming.GetProperVariableName(referenced.SchemaName, false)))
                {
                    var referencing = (MappingRelationshipMN)referenced.Clone();
                    referencing.DisplayName = "Referencing" + Naming.GetProperVariableName(referenced.SchemaName, false);
                    referencing.EntityRole  = "Microsoft.Xrm.Sdk.EntityRole.Referencing";
                    relationshipsManyToMany.Add(referencing);
                }
            }

            entity.RelationshipsManyToMany = relationshipsManyToMany.OrderBy(r => r.DisplayName).ToArray();

            entity.FriendlyName = Naming.Clean(string.IsNullOrEmpty(entity.Label)
                                                                   ? Naming.Clean(entity.HybridName)
                                                                   : Naming.Clean(entity.Label));

            // generate attribute friendly names and detect duplicates
            entity.Fields.AsParallel()
            .ForAll(field =>
            {
                var cleanFieldName =
                    Naming.Clean(
                        string.IsNullOrEmpty(field.Label)
                                                                        ? Naming.Clean(field.DisplayName)
                                                                        : Naming.Clean(field.Label))
                    + (field == entity.PrimaryKey ? "Id" : "");

                var isDuplicateName = entity.Fields.Count(
                    fieldQ => Naming.Clean(
                        string.IsNullOrEmpty(fieldQ.Label)
                                                                        ? Naming.Clean(fieldQ.DisplayName)
                                                                        : Naming.Clean(fieldQ.Label))
                    == cleanFieldName) > 1;

                isDuplicateName = isDuplicateName ||
                                  cleanFieldName == "Attributes" ||
                                  cleanFieldName == entity.FriendlyName ||
                                  cleanFieldName == "LogicalName" ||
                                  cleanFieldName == "EntityLogicalName" ||
                                  cleanFieldName == "SchemaName" ||
                                  cleanFieldName == "DisplayName" ||
                                  cleanFieldName == "EntityTypeCode";

                field.FriendlyName = cleanFieldName +
                                     (isDuplicateName ? "_" + field.DisplayName : "");
            });

            // generate enum friendly names
            entity.Enums.AsParallel()
            .ForAll(enm =>
            {
                var attribute    = entity.Fields.FirstOrDefault(field => field.LogicalName == enm.LogicalName);
                enm.FriendlyName = attribute == null ? enm.DisplayName : attribute.FriendlyName;
            });

            return(entity);
        }
Example #4
0
        public static MappingEntity Parse(EntityMetadata entityMetadata)
        {
            var entity = new MappingEntity();

            entity.Attribute             = new CrmEntityAttribute();
            entity.TypeCode              = entityMetadata.ObjectTypeCode;
            entity.Attribute.LogicalName = entityMetadata.LogicalName;
            entity.IsIntersect           = (bool)entityMetadata.IsIntersect;
            entity.Attribute.PrimaryKey  = entityMetadata.PrimaryIdAttribute;

            // entity.DisplayName = Helper.GetProperVariableName(entityMetadata.SchemaName);
            entity.DisplayName = Naming.GetProperEntityName(entityMetadata.SchemaName);
            entity.HybridName  = Naming.GetProperHybridName(entityMetadata.SchemaName, entityMetadata.LogicalName);
            entity.StateName   = entity.HybridName + "State";

            if (entityMetadata.Description != null)
            {
                if (entityMetadata.Description.UserLocalizedLabel != null)
                {
                    entity.Description = entityMetadata.Description.UserLocalizedLabel.Label;
                }
            }

            var fields = entityMetadata.Attributes
                         .Where(a => a.AttributeOf == null)
                         .Select(a => MappingField.Parse(a, entity)).ToList();

            fields.ForEach(f =>
            {
                if (f.DisplayName == entity.DisplayName)
                {
                    f.DisplayName += "1";
                }
                //f.HybridName = Naming.GetProperHybridFieldName(f.DisplayName, f.Attribute);
            }
                           );

            AddEnityImageCRM2013(fields);
            AddLookupFields(fields);

            entity.Fields = fields.ToArray();
            entity.States = entityMetadata.Attributes.Where(a => a is StateAttributeMetadata).Select(a => MappingEnum.Parse(a as EnumAttributeMetadata)).FirstOrDefault();

            entity.Enums = entityMetadata.Attributes
                           .Where(a => a is PicklistAttributeMetadata || a is StateAttributeMetadata || a is StatusAttributeMetadata || a is BooleanAttributeMetadata)
                           .Select(a => MappingEnum.Parse(a)).ToArray();

            entity.PrimaryKey           = entity.Fields.First(f => f.Attribute.LogicalName == entity.Attribute.PrimaryKey);
            entity.PrimaryKeyProperty   = entity.PrimaryKey.DisplayName;
            entity.PrimaryNameAttribute = entityMetadata.PrimaryNameAttribute;

            entity.RelationshipsOneToMany = entityMetadata.OneToManyRelationships.Select(r =>
                                                                                         MappingRelationship1N.Parse(r, entity.Fields)).ToArray();

            entity.RelationshipsOneToMany.ToList().ForEach(r => {
                var newName = r.DisplayName;

                if (newName == entity.DisplayName || newName == entity.HybridName)
                {
                    newName = r.DisplayName += "1";
                }

                if (entity.Fields.Any(e => e.DisplayName == newName))
                {
                    newName = r.DisplayName += "2";
                }
            });


            entity.RelationshipsManyToOne = entityMetadata.ManyToOneRelationships.Select(r =>
                                                                                         MappingRelationshipN1.Parse(r, entity.Fields)).ToArray();

            entity.RelationshipsManyToOne.ToList().ForEach(r => {
                var newName = r.DisplayName;

                if (newName == entity.DisplayName || newName == entity.HybridName)
                {
                    newName = r.DisplayName += "1";
                }

                if (entity.Fields.Any(e => e.DisplayName == newName))
                {
                    newName = r.DisplayName += "2";
                }
            });

            var RelationshipsManyToMany = entityMetadata.ManyToManyRelationships.Select(r => MappingRelationshipMN.Parse(r, entity.LogicalName)).ToList();
            var selfReferenced          = RelationshipsManyToMany.Where(r => r.IsSelfReferenced).ToList();

            foreach (var referecned in selfReferenced)
            {
                var referencing = (MappingRelationshipMN)referecned.Clone();
                referencing.DisplayName = "Referencing" + Naming.GetProperVariableName(referecned.SchemaName);
                referencing.EntityRole  = "Microsoft.Xrm.Sdk.EntityRole.Referencing";
                RelationshipsManyToMany.Add(referencing);
            }
            RelationshipsManyToMany.ForEach(r => {
                var newName = r.DisplayName;

                if (newName == entity.DisplayName || newName == entity.HybridName)
                {
                    newName = r.DisplayName += "1";
                }

                if (entity.Fields.Any(e => e.DisplayName == newName))
                {
                    newName = r.DisplayName += "2";
                }
            });
            entity.RelationshipsManyToMany = RelationshipsManyToMany.OrderBy(r => r.DisplayName).ToArray();

            return(entity);
        }