private void GenerateLists()
        {
            if (AttributeMetadataCache[LogicalName] == null)
            {
                throw new Exception("Failed to load metadata related to this entity.");
            }

            // choose non-primary attributes, and ones that don't represent others (like names of OptionSetValues)
            // sort by IsSelected, and then by name -- bubbles the selected to the top
            var attributes = from attributeQ in AttributeMetadataCache[LogicalName].Attributes
                             where (!attributeQ.IsPrimaryId.HasValue || !attributeQ.IsPrimaryId.Value) &&
                             string.IsNullOrEmpty(attributeQ.AttributeOf)
                             orderby EntityDataFilter.Attributes == null ||
                             EntityDataFilter.Attributes.Contains(attributeQ.LogicalName) descending,
                attributeQ.LogicalName
            select attributeQ;

            // if no filter, select all
            FieldsSelectAll = EntityDataFilter.Attributes != null &&
                              EntityDataFilter.Attributes.Length == attributes.Count();

            ReadOnlySelectAll = EntityDataFilter.ReadOnly != null &&
                                EntityDataFilter.ReadOnly.Length == attributes.Count();

            ClearFlagSelectAll = EntityDataFilter.ClearFlag != null &&
                                 EntityDataFilter.ClearFlag.Length == attributes.Count();

            foreach (var attribute in attributes)
            {
                var attributeAsync = attribute;

                Dispatcher.Invoke(() =>
                {
                    Fields.Add(new FieldGridRow
                    {
                        IsSelected =
                            EntityDataFilter.Attributes?.Contains(attributeAsync.LogicalName) == true,
                        Name        = attributeAsync.LogicalName,
                        DisplayName =
                            attributeAsync.DisplayName?.UserLocalizedLabel == null || !Settings.UseDisplayNames
                                                                                             ? Naming.GetProperVariableName(attributeAsync, Settings.TitleCaseLogicalNames)
                                                                                             : Naming.Clean(attributeAsync.DisplayName.UserLocalizedLabel.Label),
                        Rename =
                            EntityDataFilter.AttributeRenames?.FirstNotNullOrEmpty(attributeAsync.LogicalName),
                        Language =
                            EntityDataFilter.AttributeLanguages?.FirstNotNullOrEmpty(attributeAsync.LogicalName),
                        IsReadOnly = EntityDataFilter.ReadOnly?.Contains(attributeAsync.LogicalName) == true ||
                                     (attributeAsync.IsValidForCreate != true &&
                                      attributeAsync.IsValidForUpdate != true),
                        IsReadOnlyEnabled = attributeAsync.IsValidForCreate == true ||
                                            attributeAsync.IsValidForUpdate == true,
                        IsClearFlag =
                            EntityDataFilter.ClearFlag?.Contains(attributeAsync.LogicalName) == true
                    });
                });
            }

            var relations1N = from relation1nQ in AttributeMetadataCache[LogicalName].OneToManyRelationships
                              orderby EntityDataFilter.OneToN == null ||
                              EntityDataFilter.OneToN.Contains(relation1nQ.SchemaName) descending,
                relation1nQ.ReferencingEntity, relation1nQ.ReferencingAttribute
            select relation1nQ;

            // if no filter, select all
            Relations1NSelectAll = EntityDataFilter.OneToN != null &&
                                   EntityDataFilter.OneToN.Length == relations1N.Count();

            foreach (var relation1n in relations1N)
            {
                var relation1nAsync = relation1n;

                Dispatcher.Invoke(() =>
                {
                    var row = new Relations1NGridRow
                    {
                        IsSelected = EntityDataFilter.OneToN == null ||
                                     EntityDataFilter.OneToN.Contains(relation1nAsync.SchemaName),
                        Name     = relation1nAsync.SchemaName,
                        ToEntity = relation1nAsync.ReferencingEntity ?? "",
                        ToField  = relation1nAsync.ReferencingAttribute ?? "",
                        Rename   =
                            EntityDataFilter.OneToNRenames?.FirstNotNullOrEmpty(relation1nAsync.SchemaName),
                        IsReadOnlyEnabled = true,
                        IsReadOnly        = EntityDataFilter.OneToNReadOnly != null &&
                                            EntityDataFilter.OneToNReadOnly.ContainsKey(
                            relation1nAsync.SchemaName) &&
                                            EntityDataFilter.OneToNReadOnly[relation1nAsync.SchemaName]
                    };

                    Relations1N.Add(row);
                });
            }

            var relationsN1 = from relationN1Q in AttributeMetadataCache[LogicalName].ManyToOneRelationships
                              orderby EntityDataFilter.NToOne == null ||
                              EntityDataFilter.NToOne.Contains(relationN1Q.SchemaName) descending,
                relationN1Q.ReferencedEntity, relationN1Q.ReferencingAttribute
            select relationN1Q;

            // if no filter, select all
            RelationsN1SelectAll = EntityDataFilter.NToOne != null &&
                                   EntityDataFilter.NToOne.Length == relationsN1.Count();

            foreach (var relationN1 in relationsN1)
            {
                var relationN1Async = relationN1;

                Dispatcher.Invoke(() =>
                {
                    var row = new RelationsN1GridRow
                    {
                        IsSelected = EntityDataFilter.NToOne == null ||
                                     EntityDataFilter.NToOne.Contains(relationN1Async.SchemaName),
                        Name      = relationN1Async.SchemaName,
                        ToEntity  = relationN1Async.ReferencedEntity ?? "",
                        FromField = relationN1Async.ReferencingAttribute ?? "",
                        Rename    = EntityDataFilter.NToOneRenames?
                                    .FirstNotNullOrEmpty(relationN1Async.SchemaName),
                        IsFlatten = EntityDataFilter.NToOneFlatten != null &&
                                    EntityDataFilter.NToOneFlatten.ContainsKey(
                            relationN1Async.SchemaName) &&
                                    EntityDataFilter.NToOneFlatten[relationN1Async.SchemaName],
                        IsReadOnlyEnabled = true,
                        IsReadOnly        = EntityDataFilter.NToOneReadOnly != null &&
                                            EntityDataFilter.NToOneReadOnly.ContainsKey(
                            relationN1Async.SchemaName) &&
                                            EntityDataFilter.NToOneReadOnly[relationN1Async.SchemaName]
                    };

                    RelationsN1.Add(row);
                });
            }

            var relationsNN = from relationNNQ in AttributeMetadataCache[LogicalName].ManyToManyRelationships
                              orderby EntityDataFilter.NToN == null ||
                              EntityDataFilter.NToN.Contains(relationNNQ.SchemaName) descending,
            (relationNNQ.Entity1LogicalName == LogicalName)
                                                          ? relationNNQ.Entity2LogicalName
                                                          : (relationNNQ.Entity1LogicalName ?? ""),
            relationNNQ.IntersectEntityName
            select relationNNQ;

            // if no filter, select all
            RelationsNNSelectAll = EntityDataFilter.NToN != null &&
                                   EntityDataFilter.NToN.Length == relationsNN.Count();

            foreach (var relationNN in relationsNN)
            {
                var relationNNAsync = relationNN;

                Dispatcher.Invoke(() =>
                {
                    var row = new RelationsNNGridRow
                    {
                        IsSelected = EntityDataFilter.NToN == null ||
                                     EntityDataFilter.NToN.Contains(relationNNAsync.SchemaName),
                        Name     = relationNNAsync.SchemaName,
                        ToEntity = relationNNAsync.Entity1LogicalName == LogicalName
                                                                                               ? relationNNAsync.Entity2LogicalName
                                                                                               : (relationNNAsync.Entity1LogicalName ?? ""),
                        IntersectEntity   = relationNNAsync.IntersectEntityName ?? "",
                        Rename            = EntityDataFilter.NToNRenames?.FirstNotNullOrEmpty(relationNNAsync.SchemaName),
                        IsReadOnlyEnabled = true,
                        IsReadOnly        = EntityDataFilter.NToNReadOnly != null &&
                                            EntityDataFilter.NToNReadOnly.ContainsKey(
                            relationNNAsync.SchemaName) &&
                                            EntityDataFilter.NToNReadOnly[relationNNAsync.SchemaName]
                    };

                    RelationsNN.Add(row);
                });
            }
        }
        private void InitEntityList(List <string> filter = null)
        {
            Dispatcher.Invoke(Entities.Clear);

            var rowList = new List <EntitiesSelectionGridRow>();

            var filteredEntities = EntityMetadataCache
                                   .Where(entity => filter == null || filter.Contains(entity.LogicalName)).ToArray();

            foreach (var entity in filteredEntities)
            {
                var entityAsync = entity;

                Dispatcher.Invoke(() =>
                {
                    var row = new EntitiesSelectionGridRow
                    {
                        IsSelected  = Settings.EntitiesSelected.Contains(entity.LogicalName),
                        Name        = entityAsync.LogicalName,
                        DisplayName =
                            entity.DisplayName?.UserLocalizedLabel == null || !Settings.UseDisplayNames
                                                                                            ? Naming.GetProperHybridName(entity.SchemaName, entity.LogicalName)
                                                                                            : Naming.Clean(entity.DisplayName.UserLocalizedLabel.Label),
                        IsFiltered        = Settings.FilteredEntities.Contains(entity.LogicalName),
                        IsGenerateMeta    = Settings.PluginMetadataEntitiesSelected.Contains(entity.LogicalName),
                        IsJsEarly         = Settings.JsEarlyBoundEntitiesSelected.Contains(entity.LogicalName),
                        IsActions         = Settings.ActionEntitiesSelected.Contains(entity.LogicalName),
                        IsOptionsetLabels =
                            Settings.OptionsetLabelsEntitiesSelected.Contains(entity.LogicalName),
                        IsLookupLabels = Settings.LookupLabelsEntitiesSelected.Contains(entity.LogicalName)
                    };

                    row.PropertyChanged += (sender, args) =>
                    {
                        if (args.PropertyName == "IsSelected")
                        {
                            if (row.IsSelected &&
                                !Settings.EntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.EntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsSelected &&
                                     Settings.EntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.EntitiesSelected.Remove(entity.LogicalName);
                            }
                        }
                        else if (args.PropertyName == "IsGenerateMeta")
                        {
                            if (row.IsGenerateMeta &&
                                !Settings.PluginMetadataEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.PluginMetadataEntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsGenerateMeta &&
                                     Settings.PluginMetadataEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.PluginMetadataEntitiesSelected.Remove(entity.LogicalName);
                            }
                        }
                        else if (args.PropertyName == "IsJsEarly")
                        {
                            if (row.IsJsEarly &&
                                !Settings.JsEarlyBoundEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.JsEarlyBoundEntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsJsEarly &&
                                     Settings.JsEarlyBoundEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.JsEarlyBoundEntitiesSelected.Remove(entity.LogicalName);
                            }
                        }
                        else if (args.PropertyName == "IsActions")
                        {
                            if (row.IsActions &&
                                !Settings.ActionEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.ActionEntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsActions &&
                                     Settings.ActionEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.ActionEntitiesSelected.Remove(entity.LogicalName);
                            }
                        }
                        else if (args.PropertyName == "IsOptionsetLabels")
                        {
                            if (row.IsOptionsetLabels &&
                                !Settings.OptionsetLabelsEntitiesSelected.Contains(
                                    entity.LogicalName))
                            {
                                Settings.OptionsetLabelsEntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsOptionsetLabels &&
                                     Settings.OptionsetLabelsEntitiesSelected.Contains(
                                         entity.LogicalName))
                            {
                                if (Settings.EntityDataFilterArray.EntityFilters
                                    .SelectMany(filterQ => filterQ.EntityFilterList)
                                    .Any(dataFilter => dataFilter.LogicalName == entity.LogicalName &&
                                         dataFilter.IsOptionsetLabels))
                                {
                                    row.IsOptionsetLabels = true;
                                }
                                else
                                {
                                    Settings.OptionsetLabelsEntitiesSelected.Remove(entity.LogicalName);
                                }
                            }
                        }
                        else if (args.PropertyName == "IsLookupLabels")
                        {
                            if (row.IsLookupLabels &&
                                !Settings.LookupLabelsEntitiesSelected.Contains(entity.LogicalName))
                            {
                                Settings.LookupLabelsEntitiesSelected.Add(entity.LogicalName);
                            }
                            else if (!row.IsLookupLabels &&
                                     Settings.LookupLabelsEntitiesSelected.Contains(entity.LogicalName))
                            {
                                if (Settings.EntityDataFilterArray.EntityFilters
                                    .SelectMany(filterQ => filterQ.EntityFilterList)
                                    .Any(dataFilter => dataFilter.LogicalName == entity.LogicalName &&
                                         dataFilter.IsLookupLabels))
                                {
                                    row.IsLookupLabels = true;
                                }
                                else
                                {
                                    Settings.LookupLabelsEntitiesSelected.Remove(entity.LogicalName);
                                }
                            }
                        }
                    };

                    rowList.Add(row);
                });
            }

            foreach (var row in rowList.OrderByDescending(row => row.IsSelected).ThenBy(row => row.Name))
            {
                Dispatcher.Invoke(() => Entities.Add(row));
            }

            // selectAll status based on selection count
            if (filteredEntities.All(entity => rowList.Where(row => row.IsSelected).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => EntitiesSelectAll = true);
            }

            if (filteredEntities.All(entity => rowList.Where(row => row.IsGenerateMeta).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => IsMetadataSelectAll = true);
            }

            if (filteredEntities.All(entity => rowList.Where(row => row.IsJsEarly).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => IsJsEarlySelectAll = true);
            }

            if (filteredEntities.All(entity => rowList.Where(row => row.IsActions).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => IsActionsSelectAll = true);
            }

            if (filteredEntities.All(entity => rowList.Where(row => row.IsOptionsetLabels).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => IsOptionsetLabelsSelectAll = true);
            }

            if (filteredEntities.All(entity => rowList.Where(row => row.IsLookupLabels).Select(row => row.Name)
                                     .Contains(entity.LogicalName)))
            {
                Dispatcher.Invoke(() => IsLookupLabelsSelectAll = true);
            }
        }
Example #3
0
        private void InitEntityList()
        {
            Dispatcher.Invoke(Entities.Clear);

            var rowList = new List <EntityGridRow>();

            foreach (var entity in EntityMetadataCache)
            {
                var entityAsync = entity;

                Dispatcher.Invoke(() =>
                {
                    var dataFilter = EntityFilter.EntityFilterList
                                     .FirstOrDefault(filter => filter.LogicalName == entityAsync.LogicalName);

                    if (dataFilter == null)
                    {
                        dataFilter = new EntityDataFilter(entityAsync.LogicalName);
                        EntityFilter.EntityFilterList.Add(dataFilter);
                    }

                    var row = new EntityGridRow
                    {
                        IsSelected  = !dataFilter.IsExcluded,
                        Name        = entityAsync.LogicalName,
                        DisplayName =
                            entity.DisplayName?.UserLocalizedLabel == null || !Settings.UseDisplayNames
                                                                                            ? Naming.GetProperHybridName(entity.SchemaName, entity.LogicalName)
                                                                                            : Naming.Clean(entity.DisplayName.UserLocalizedLabel.Label),
                        Rename            = dataFilter.EntityRename,
                        IsGenerateMeta    = dataFilter.IsGenerateMeta,
                        IsOptionsetLabels = dataFilter.IsOptionsetLabels,
                        IsLookupLabels    = dataFilter.IsLookupLabels,
                        ValueClearMode    = dataFilter.ValueClearMode == null
                                                                                                     ? ClearModeEnumUi.Default
                                                                                                     : (ClearModeEnumUi)dataFilter.ValueClearMode
                    };

                    row.PropertyChanged += (sender, args) =>
                    {
                        if (args.PropertyName == "IsSelected")
                        {
                            dataFilter.IsExcluded = !row.IsSelected;
                        }
                        else if (args.PropertyName == "IsGenerateMeta")
                        {
                            dataFilter.IsGenerateMeta = row.IsGenerateMeta;
                        }
                        else if (args.PropertyName == "IsOptionsetLabels")
                        {
                            dataFilter.IsOptionsetLabels = row.IsOptionsetLabels;
                        }
                        else if (args.PropertyName == "IsLookupLabels")
                        {
                            dataFilter.IsLookupLabels = row.IsLookupLabels;
                        }
                        else if (args.PropertyName == "Rename")
                        {
                            dataFilter.EntityRename = row.Rename;
                        }
                        else if (args.PropertyName == "ValueClearMode")
                        {
                            switch (row.ValueClearMode)
                            {
                            case ClearModeEnumUi.Default:
                                dataFilter.ValueClearMode = null;
                                break;

                            default:
                                dataFilter.ValueClearMode =
                                    (ClearModeEnum?)row.ValueClearMode;
                                break;
                            }
                        }
                    };

                    rowList.Add(row);
                });
            }

            foreach (var row in rowList.OrderByDescending(row => row.IsSelected).ThenBy(row => row.Name))
            {
                Dispatcher.Invoke(() => Entities.Add(row));
            }

            // if no filter, select all
            if (EntityFilter.EntityFilterList.Count(filter => !filter.IsExcluded)
                == EntityMetadataCache.Count)
            {
                Dispatcher.Invoke(() => EntitiesSelectAll = true);
            }

            if (EntityFilter.EntityFilterList.Count(filter => filter.IsOptionsetLabels)
                == EntityMetadataCache.Count)
            {
                Dispatcher.Invoke(() => IsOptionsetLabelsSelectAll = true);
            }

            if (EntityFilter.EntityFilterList.Count(filter => filter.IsLookupLabels)
                == EntityMetadataCache.Count)
            {
                Dispatcher.Invoke(() => IsLookupLabelsSelectAll = true);
            }
        }
        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 #5
0
        public static MappingEnum GetMappingEnum(AttributeMetadata picklist, MappingEnum mappingEnum, bool isTitleCaseLogicalName)
        {
            mappingEnum = mappingEnum
                          ?? new MappingEnum
            {
                MetadataId = picklist.MetadataId
            };

            if (picklist.SchemaName != null)
            {
                mappingEnum.DisplayName = Naming.GetProperVariableName(picklist, isTitleCaseLogicalName);
            }

            mappingEnum.LogicalName = picklist.LogicalName ?? mappingEnum.LogicalName;
            mappingEnum.Items       = new MapperEnumItem[0];

            var attributeAsEnum = picklist as EnumAttributeMetadata;

            if (attributeAsEnum?.OptionSet != null && attributeAsEnum.OptionSet.Options.Count > 0)
            {
                var newItems = new List <MapperEnumItem>();

                var isGlobal = attributeAsEnum.OptionSet.IsGlobal == true;

                if (isGlobal)
                {
                    var label       = attributeAsEnum.OptionSet.DisplayName?.UserLocalizedLabel?.Label;
                    var displayName = Naming.GetProperVariableName(attributeAsEnum.OptionSet.Name, isTitleCaseLogicalName);

                    mappingEnum.Global =
                        new MapperEnumGlobal
                    {
                        EnumName     = attributeAsEnum.OptionSet.Name,
                        FriendlyName = Naming.Clean(
                            string.IsNullOrEmpty(label)
                                                                        ? Naming.Clean(displayName)
                                                                        : Naming.Clean(label)),
                        DisplayName = displayName,
                        LogicalName = attributeAsEnum.OptionSet.Name
                    };
                }

                mappingEnum.EnumName = mappingEnum.LogicalName;

                newItems.AddRange(attributeAsEnum.OptionSet.Options
                                  .Where(o => o.Label.UserLocalizedLabel != null)
                                  .Select(e => GetEnumItem(e, isTitleCaseLogicalName)));

                mappingEnum.Items = newItems.ToArray();
            }
            else
            {
                var attributeAsBool = picklist as BooleanAttributeMetadata;

                if (attributeAsBool?.OptionSet != null)
                {
                    var newItems = new List <MapperEnumItem>();

                    var trueOption = attributeAsBool.OptionSet.TrueOption;

                    if (trueOption.Label.UserLocalizedLabel != null)
                    {
                        newItems.Add(GetEnumItem(trueOption, isTitleCaseLogicalName));
                    }

                    var falseOption = attributeAsBool.OptionSet.FalseOption;

                    if (falseOption.Label.UserLocalizedLabel != null)
                    {
                        newItems.Add(GetEnumItem(falseOption, isTitleCaseLogicalName));
                    }

                    mappingEnum.Items = newItems.ToArray();
                }
            }

            var duplicates = new Dictionary <string, int>();

            foreach (var item in mappingEnum.Items)
            {
                if (duplicates.ContainsKey(item.Name))
                {
                    duplicates[item.Name] = duplicates[item.Name] + 1;
                    item.Name            += "_" + duplicates[item.Name];
                }
                else
                {
                    duplicates[item.Name] = 1;
                }
            }

            mappingEnum.IsMultiSelect = picklist is MultiSelectPicklistAttributeMetadata;

            return(mappingEnum);
        }