예제 #1
0
        private Schema CreateResourceChildSchema(ResourceChildItem resourceChildItem, SwaggerResource swaggerResource)
        {
            var properties = resourceChildItem.Properties
                             .Select(
                p => new
            {
                IsRequired = p.IsIdentifying || !p.PropertyType.IsNullable,
                Key        = UniqueIdSpecification.GetUniqueIdPropertyName(p.JsonPropertyName).ToCamelCase(),
                Schema     = SwaggerDocumentHelper.CreatePropertySchema(p)
            }).Concat(
                resourceChildItem.References.Select(
                    r => new
            {
                r.IsRequired,
                Key    = r.PropertyName.ToCamelCase(),
                Schema = new Schema
                {
                    @ref = SwaggerDocumentHelper.GetDefinitionReference(
                        _swaggerDefinitionsFactoryNamingStrategy.GetReferenceName(swaggerResource.Resource, r))
                }
            })).Concat(
                resourceChildItem.Collections.Select(
                    c => new
            {
                IsRequired = c.Association.IsRequiredCollection,
                Key        = c.JsonPropertyName,
                Schema     = CreateCollectionSchema(c, swaggerResource)
            })).Concat(
                resourceChildItem.EmbeddedObjects.Select(
                    e => new
            {
                IsRequired = false,
                Key        = e.JsonPropertyName,
                Schema     = CreateEmbeddedObjectSchema(e, swaggerResource)
            })).ToList();

            var bridgeSchema = GetEdFiExtensionBridgeReferenceSchema(resourceChildItem, swaggerResource);

            if (bridgeSchema != null)
            {
                properties.Add(
                    new
                {
                    IsRequired = false,
                    Key        = ExtensionCollectionKey,
                    Schema     = bridgeSchema
                });
            }

            var requiredProperties = properties.Where(x => x.IsRequired).Select(x => x.Key).ToList();

            return(new Schema
            {
                type = "object",
                required = requiredProperties.Any()
                    ? requiredProperties
                    : null,
                properties = properties.ToDictionary(k => k.Key, v => v.Schema)
            });
        }
예제 #2
0
 /// <summary>
 /// Indicates whether the supplied property name is one that should be included
 /// in the resource model.
 /// </summary>
 /// <param name="entityPropertyName">The name of the property to be evaluated.</param>
 /// <returns><b>true</b> if the property is allowed to appear in the resource; otherwise <b>false</b>.</returns>
 public static bool IsAllowableResourceProperty(string entityPropertyName)
 {
     // Exclude boilerplate dates from resources
     return(!(entityPropertyName.EqualsIgnoreCase("LastModifiedDate") ||
              entityPropertyName.EqualsIgnoreCase("CreateDate") ||
              UniqueIdSpecification.IsUSI(entityPropertyName)));
 }
예제 #3
0
        private bool ShouldIncludeInQueryCriteria(PropertyDescriptor property, object value, TEntity entity)
        {
            // Null values and underscore-prefixed properties are ignored for specification purposes
            if (value == null || property.Name.StartsWith("_") || "|Url|".Contains(property.Name))
            {
                // TODO: Come up with better way to exclude non-data properties
                return(false);
            }

            Type valueType = value.GetType();

            // Only use value types (or strings), and non-default values (i.e. ignore 0's)
            var result = (valueType.IsValueType || valueType == typeof(string)) &&
                         (!value.Equals(valueType.GetDefaultValue()) ||
                          UniqueIdSpecification.IsUSI(property.Name) &&
                          GetPropertyValue(entity, UniqueIdSpecification.GetUniqueIdPropertyName(property.Name)) != null);

            // Don't include properties that are explicitly to be ignored
            result = result && !_propertiesToIgnore.Contains(property.Name);

            // Don't include UniqueId properties when they appear on a Person entity
            result = result &&
                     (!_uniqueIdProperties.Contains(property.Name) || PersonEntitySpecification.IsPersonEntity(entity.GetType()));

            return(result);
        }
예제 #4
0
        private PropertyData AssembleDerivedProperty(ResourceProperty property)
        {
            var propertyData = PropertyData.CreateDerivedProperty(property);

            if (property.EntityProperty.IsInheritedIdentifyingRenamed)
            {
                return(propertyData);
            }

            if (property.IsInherited)
            {
                var baseProperty = property.BaseEntityProperty();

                if (!baseProperty.IncomingAssociations.Any())
                {
                    propertyData[ResourceRenderer.RenderType] = ResourceRenderer.RenderStandard;
                    return(propertyData);
                }

                return(PropertyData.CreateReferencedProperty(
                           baseProperty.ToResourceProperty(property.Parent),
                           UniqueIdSpecification.IsUniqueId(property.PropertyName)
                        ? string.Format(
                               "A unique alphanumeric code assigned to a {0}.",
                               property.RemoveUniqueIdOrUsiFromPropertyName()
                               .ToCamelCase())
                        : property.Description.ScrubForXmlDocumentation(),
                           property.Parent.Name));
            }

            propertyData[ResourceRenderer.RenderType] = ResourceRenderer.RenderStandard;
            return(propertyData);
        }
예제 #5
0
        private bool IsUsiWithTransformedResourcePropertyName(EntityProperty property)
        {
            //Not: Use C# 7 '_' wildcard instead when available.
            string notUsed;

            //If the resource property name was flipped to a UniqueId for this USI property
            return(UniqueIdSpecification.IsUSI(property.PropertyName) &&
                   UniqueIdSpecification.TryGetUniqueIdPersonType(PropertyName, out notUsed));
        }
예제 #6
0
        private IEnumerable <KeyValuePair <string, object> > EnumerateKeyValuePairs(
            Hashtable sourceRow,
            NullValueHandling nullValueHandling,
            IEnumerable <string> keysToProcess,
            Dictionary <string, object> descriptorNamespaceByKey,
            HashSet <string> selectedKeys)
        {
            foreach (string key in keysToProcess)
            {
                string renamedKey = null;

                // Handle Pass through values
                if (key.EndsWith(CompositeDefinitionHelper.PassThroughMarker))
                {
                    renamedKey = key.TrimSuffix(CompositeDefinitionHelper.PassThroughMarker);
                    yield return(new KeyValuePair <string, object>(renamedKey ?? key, sourceRow[key]));
                }
                else
                {
                    // Remove null values, if appropriate
                    object value;

                    if (sourceRow[key] == null)
                    {
                        if (nullValueHandling == NullValueHandling.Include)
                        {
                            value = sourceRow[key];
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (descriptorNamespaceByKey.TryGetValue(key, out object namespaceForDescriptor))
                        {
                            value =
                                EdFiDescriptorReferenceSpecification.GetFullyQualifiedDescriptorReference(
                                    namespaceForDescriptor.ToString(),
                                    sourceRow[key]
                                    .ToString());
                        }
                        else
                        {
                            // See if we need to convert an USI to a UniqueId
                            if (UniqueIdSpecification.IsUSI(key) &&
                                UniqueIdSpecification.TryGetUSIPersonTypeAndRoleName(key, out string personType, out string roleName))
                            {
                                // Translate to UniqueId
                                string uniqueId    = _personUniqueIdToUsiCache.GetUniqueId(personType, (int)sourceRow[key]);
                                string uniqueIdKey = (roleName + personType + CompositeDefinitionHelper.UniqueId).ToCamelCase();

                                renamedKey = uniqueIdKey;
                                value      = uniqueId;
                            }
        public static int?GetMaxLength(ResourceProperty resourceProperty)
        {
            if (UniqueIdSpecification.IsUniqueId(resourceProperty.JsonPropertyName))
            {
                return(32);
            }

            return(resourceProperty.PropertyType.ToCSharp().EqualsIgnoreCase("string") && resourceProperty.PropertyType.MaxLength > 0
                ? resourceProperty.PropertyType.MaxLength
                : (int?)null);
        }
예제 #8
0
 private static PropertyType GetBasePersonUniqueIdPropertyType(EntityProperty property)
 {
     //we need to go find the correct PropertyType information by looking through
     //the incoming associations for the ones that have the USI property
     //and walking those entities until we find the person type that is the base of this
     //property, then return the entity's unique id property's property type from there.
     return(GetNestedPersonEntityProperty(property, property.PropertyName)
            .Entity.Properties
            .Where(x => !UniqueIdSpecification.IsUSI(x.PropertyName) && PersonEntitySpecification.IsPersonIdentifier(x.PropertyName))
            .Select(x => x.PropertyType)
            .Single());
 }
예제 #9
0
        /// <summary>
        /// Will convert a USI property to a UniqueID format
        /// If the property is not a USI type property, then an exception is thrown.
        /// </summary>
        /// <param name="usiPropertyName"></param>
        /// <returns></returns>
        public static string ConvertToUniqueId(this string usiPropertyName)
        {
            if (!UniqueIdSpecification.IsUSI(usiPropertyName))
            {
                throw new ArgumentException(
                          string.Format(
                              "Supplied property '{0}' is not an USI property.",
                              usiPropertyName));
            }

            return(UniqueIdSpecification.GetUniqueIdPropertyName(usiPropertyName));
        }
 private IEnumerable <AuthorizationContextProperty> UniqueIdProperties(Resource resource)
 {
     return(resource.Entity.Properties.Where(p => UniqueIdSpecification.IsUSI(p.PropertyName))
            .Select(
                p => new AuthorizationContextProperty
     {
         PropertyName = p.PropertyName, PropertyType = "int", IsIdentifying = p.IsIdentifying,
         IsIncluded = p.IsIdentifying, Reason = p.IsIdentifying
                                      ? "USI"
                                      : "Not part of primary key"
     }));
 }
예제 #11
0
        /// <summary>
        /// Converts surrogate id property names to their publicly visible counterparts.
        /// </summary>
        /// <param name="entityProperty">The property to be evaluated.</param>
        /// <returns>The property name appropriate for use on the model abstraction.</returns>
        public static string GetModelsInterfacePropertyName(this EntityProperty entityProperty)
        {
            if (entityProperty.IsLookup)
            {
                return(entityProperty.PropertyName.TrimSuffix("Id"));
            }

            if (UniqueIdSpecification.IsCoreUSI(entityProperty.PropertyName))
            {
                return(UniqueIdSpecification.GetUniqueIdPropertyName(entityProperty.PropertyName));
            }

            return(entityProperty.PropertyName);
        }
예제 #12
0
        private static string GetResourcePropertyName(EntityProperty property)
        {
            // Simplistic conversion using conventions
            if (property.IsLookup)
            {
                return(property.PropertyName.TrimSuffix("Id"));
            }

            // Convert USIs to UniqueIds everywhere but on the people
            if (UniqueIdSpecification.IsUSI(property.PropertyName) &&
                !PersonEntitySpecification.IsPersonEntity(property.Entity.Name))
            {
                return(property.PropertyName.Replace("USI", "UniqueId"));
            }

            return(property.PropertyName);
        }
예제 #13
0
        protected ResourceMemberBase(ResourceClassBase resourceClass, string propertyName)
        {
            ResourceClass = resourceClass;
            PropertyName  = propertyName;

            _jsonPropertyName = new Lazy <string>(
                () =>
            {
                var jsonPropertyName =
                    ResourceClass.AllProperties.Any(x => x.PropertyName == PropertyName) ||
                    ResourceClass.MemberNamesInvolvedInJsonCollisions.Contains(PropertyName)
                            ? PropertyName.ToCamelCase()
                            : JsonNamingConvention.ProposeJsonPropertyName(ParentFullName.Name, PropertyName);

                return(UniqueIdSpecification.IsUSI(jsonPropertyName)
                        ? UniqueIdSpecification.GetUniqueIdPropertyName(jsonPropertyName)
                        : jsonPropertyName);
            });
        }
예제 #14
0
        private string GetImplementedInterfaceString(ResourceClassBase resourceClass)
        {
            var interfaceStringBuilder = new StringBuilder();

            if (resourceClass.Entity?.IsDerived == true)
            {
                AddInterface(
                    $"{resourceClass.Entity.BaseEntity.SchemaProperCaseName()}.I{resourceClass.Entity.BaseEntity.Name}",
                    interfaceStringBuilder);
            }

            if (resourceClass.Entity?.IsAbstractRequiringNoCompositeId() != true)
            {
                AddInterface("ISynchronizable", interfaceStringBuilder);
                AddInterface("IMappable", interfaceStringBuilder);
            }

            // We want to exclude base concrete classes, descriptors and types from extensions.
            if (resourceClass.IsExtendable())
            {
                AddInterface("IHasExtensions", interfaceStringBuilder);
            }

            if (resourceClass is Resource)
            {
                AddInterface("IHasIdentifier", interfaceStringBuilder);
            }

            if (resourceClass.Properties.Where(p => p.IsIdentifying)
                .Any(p => UniqueIdSpecification.IsUniqueId(p.PropertyName) && p.IsLocallyDefined))
            {
                AddInterface("IIdentifiablePerson", interfaceStringBuilder);
            }

            AddInterface("IGetByExample", interfaceStringBuilder);

            return(interfaceStringBuilder.ToString());
        }
        private static IDictionary <string, List <string> > ExpectedPropertyNamesByDefinitionName(IEnumerable <Resource> resources)
        {
            var namingStrategy = new SwaggerDefinitionsFactoryDefaultNamingStrategy();

            var definitions = resources.Select(
                d => new
            {
                DefinitionName = namingStrategy.GetResourceName(d, new SwaggerResource(d)),
                Properties     = d.UnifiedKeyAllProperties().Select(p => p.JsonPropertyName).Concat(
                    d.Collections.Select(
                        c => c.IsDerivedEntityATypeEntity() && c.IsInherited
                                    ? c.Association.OtherEntity.PluralName.ToCamelCase()
                                    : c.JsonPropertyName)).Concat(d.EmbeddedObjects.Select(e => e.JsonPropertyName))
                                 .Concat(d.References.Select(r => r.PropertyName.ToCamelCase()))
            }).Concat(
                resources.SelectMany(r => r.AllContainedItemTypes).Select(
                    i => new
            {
                DefinitionName = namingStrategy.GetContainedItemTypeName(
                    new SwaggerResource(new Resource("TestResource")), i).ToCamelCase(),
                Properties = i.Properties
                             .Select(p => UniqueIdSpecification.GetUniqueIdPropertyName(p.JsonPropertyName))
                             .Concat(i.Collections.Select(c => c.JsonPropertyName))
                             .Concat(i.EmbeddedObjects.Select(e => e.JsonPropertyName))
                             .Concat(i.References.Select(r => r.PropertyName.ToCamelCase()))
            })).Concat(
                resources.SelectMany(x => x.AllContainedReferences).Distinct(ModelComparers.ReferenceTypeNameOnly).Select(
                    reference => new
            {
                DefinitionName = namingStrategy.GetReferenceName(new Resource("TestResource"), reference),
                Properties     = reference.ReferenceTypeProperties.Where(p => p.IsIdentifying).Select(
                    p => UniqueIdSpecification.GetUniqueIdPropertyName(p.JsonPropertyName))
            })).ToList();

            return(definitions.GroupBy(x => x.DefinitionName).Select(x => x.First()).ToDictionary(
                       k => k.DefinitionName.ToCamelCase(), v => v.Properties.ToList()));
        }
예제 #16
0
        public ResourceProperty(ResourceClassBase resourceClass, EntityProperty entityProperty)
            : base(resourceClass, GetResourcePropertyName(entityProperty))
        {
            EntityProperty = entityProperty;

            string personType;

            // Assign property characteristics
            IsLookup       = entityProperty.IsLookup;
            IsDirectLookup = entityProperty.IsDirectLookup;

            IsIdentifying = entityProperty.IsIdentifying ||
                            UniqueIdSpecification.TryGetUniqueIdPersonType(entityProperty.PropertyName, out personType) &&
                            personType == resourceClass.Name;

            IsLocallyDefined = entityProperty.IsLocallyDefined;
            IsServerAssigned = entityProperty.IsServerAssigned;

            LookupTypeName = entityProperty.LookupEntity == null
                ? null
                : entityProperty.LookupEntity.Name;

            DescriptorResource = entityProperty.LookupEntity == null
                ? null
                : resourceClass?.ResourceModel?.GetResourceByFullName(entityProperty.LookupEntity.FullName);

            PropertyType       = GetResourcePropertyType(entityProperty);
            Description        = entityProperty.Description;
            IsDeprecated       = entityProperty.IsDeprecated;
            DeprecationReasons = entityProperty.DeprecationReasons;

            // Cannot just use resourceClass.Name here because properties may be from a base class which
            // produces a different result.  Base class properties should retain their lineage
            // when "merged" into the resource model.
            ParentFullName = EntityProperty.Entity.FullName;
        }
예제 #17
0
        protected override object Build()
        {
            var resourceClassesToRender = ResourceModelProvider.GetResourceModel()
                                          .GetAllResources()
                                          .SelectMany(
                r => r.AllContainedItemTypesOrSelf.Where(
                    i => TemplateContext.ShouldRenderResourceClass(i)

                    // Don't render artifacts for base class children in the context of derived resources
                    && !i.IsInheritedChildItem()))
                                          .OrderBy(r => r.Name)
                                          .ToList();

            var entityInterfacesModel = new
            {
                EntitiesBaseNamespace =
                    EdFiConventions.BuildNamespace(
                        Namespaces.Entities.Common.BaseNamespace,
                        TemplateContext.SchemaProperCaseName),
                Interfaces = resourceClassesToRender
                             .Where(TemplateContext.ShouldRenderResourceClass)
                             .Select(
                    r => new
                {
                    r.FullName.Schema,
                    r.Name,
                    AggregateName         = r.Name,
                    ImplementedInterfaces = GetImplementedInterfaceString(r),
                    ParentInterfaceName   = GetParentInterfaceName(r),
                    ParentClassName       = GetParentClassName(r),
                    IdentifyingProperties = r
                                            .IdentifyingProperties

                                            // Exclude inherited identifying properties where the property has not been renamed
                                            .Where(
                        p => !(
                            p.EntityProperty
                            ?.IsInheritedIdentifying ==
                            true &&
                            !p
                            .EntityProperty
                            ?.IsInheritedIdentifyingRenamed ==
                            true))
                                            .OrderBy(
                        p => p
                        .PropertyName)
                                            .Select(
                        p =>
                        new
                    {
                        p.IsServerAssigned,
                        IsUniqueId
                            = UniqueIdSpecification
                              .IsUniqueId(
                                  p.PropertyName)
                              &&
                              PersonEntitySpecification
                              .IsPersonEntity(
                                  r.Name),
                        p.IsLookup,
                        CSharpType
                            = p
                              .PropertyType
                              .ToCSharp(
                                  false),
                        Name
                            = p
                              .PropertyName,
                        CSharpSafePropertyName
                            = p
                              .PropertyName
                              .MakeSafeForCSharpClass(
                                  r.Name),
                        LookupName
                            = p
                              .PropertyName
                    })
                                            .ToList(),
                    r.IsDerived,
                    InheritedNonIdentifyingProperties = r.IsDerived
                                ? r.AllProperties
                                                        .Where(p => p.IsInherited && !p.IsIdentifying)
                                                        .OrderBy(p => p.PropertyName)
                                                        .Where(IsModelInterfaceProperty)
                                                        .Select(
                        p =>
                        new
                    {
                        p.IsLookup,
                        CSharpType = p.PropertyType.ToCSharp(true),
                        Name       = p.PropertyName,
                        LookupName = p.PropertyName.TrimSuffix("Id")
                    })
                                                        .ToList()
                                : null,
                    NonIdentifyingProperties = r.NonIdentifyingProperties
                                               .Where(p => !p.IsInherited)
                                               .OrderBy(p => p.PropertyName)
                                               .Where(IsModelInterfaceProperty)
                                               .Select(
                        p =>
                        new
                    {
                        p.IsLookup,
                        CSharpType =
                            p.PropertyType.ToCSharp(true),
                        Name = p.PropertyName,
                        CSharpSafePropertyName =
                            p.PropertyName
                            .MakeSafeForCSharpClass(r.Name),
                        LookupName =
                            p.PropertyName.TrimSuffix("Id")
                    })
                                               .ToList(),
                    HasNavigableOneToOnes = r.EmbeddedObjects.Any(),
                    NavigableOneToOnes    = r
                                            .EmbeddedObjects
                                            .Where(eo => !eo.IsInherited)
                                            .OrderBy(
                        eo
                        => eo
                        .PropertyName)
                                            .Select(
                        eo
                        => new
                    {
                        Name
                            = eo
                              .PropertyName
                    })
                                            .ToList(),
                    InheritedLists = r.IsDerived
                                ? r.Collections
                                     .Where(c => c.IsInherited)
                                     .OrderBy(c => c.PropertyName)
                                     .Select(
                        c => new
                    {
                        c.ItemType.Name,
                        PluralName = c.PropertyName
                    })
                                     .ToList()
                                : null,
                    Lists = r.Collections
                            .Where(c => !c.IsInherited)
                            .OrderBy(c => c.PropertyName)
                            .Select(
                        c => new
                    {
                        c.ItemType.Name,
                        PluralName = c.PropertyName
                    })
                            .ToList(),
                    HasDiscriminator    = r.HasDiscriminator(),
                    AggregateReferences =
                        r.Entity?.GetAssociationsToReferenceableAggregateRoots()
                        .OrderBy(a => a.Name)
                        .Select(
                            a => new
                    {
                        AggregateReferenceName = a.Name,
                        MappedReferenceDataHasDiscriminator =
                            a.OtherEntity.HasDiscriminator()
                    })
                        .ToList()
                })
                             .ToList()
            };

            return(entityInterfacesModel);
        }
예제 #18
0
        public object Render()
        {
            AssociationView derivedBaseProperty = Property.DerivedBaseProperty();

            var derivedName = derivedBaseProperty != null
                ? derivedBaseProperty.OtherEntity.Name
                : null;

            var desc = this[ResourceRenderer.DescriptionOverride] != null
                ? this[ResourceRenderer.DescriptionOverride]
                       .ScrubForXmlDocumentation()
                : UniqueIdSpecification.IsUniqueId(Property.PropertyName)
                    ? string.Format(
                "A unique alphanumeric code assigned to a {0}.",
                Property.RemoveUniqueIdOrUsiFromPropertyName()
                .ToLower())
                    : Property.Description.ScrubForXmlDocumentation();

            var propertyNamespacePrefix = Property.ProperCaseSchemaName() == null
                ? null
                : $"{Namespaces.Entities.Common.RelativeNamespace}.{Property.ProperCaseSchemaName()}.";

            return(new
            {
                Description = desc,
                Misc = this[ResourceRenderer.MiscellaneousComment],
                JsonPropertyName = Property.JsonPropertyName,
                PropertyName = IsReferencedProperty
                    ? string.Format(
                    "backReference.{0} != null && backReference.{0}.{1}",
                    Property.EntityProperty.Entity.Aggregate.Name,
                    Property.PropertyName)
                    : Property.PropertyName,
                CSharpSafePropertyName = Property.PropertyName.MakeSafeForCSharpClass(Property.ParentFullName.Name),
                ParentName =
                    Property.EntityProperty.IsFromParent
                        ? Property.EntityProperty.Entity.Parent.Name
                        : Property.EntityProperty.Entity.Name,
                PropertyFieldName = Property.EntityProperty.Entity
                                    .ResolvedEdFiEntityName()
                                    .ToCamelCase(),
                PropertyType = Property.PropertyType.ToCSharp(true),
                IsFirstProperty = IsFirstProperty,
                IsLastProperty = IsLastProperty,
                IsUnique = IsUnique,
                NumericAttribute = Property.ToRangeAttributeCSharp(),
                IsDateOnlyProperty = Property.PropertyType.DbType == DbType.Date,
                IsTimeSpanProperty = Property.PropertyType.DbType == DbType.Time,
                ClassName = this[ResourceRenderer.ClassName]
                            ?? Property.EntityProperty.Entity
                            .ResolvedEdFiEntityName(),
                UnifiedKeys = Associations.Any()
                    ? AssembleOtherUnifiedChild(Associations)
                    : null,
                UnifiedExtensions = ExtensionAssociations.Any()
                    ? AssembleOtherUnifiedChild(ExtensionAssociations)
                    : null,
                ImplicitPropertyName = Associations.Any()
                    ? Associations.OrderByDescending(x => x.IsRequired)
                                       .First()
                                       .Name
                    : null,
                ImplicitNullable = Property.PropertyType.IsNullableCSharpType()
                    ? ".GetValueOrDefault()"
                    : null,
                ParentPropertyName = this[ResourceRenderer.ParentPropertyName],
                DerivedName = derivedName,
                PropertyNamespacePrefix = propertyNamespacePrefix,
                NullPropertyPrefix = Property.EntityProperty.Entity.IsEntityExtension
                    ? $"{propertyNamespacePrefix}I{Property.EntityProperty.Entity.Name}."
                    : $"{propertyNamespacePrefix}I{Property.EntityProperty.Entity.ResolvedEdFiEntityName()}."
            });
        }
예제 #19
0
        public static PropertyData CreateReferencedProperty(
            ResourceProperty property,
            string desc                = null,
            string className           = null,
            ResourceClassBase resource = null)
        {
            var propertyData = new PropertyData(property);

            var associations = resource == null || !resource.References.Any()
                ? property.EntityProperty.IncomingAssociations
                : resource.References.Where(
                r =>
                r.Properties.Contains(
                    property,
                    ModelComparers.ResourcePropertyNameOnly))
                               .Select(r => r.Association)
                               .ToList();

            // we want to prioritize identifiers that are not optional.
            var association =
                associations
                .OrderBy(x => x.ThisProperties.Any(y => y.PropertyType.IsNullable))
                .ThenBy(x => x.Name)
                .FirstOrDefault(
                    x => x.PropertyMappingByThisName.ContainsKey(property.PropertyName) ||
                    x.PropertyMappingByThisName.ContainsKey(property.EntityProperty.PropertyName));

            var parent = association != null
                ? association.PropertyMappingByThisName.ContainsKey(property.PropertyName)
                    ? association.PropertyMappingByThisName[property.PropertyName]
                         .OtherProperty
                    : association.PropertyMappingByThisName.ContainsKey(property.EntityProperty.PropertyName)
                        ? association.PropertyMappingByThisName[property.EntityProperty.PropertyName]
                         .OtherProperty
                        : null
                : null;

            string parentPropertyName = parent != null
                ? property.IsLookup
                    ? parent.PropertyName.TrimSuffix("Id")
                    : UniqueIdSpecification.GetUniqueIdPropertyName(parent.PropertyName)
                : property.ParentFullName.Name;

            propertyData[ResourceRenderer.ParentPropertyName] = UniqueIdSpecification.GetUniqueIdPropertyName(parentPropertyName);

            if (className != null)
            {
                propertyData[ResourceRenderer.ClassName] = className;
            }

            if (desc != null)
            {
                propertyData[ResourceRenderer.DescriptionOverride] = desc;
            }

            if (associations.Any())
            {
                propertyData.Associations.AddRange(associations);
            }

            if (property.IsLookup)
            {
                propertyData[ResourceRenderer.RenderType] = ResourceRenderer.RenderUnified;

                propertyData[ResourceRenderer.MiscellaneousComment] =
                    string.Format(
                        "// IS in a reference ({0}.{1}Id), IS a lookup column ",
                        className ?? property.EntityProperty.Entity.ResolvedEdFiEntityName(),
                        property.PropertyName);
            }
            else
            {
                propertyData[ResourceRenderer.MiscellaneousComment] = "// IS in a reference, NOT a lookup column ";
                propertyData[ResourceRenderer.RenderType]           = ResourceRenderer.RenderReferenced;
            }

            return(propertyData);
        }
 public static string PropertyDescription(ResourceProperty resourceProperty)
 => UniqueIdSpecification.IsUniqueId(resourceProperty.JsonPropertyName)
         ? $"A unique alphanumeric code assigned to a {UniqueIdSpecification.RemoveUniqueIdSuffix(resourceProperty.JsonPropertyName.ScrubForOpenApi()).ToLower()}."
         : resourceProperty.Description
 .ScrubForOpenApi();
 public static string PropertyFormat(ResourceProperty resourceProperty) => UniqueIdSpecification.IsUniqueId(resourceProperty.JsonPropertyName)
     ? null
     : resourceProperty.PropertyType.ToOpenApiFormat();
 public static string PropertyType(ResourceProperty resourceProperty) => resourceProperty.IsLookup ||
 UniqueIdSpecification.IsUniqueId(resourceProperty.JsonPropertyName)
     ? "string"
     : resourceProperty.PropertyType.ToOpenApiType();
예제 #23
0
        private void ProcessQueryStringParameters(HqlBuilderContext builderContext, CompositeDefinitionProcessorContext processorContext)
        {
            // Get all non "special" query string parameter for property value equality processing
            var queryStringParameters = GetCriteriaQueryStringParameters(builderContext);

            foreach (var queryStringParameter in queryStringParameters)
            {
                ResourceProperty targetProperty;

                // TODO: Embedded convention. Types and descriptors at the top level
                if (processorContext.CurrentResourceClass.AllPropertyByName.TryGetValue(queryStringParameter.Key, out targetProperty))
                {
                    string criteriaPropertyName;
                    object parameterValue;
                    string personType;

                    // Handle Lookup conversions
                    if (targetProperty.IsLookup)
                    {
                        var id = _descriptorsCache.GetId(
                            targetProperty.LookupTypeName,
                            Convert.ToString(queryStringParameter.Value));

                        criteriaPropertyName = targetProperty.EntityProperty.PropertyName;
                        parameterValue       = id;
                    }

                    // Handle UniqueId conversions
                    else if (UniqueIdSpecification.TryGetUniqueIdPersonType(targetProperty.PropertyName, out personType))
                    {
                        int usi = _personUniqueIdToUsiCache.GetUsi(personType, Convert.ToString(queryStringParameter.Value));

                        // TODO: Embedded convention - Convert UniqueId to USI from Resource model to query Entity model on Person entities
                        // The resource model maps uniqueIds to uniqueIds on the main entity(Student,Staff,Parent)
                        if (PersonEntitySpecification.IsPersonEntity(targetProperty.ParentFullName.Name))
                        {
                            criteriaPropertyName = targetProperty.EntityProperty.PropertyName.Replace("UniqueId", "USI");
                        }
                        else
                        {
                            criteriaPropertyName = targetProperty.EntityProperty.PropertyName;
                        }

                        parameterValue = usi;
                    }
                    else
                    {
                        criteriaPropertyName = targetProperty.PropertyName;
                        parameterValue       = ConvertParameterValueForProperty(targetProperty, Convert.ToString(queryStringParameter.Value));
                    }

                    // Add criteria to the query
                    builderContext.SpecificationWhere.AppendFormat(
                        "{0}{1}.{2} = :{2}",
                        AndIfNeeded(builderContext.SpecificationWhere),
                        builderContext.CurrentAlias,
                        criteriaPropertyName);

                    if (builderContext.CurrentQueryFilterParameterValueByName.ContainsKey(criteriaPropertyName))
                    {
                        throw new ArgumentException(
                                  string.Format(
                                      "The value for parameter '{0}' was already assigned and cannot be reassigned using the query string.",
                                      criteriaPropertyName));
                    }

                    builderContext.CurrentQueryFilterParameterValueByName[criteriaPropertyName] =
                        parameterValue;
                }
                else
                {
                    ThrowPropertyNotFoundException(queryStringParameter.Key);
                }
            }
        }
예제 #24
0
 /// <summary>
 /// Removes the trailing uniquid or usi from the property name.
 /// </summary>
 /// <param name="property"></param>
 /// <returns></returns>
 public static string RemoveUniqueIdOrUsiFromPropertyName(this ResourceProperty property)
 {
     return(UniqueIdSpecification.IsUniqueId(property.PropertyName)
         ? UniqueIdSpecification.RemoveUniqueIdSuffix(property.PropertyName)
         : UniqueIdSpecification.RemoveUsiSuffix(property.PropertyName));
 }
예제 #25
0
 /// <summary>
 /// Checks to see if the property is an USI property or if the property is a person entity
 /// </summary>
 /// <param name="property"></param>
 /// <returns></returns>
 public static bool IsPersonOrUsi(this ResourceProperty property)
 {
     return(property.Parent.Entity.IsPersonEntity() || UniqueIdSpecification.IsUSI(property.PropertyName));
 }
예제 #26
0
        public static IEnumerable <EntityProperty> TransformUsisToUniqueIds(this IEnumerable <EntityProperty> properties)
        {
            var suppliedProperties = properties.ToList();

            // Return an empty enumerable if there aren't any properties in the source
            if (!suppliedProperties.Any())
            {
                yield break;
            }

            var containingEntity = suppliedProperties
                                   .Select(x => x.Entity)
                                   .FirstOrDefault(x => x != null);

            if (containingEntity == null)
            {
                throw new InvalidOperationException("None of the properties supplied have an associated Entity.");
            }

            foreach (var entityProperty in suppliedProperties)
            {
                // If column is an USI column...
                if (UniqueIdSpecification.IsUSI(entityProperty.PropertyName))
                {
                    string uniqueIdPropertyName = entityProperty.PropertyName.ConvertToUniqueId();

                    // Find a corresponding UniqueId column, if it exists
                    var correspondingUniqueIdProperty = containingEntity
                                                        .Properties
                                                        .SingleOrDefault(p => p.PropertyName.EqualsIgnoreCase(uniqueIdPropertyName));

                    if (correspondingUniqueIdProperty != null)
                    {
                        // Swap the UniqueId column in for the USI
                        yield return(correspondingUniqueIdProperty);

                        continue;
                    }

                    // Replace the USI column with a newly created UniqueId column
                    yield return
                        (new EntityProperty(uniqueIdPropertyName,
                                            new PropertyType(DbType.AnsiString, 32, entityProperty.PropertyType.IsNullable),
                                            string.Format("A unique alpha-numeric code assigned to a {0}.", entityProperty.Entity.Name)));
                }
                else if (UniqueIdSpecification.IsUniqueId(entityProperty.PropertyName))
                {
                    string usiPropertyName = UniqueIdSpecification.GetUsiPropertyName(entityProperty.PropertyName);

                    // Find a corresponding USI column, if it exists
                    var correspondingUsiProperty = containingEntity
                                                   .Properties
                                                   .SingleOrDefault(p => p.PropertyName.EqualsIgnoreCase(usiPropertyName));

                    // If a corresponding USI property exists, then skip the UniqueId (it's been returned for use wherever the USI had been used)
                    if (correspondingUsiProperty != null)
                    {
                        continue;
                    }

                    yield return(entityProperty);
                }
                else
                {
                    yield return(entityProperty);
                }
            }
        }
예제 #27
0
 /// <summary>
 /// Checks to see if the property is an USI property or a UniqueId, and if the property is a person entity, similar as EntityMapper.IsDefiningUniqueId
 /// </summary>
 /// <param name="property"></param>
 /// <returns></returns>
 public static bool IsDefiningUniqueIdOrUsi(this ResourceProperty property)
 {
     return(property.Parent.Entity?.IsPersonEntity() == true &&
            (UniqueIdSpecification.IsUniqueId(property.PropertyName) ||
             UniqueIdSpecification.IsUSI(property.PropertyName)));
 }
예제 #28
0
 private static bool IsDefiningUniqueId(ResourceClassBase resourceClass, ResourceProperty property)
 {
     return(UniqueIdSpecification.IsUniqueId(property.PropertyName) &&
            PersonEntitySpecification.IsPersonEntity(resourceClass.Name));
 }