Пример #1
0
        public MethodInfo GetMapperMethod <TEntity>()
        {
            string entityName = typeof(TEntity).Name;

            string mapperTypeName = string.Format(
                "{0}.{1}Mapper",
                EdFiConventions.BuildNamespace(Namespaces.Entities.Common.BaseNamespace, EdFiConventions.ProperCaseName),
                entityName);

            // TODO: Embedded convention - Mapper type namespace
            var mapperType = Type.GetType(
                mapperTypeName + ", " + typeof(Marker_EdFi_Ods_Standard).Assembly.GetName()
                .Name);

            BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;

            var mapperMethod = mapperType.GetMethod("MapTo", bindingFlags);

            if (mapperMethod == null)
            {
                mapperMethod = mapperType.GetMethod("MapDerivedTo", bindingFlags);

                if (mapperMethod == null)
                {
                    throw new Exception($"Unable to find MapTo or MapDerivedTo method on type '{mapperType.FullName}'.");
                }
            }

            return(mapperMethod);
        }
Пример #2
0
 protected override void Act()
 {
     _actualResult =
         EdFiConventions.BuildNamespace(
             $"{Namespaces.Resources.BaseNamespace}",
             EdFiConventions.ProperCaseName);
 }
Пример #3
0
 protected override object Build()
 {
     return(new
     {
         CommonRecordsNamespace =
             EdFiConventions.BuildNamespace(
                 Namespaces.Entities.Records.BaseNamespace,
                 TemplateContext.SchemaProperCaseName),
         Interfaces =
             TemplateContext.DomainModelProvider.GetDomainModel()
             .Entities
             .Where(TemplateContext.ShouldRenderEntity)
             .Select(
                 e => new
         {
             e.Schema,
             AggregateRootName = e.Aggregate.AggregateRoot.Name,
             EntityName = e.Name,
             EntityProperties = e.EntityRecordInterfaceUnifiedProperties()
                                .OrderBy(
                 p => p.PropertyName)
                                .Select(
                 p => new
             {
                 PropertyType = p.PropertyType.ToCSharp(true),
                 CSharpSafePropertyName =
                     p.PropertyName.MakeSafeForCSharpClass(e.Name)
             })
         })
     });
 }
Пример #4
0
 private string GetNamespace(Resource resource)
 {
     return
         (EdFiConventions.BuildNamespace(
              Namespaces.Requests.BaseNamespace,
              TemplateContext.SchemaProperCaseName,
              resource.Entity.PluralName,
              resource.Entity.IsExtensionEntity));
 }
Пример #5
0
 protected override void Act()
 {
     _actualResult =
         EdFiConventions.BuildNamespace(
             $"{Namespaces.Resources.BaseNamespace}",
             "Sample",
             "StaffExtension",
             isExtensionObject: true);
 }
Пример #6
0
 protected override void Act()
 {
     _actualResult = EdFiConventions.CreateResourceNamespace(
         "SchemaProperCaseName",
         "ResourceName",
         null,
         null,
         null,
         null);
 }
Пример #7
0
        private string GetResourceClassTypeName(Resource resource, string profileName)
        {
            string resourceNamespace =
                EdFiConventions.CreateResourceNamespace(
                    resource,
                    GetProfileNamespaceName(profileName),
                    "_Writable");

            return($"{resourceNamespace}.{resource.Name}");
        }
Пример #8
0
 protected override void Act()
 {
     _actualResult = EdFiConventions.CreateResourceNamespace(
         "SchemaProperCaseName",
         "ResourceName",
         "ProfileNamespaceName",
         "ReadableWritableContext",
         null,
         "ExtensionSchemaProperCaseName");
 }
Пример #9
0
 private string FormatControllersNamespace(StandardizedResourceProfileData resourceData)
 {
     return(string.Format(
                "{0}{1}",
                EdFiConventions.BuildNamespace(
                    BaseNamespaceName,
                    TemplateContext.GetSchemaProperCaseNameForResource(resourceData.ResolvedResource),
                    resourceData.ResolvedResource.PluralName,
                    resourceData.ResolvedResource.Entity.IsExtensionEntity),
                resourceData.ProfileNamespaceSection));
 }
Пример #10
0
 private EdFiAuthorizationContext CreateAuthorizationContext(
     HttpActionContext actionContext,
     EdFiAuthorizationAttribute authorizationAttribute)
 {
     return(new EdFiAuthorizationContext(
                (ClaimsPrincipal)actionContext.RequestContext.Principal,
                EdFiConventions.GetApiResourceClaimUris(authorizationAttribute.Resource),
                _securityRepository.GetActionByHttpVerb(actionContext.Request.Method.Method)
                .ActionUri,
                null as object));
 }
        private string GetResourceTypeName(Resource resource, string profileName = null)
        {
            string resourceNamespace = EdFiConventions.CreateResourceNamespace(
                resource,
                profileName?.Replace('-', '_'),
                profileName == null
                    ? null
                    : "_Writable");

            return($"{resourceNamespace}.{resource.Name}");
        }
        protected override object Build()
        {
            var model =
                new
            {
                ClaimsNamespace   = Namespaces.Common.Claims,
                EntitiesNamespace =
                    EdFiConventions.BuildNamespace(
                        Namespaces.Entities.Common.BaseNamespace,
                        TemplateContext.SchemaProperCaseName),
                AuthorizationStrategyNamespace = Namespaces.Security.Relationships,
                AggregateEntityIncludes        = GetAggregateEntityIncludes()
                                                 .Select(
                    i => new { Include = i }),
                ContextDataProviderNamespace =
                    EdFiConventions.BuildNamespace(
                        Namespaces.Security.ContextDataProviders,
                        TemplateContext.SchemaProperCaseName),
                ResourcesToRender = _authorizationPropertiesByResource.Select(
                    r => new
                {
                    r.Key.Entity.Schema,
                    ResourceName                    = r.Key.Name,
                    ResourceNameCamelCase           = r.Key.Name.ToCamelCase(),
                    SchemaIsEdFi                    = r.Key.IsEdFiResource(),
                    AuthorizationResourceProperties = r.Value.OrderBy(p => p.PropertyName)
                                                      .Select(
                        p => new
                    {
                        ContextPropertyIsIncludedAndNumeric
                            = p.IsIncluded && p
                              .IsNumeric,
                        ContextPropertyIsIncludedOrNumeric
                            = p.IsIncluded ^ p
                              .IsNumeric,
                        ContextPropertyIsNotIncludedAndNumeric
                            = !p.IsIncluded && p
                              .IsNumeric,
                        ContextPropertyName =
                            p.PropertyName,
                        ContextPropertyType =
                            p.PropertyType,
                        ContextPropertyReason =
                            p.Reason,
                        p.IsIdentifying,
                        p.IsIncluded
                    })
                })
            };

            return(model);
        }
Пример #13
0
        private string GetNamespace(Resource resource, string profileName)
        {
            string baseNamespace = EdFiConventions.BuildNamespace(
                Namespaces.Requests.BaseNamespace,
                TemplateContext.GetSchemaProperCaseNameForResource(resource),
                resource.Entity.PluralName,
                resource.Entity.IsExtensionEntity);

            return(string.Format(
                       "{0}.{1}",
                       baseNamespace,
                       GetProfileNamespaceName(profileName)));
        }
Пример #14
0
        protected override object Build()
        {
            var resources = ResourceModelProvider.GetResourceModel()
                            .GetAllResources();

            var aggregates = resources
                             .Select(
                r => new
            {
                ResourceName = r.Name, ResourceClasses =

                    // Add the root resource class (if it's not abstract or it has a composite id)
                    (r.Entity?.IsAbstractRequiringNoCompositeId() != true && TemplateContext.ShouldRenderResourceClass(r)
                                                  ? new ResourceClassBase[]
                {
                    r
                }
                                                  : new ResourceClassBase[0])

                    // Add in non-inherited child items
                    .Concat(
                        r.AllContainedItemTypes
                        .Where(
                            t => TemplateContext.ShouldRenderResourceClass(t) &&
                            !t.IsInheritedChildItem))
                    .ToList()
            })
                             .Where(x => x.ResourceClasses.Any())
                             .OrderBy(x => x.ResourceName)
                             .Select(
                x => new
            {
                AggregateName = x.ResourceName, Mappers = x.ResourceClasses
                                                          .OrderBy(y => y.Name)
                                                          .Select(BuildMapper)
            });

            var hasDerivedResources = resources.Any(r => r.IsDerived);

            return(new
            {
                HasDerivedResources = hasDerivedResources, NamespaceName =
                    EdFiConventions.BuildNamespace(
                        Namespaces.Entities.Common.BaseNamespace,
                        TemplateContext.SchemaProperCaseName),
                Aggregates = aggregates
            });
        }
Пример #15
0
        private string FormatEntityInterface(ResourceClassBase resource)
        {
            string properCaseName = resource.IsEdFiResource()
                ? TemplateContext.SchemaProperCaseName
                : resource.ResourceModel.SchemaNameMapProvider
                                    .GetSchemaMapByPhysicalName(resource.Entity.Schema)
                                    .ProperCaseName;

            return(RemoveEdFiNamespacePrefix(
                       string.Format(
                           "{0}.I{1}",
                           EdFiConventions.BuildNamespace(
                               Namespaces.Entities.Common.BaseNamespace,
                               properCaseName),
                           resource.Name)));
        }
Пример #16
0
        private string FormatDeleteRequest(StandardizedResourceProfileData resourceData)
        {
            //For some reason delete is included in the read only profiles.
            //If that ever changes:
            //FormatWritableRequest(resourceData, "Delete");

            return(string.Format(
                       "{0}{1}.{2}{3}",
                       EdFiConventions.BuildNamespace(
                           Namespaces.Requests.RelativeNamespace,
                           TemplateContext.GetSchemaProperCaseNameForResource(resourceData.ResolvedResource),
                           resourceData.ResolvedResource.PluralName,
                           resourceData.ResolvedResource.Entity.IsExtensionEntity),
                       resourceData.ProfileNamespaceSection,
                       resourceData.ResolvedResource.Name,
                       "Delete"));
        }
Пример #17
0
        private string FormatWritableRequest(StandardizedResourceProfileData resourceData, string requestType)
        {
            if (resourceData.Writable == null)
            {
                return(FormatNullWriteRequest(resourceData));
            }

            return(string.Format(
                       "{0}{1}.{2}{3}",
                       EdFiConventions.BuildNamespace(
                           Namespaces.Requests.RelativeNamespace,
                           TemplateContext.GetSchemaProperCaseNameForResource(resourceData.ResolvedResource),
                           resourceData.Writable.PluralName,
                           resourceData.Writable.Entity.IsExtensionEntity),
                       resourceData.ProfileNamespaceSection,
                       resourceData.Writable.Name,
                       requestType));
        }
Пример #18
0
        private string FormatResourceWriteModel(StandardizedResourceProfileData resourceData)
        {
            if (resourceData.Writable == null)
            {
                return(FormatNullWriteRequest(resourceData));
            }

            return(RemoveEdFiNamespacePrefix(
                       string.Format(
                           "{0}.{1}",
                           EdFiConventions.CreateResourceNamespace(
                               resourceData.Writable,
                               resourceData.ProfileNamespaceName,
                               resourceData.ProfileNamespaceName != null
                            ? "_Writable"
                            : null),
                           resourceData.Writable.Name)));
        }
Пример #19
0
        protected override object Build()
        {
            var profileDatas = _resourceProfileProvider
                               .GetResourceProfileData()
                               .ToList();

            var schemaNameMapProvider = TemplateContext.DomainModelProvider.GetDomainModel()
                                        .SchemaNameMapProvider;

            // NOTE: for model matching only we need to include abstract models
            return(new
            {
                ResourceContexts = profileDatas
                                   .SelectMany(CreateResourceContextModels)
                                   .Where(rc => rc != null)
                                   .ToList(),
                SchemaNamespaces = GetSchemaProperCaseNames(profileDatas, schemaNameMapProvider)
                                   .Select(
                    x => new { Namespace = EdFiConventions.BuildNamespace(Namespaces.Entities.Common.BaseNamespace, x) }),
                ProperCaseName = TemplateContext.SchemaProperCaseName,
                IsExtensionContext = TemplateContext.IsExtension
            });
        }
Пример #20
0
 protected override void Act()
 {
     EdFiConventions.CreateResourceNamespace("SchemaProperCaseName", "ResourceName", null, null, "ConcreteContext", null);
 }
Пример #21
0
        private object CreateResourceClass(ResourceProfileData profileData, ResourceClassBase resourceClass)
        {
            // NOTE model matching
            if (resourceClass.IsAbstract())
            {
                return(new
                {
                    ResourceReference = new
                    {
                        ReferenceName = resourceClass.Name,
                        ReferenceIdentifiers =
                            _resourcePropertyRenderer.AssembleIdentifiers(profileData, resourceClass),
                        Href = AssembleHref(profileData, resourceClass),
                        HasDiscriminator = resourceClass.HasDiscriminator()
                    },
                    ShouldRenderClass = false,
                    HasDiscriminator = resourceClass.HasDiscriminator()
                });
            }

            var parentResource = (resourceClass as ResourceChildItem)?.Parent;

            // NOTE model matching
            if (parentResource != null && parentResource.IsAbstract() &&
                parentResource.Entity?.IsSameAggregate(resourceClass.Entity) != true)
            {
                return(new { ShouldRenderClass = false });
            }

            object putPostRequestValidator = _resourceCollectionRenderer.CreatePutPostRequestValidator(profileData, resourceClass, TemplateContext);

            // Contextual parent handling
            var resourceAsChildItem = resourceClass as ResourceChildItem;
            var contextualParent    = GetContextualParent(resourceAsChildItem, profileData);

            var parentProperCaseSchemaName =
                contextualParent?.ResourceModel.SchemaNameMapProvider
                .GetSchemaMapByPhysicalName(contextualParent.FullName.Schema)
                .ProperCaseName;

            var collections = _resourceCollectionRenderer.Collections(profileData, resourceClass, TemplateContext);

            return(new
            {
                ShouldRenderClass = true,
                ResourceReference = resourceClass.IsAggregateReference()
                    ? new
                {
                    ReferenceName = resourceClass.Name,
                    ReferenceIdentifiers = _resourcePropertyRenderer
                                           .AssembleIdentifiers(profileData, resourceClass),
                    Href = AssembleHref(profileData, resourceClass)
                }
                    : ResourceRenderer.DoNotRenderProperty,
                ContextSpecificResourceReferences = CreateContextSpecificResourceReferences(profileData, resourceClass),
                ClassName = resourceClass.Name,
                EntityName = resourceClass.Name,
                Constructor = AssembleConstructor(profileData, resourceClass),
                HasCollections = ((IList)collections).Count > 0,
                Collections = collections,
                Identifiers = _resourcePropertyRenderer.AssemblePrimaryKeys(profileData, resourceClass, TemplateContext),
                NonIdentifiers = _resourcePropertyRenderer.AssembleProperties(resourceClass),
                InheritedProperties = _resourcePropertyRenderer.AssembleInheritedProperties(profileData, resourceClass),
                InheritedCollections =
                    _resourceCollectionRenderer.InheritedCollections(profileData, resourceClass, TemplateContext),
                OnDeserialize = _resourceCollectionRenderer.OnDeserialize(profileData, resourceClass, TemplateContext),
                Guid =
                    resourceClass.IsAggregateRoot()
                        ? new
                {
                    ResourceName = resourceClass.Name,
                    GuidConverterTypeName = "GuidConverter"
                }
                        : ResourceRenderer.DoNotRenderProperty,
                NavigableOneToOnes = _resourceCollectionRenderer.NavigableOneToOnes(profileData, resourceClass),
                InheritedNavigableOneToOnes = _resourceCollectionRenderer.InheritedNavigableOneToOnes(profileData, resourceClass),
                SynchronizationSourceSupport =
                    _resourceCollectionRenderer
                    .SynchronizationSourceSupport(profileData, resourceClass, TemplateContext),
                Versioning = resourceClass.IsAggregateRoot()
                    ? ResourceRenderer.DoRenderProperty
                    : ResourceRenderer.DoNotRenderProperty,
                References = _resourceCollectionRenderer.References(profileData, resourceClass, TemplateContext),
                FQName = resourceClass.FullName,
                IsAbstract = resourceClass.IsAbstract(),
                IsAggregateRoot = resourceClass.IsAggregateRoot(),
                DerivedName = resourceClass.IsDerived
                    ? $@", {EdFiConventions.BuildNamespace(
                            Namespaces.Entities.Common.RelativeNamespace,
                            resourceClass.Entity.BaseEntity.SchemaProperCaseName())
                        }.I{resourceClass.Entity.BaseEntity.Name}"
                    : ResourceRenderer.DoNotRenderProperty,
                ParentName = contextualParent?.Name,
                ParentFieldName = contextualParent?.Name.ToCamelCase(),
                InterfaceParentFieldName = contextualParent?.Name,
                ParentNamespacePrefix = parentProperCaseSchemaName == null
                    ? null
                    : $"{Namespaces.Entities.Common.RelativeNamespace}.{parentProperCaseSchemaName}.",
                IsBaseClassConcrete = resourceClass.Entity != null &&
                                      resourceClass.Entity.IsDerived &&
                                      resourceClass.Entity.BaseEntity != null &&
                                      !resourceClass.Entity.BaseEntity.IsAbstractRequiringNoCompositeId(),
                DerivedBaseTypeName = resourceClass.IsDerived && resourceClass.Entity != null
                    ? resourceClass.Entity.BaseEntity?.Name
                    : ResourceRenderer.DoNotRenderProperty,
                FilteredDelegates = _resourceCollectionRenderer.FilteredDelegates(profileData, resourceClass),
                ShouldRenderValidator = putPostRequestValidator != ResourceRenderer.DoNotRenderProperty,
                Validator = putPostRequestValidator,
                IsExtendable = resourceClass.IsExtendable(),
                IsProfileProject = TemplateContext.IsProfiles,
                HasSupportedExtensions = profileData.SuppliedResource.Extensions.Any(),
                SupportedExtensions = profileData.SuppliedResource.Extensions
                                      .Select(e => new { ExtensionName = TemplateContext.GetSchemaProperCaseNameForExtension(e) }),
                IsEdFiResource = resourceClass.IsEdFiResource(),
                NamespacePrefix = resourceClass.GetNamespacePrefix(),
                HasDiscriminator = resourceClass.HasDiscriminator(),

                // Foreign Key Discriminators should not have any profile applied to this, as this data is required for links
                ResourceReferences = CreateResourceReferences(resourceClass)
            });
        }
Пример #22
0
        private string GetResourceClassTypeName(Resource resource)
        {
            string resourceNamespace = EdFiConventions.CreateResourceNamespace(resource);

            return($"{resourceNamespace}.{resource.Name}");
        }
Пример #23
0
 protected override void Act()
 {
     EdFiConventions.CreateResourceNamespace(null, "TestResource", null, null, null, null);
 }
Пример #24
0
        private IEnumerable <object> CreateResourceContextModels(ResourceProfileData profileData)
        {
            // Create the context for the main resource
            var resourceContext = new
            {
                ResourceName             = profileData.ResourceName,
                ResourceClassesNamespace = EdFiConventions.CreateResourceNamespace(
                    profileData.ContextualRootResource,
                    profileData.ProfileNamespaceName,
                    profileData.ReadableWritableContext,
                    profileData.ConcreteResourceContext),
                ResourceClasses = CreateContextualResourceClasses(
                    profileData,
                    profileData.ContextualRootResource.FullName.Schema),
                IsAbstract = profileData.IsAbstract
            };

            if (resourceContext.ResourceClasses != ResourceRenderer.DoNotRenderProperty)
            {
                yield return(resourceContext);
            }

            // Process resources based on Ed-Fi standard resources for possible resource extensions
            if (profileData.ContextualRootResource.IsEdFiStandardResource)
            {
                // Get all the extension physical schema names present on the current resource model
                string[] extensionSchemaPhysicalNames =
                    !profileData.ContextualRootResource.IsEdFiStandardResource
                        ? new string[0]
                        : profileData.ContextualRootResource.AllContainedItemTypes
                    .Select(i => i.FullName.Schema)
                    .Except(
                        new[] { EdFiConventions.PhysicalSchemaName })
                    .ToArray();

                // Process each extension schema with an individual namespace
                foreach (string extensionSchemaPhysicalName in extensionSchemaPhysicalNames)
                {
                    string extensionSchemaProperCaseName = TemplateContext.DomainModelProvider.GetDomainModel()
                                                           .SchemaNameMapProvider
                                                           .GetSchemaMapByPhysicalName(extensionSchemaPhysicalName)
                                                           .ProperCaseName;

                    var extensionContext = new
                    {
                        ResourceName             = profileData.ResourceName,
                        ResourceClassesNamespace =
                            EdFiConventions.CreateResourceNamespace(
                                profileData.ContextualRootResource,
                                profileData.ProfileNamespaceName,
                                profileData.ReadableWritableContext,
                                profileData.ConcreteResourceContext,
                                extensionSchemaProperCaseName),
                        ResourceClasses = CreateContextualResourceClasses(
                            profileData,
                            extensionSchemaPhysicalName),
                        IsAbstract = profileData.IsAbstract
                    };

                    if (extensionContext.ResourceClasses != ResourceRenderer.DoNotRenderProperty)
                    {
                        yield return(extensionContext);
                    }
                }
            }
        }
Пример #25
0
 public void Should_return_true()
 {
     Assert.That(EdFiConventions.IsProfileAssembly(typeof(StaffProfileResource).Assembly), Is.True);
 }
Пример #26
0
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            if (_duplicates.Any())
            {
                throw new HttpResponseException(
                          request.CreateErrorResponse(
                              HttpStatusCode.InternalServerError,
                              $@"Duplicate controllers have been detected. 
                           Due to ambiguity, no requests will be served until this is resolved.  
                           The following controllers have been detected as duplicates: {string.Join(", ", _duplicates)}"));
            }

            IHttpRouteData routeData = request.GetRouteData();

            if (routeData == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            string controllerName = GetRouteVariable <string>(routeData, ControllerKey);

            // schema section of url ie /data/v3/{schema}/{resource} ex: /data/v3/ed-fi/schools
            string resourceSchema = GetRouteVariable <string>(routeData, ResourceOwnerKey);

            if (ShouldUseDefaultSelectController(controllerName, resourceSchema))
            {
                // If there's no controller or schema name, defer to the base class for direct route handling
                // Also if the controller is a composite controller we defer to base class.
                return(base.SelectController(request));
            }

            string resourceSchemaNamespace = string.Empty;

            if (controllerName.EqualsIgnoreCase("deletes"))
            {
                resourceSchemaNamespace = "EdFi.Ods.ChangeQueries.Controllers";
            }
            else
            {
                try
                {
                    string properCaseName = _schemaNameMapProvider
                                            .GetSchemaMapByUriSegment(resourceSchema)
                                            .ProperCaseName;

                    // for now the check is including the ignore case due to the way the schema name map provider is implemented
                    // this should be address on the changes in phase 4 where the map provider is using dictionaries.
                    resourceSchemaNamespace =
                        EdFiConventions.BuildNamespace(
                            Namespaces.Api.Controllers,
                            properCaseName,
                            controllerName,
                            !EdFiConventions.ProperCaseName.EqualsIgnoreCase(properCaseName));
                }
                // Quietly ignore any failure to find the schema name, allowing NotFound response logic below to run
                catch (KeyNotFoundException) {}
            }

            // Verify org section matches a known resource owner derived from any assembly implementing ISchemaNameMap
            if (string.IsNullOrEmpty(resourceSchemaNamespace))
            {
                throw new HttpResponseException(
                          request.CreateErrorResponse(
                              HttpStatusCode.NotFound,
                              "Resource schema value provided in uri does not match any known values."));
            }

            ProfileContentTypeDetails profileContentTypeDetails = null;

            // http method type determines where the profile specific content type will be sent.
            if (request.Method == HttpMethod.Get)
            {
                profileContentTypeDetails =
                    (from a in request.Headers.Accept
                     where a.MediaType.StartsWith("application/vnd.ed-fi.")
                     let details = a.MediaType.GetContentTypeDetails()
                                   select details)
                    .SingleOrDefault();
            }
            else if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Post)
            {
                if (request.Content != null)
                {
                    var contentType = request.Content.Headers.ContentType;

                    // check that there was a content type on the request
                    if (contentType != null)
                    {
                        // check if the content type is a profile specific content type
                        if (contentType.MediaType.StartsWith("application/vnd.ed-fi."))
                        {
                            // parse the profile specific content type string into the object.
                            profileContentTypeDetails = contentType.MediaType.GetContentTypeDetails();

                            // Was a profile-specific content type for the controller/resource found and was it parseable?
                            // if it was not parsable but started with "application/vnd.ed-fi." then throw an error
                            if (profileContentTypeDetails == null)
                            {
                                throw new HttpResponseException(
                                          BadRequestHttpResponseMessage(
                                              request,
                                              "Content type not valid on this resource."));
                            }
                        }
                    }
                }
            }

            HttpControllerDescriptor controllerDescriptor;
            string key;
            bool   profileControllerNotFound = false;

            // Was a profile-specific content type for the controller/resource found?
            if (profileContentTypeDetails != null)
            {
                // Ensure that the content type resource matchs requested resource
                if (!profileContentTypeDetails.Resource
                    .EqualsIgnoreCase(CompositeTermInflector.MakeSingular(controllerName)))
                {
                    throw new HttpResponseException(
                              BadRequestHttpResponseMessage(
                                  request,
                                  "The resource is not accessible through the profile specified by the content type."));
                }

                // Ensure that if the method is get that the profile specific content type sent readable
                if (request.Method == HttpMethod.Get && profileContentTypeDetails.Usage != ContentTypeUsage.Readable)
                {
                    throw new HttpResponseException(
                              BadRequestHttpResponseMessage(
                                  request,
                                  "The resource is not accessible through the profile specified by the content type."));
                }

                // Ensure that if the http method is PUT or POST that the profile specific type sent was writable
                if ((request.Method == HttpMethod.Put || request.Method == HttpMethod.Post) &&
                    profileContentTypeDetails.Usage != ContentTypeUsage.Writable)
                {
                    throw new HttpResponseException(
                              BadRequestHttpResponseMessage(
                                  request,
                                  "The resource is not accessible through the profile specified by the content type."));
                }

                // Use the profile name as the namespace for controller matching
                string profileName = profileContentTypeDetails.Profile.Replace('-', '_'); // + "_" + profileContentTypeDetails.Usage;

                // Find a matching controller.
                // ex : EdFi.Ods.Api.Services.Controllers.AcademicHonorCategoryTypes.Academic_Week_Readable_Excludes_Optional_References.AcademicHonorCategoryTypes
                key = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}.{1}.{2}",
                    resourceSchemaNamespace,
                    profileName,
                    controllerName);

                if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
                {
                    return(controllerDescriptor);
                }

                profileControllerNotFound = true;
            }

            // Find a matching controller.
            // ex : EdFi.Ods.Api.Services.Controllers.AcademicHonorCategoryTypes.AcademicHonorCategoryTypes
            key = string.Format(
                CultureInfo.InvariantCulture,
                "{0}.{1}",
                resourceSchemaNamespace,
                controllerName);

            if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
            {
                // If there is a controller, just not with the content type specified, it's a bad request
                if (profileControllerNotFound)
                {
                    // If the profile does not exist in this installation of the api throw an error dependent on the http method
                    if (!ProfileExists(profileContentTypeDetails.Profile))
                    {
                        if (request.Method == HttpMethod.Get)
                        {
                            throw new HttpResponseException(NotAcceptableHttpResponseMessage(request));
                        }

                        if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Post)
                        {
                            throw new HttpResponseException(UnsupportedMediaTypeHttpResponseMessage(request));
                        }
                    }

                    // The profile exists but the resource doesnt exist under it
                    throw new HttpResponseException(
                              BadRequestHttpResponseMessage(
                                  request,
                                  string.Format(
                                      "The '{0}' resource is not accessible through the '{1}' profile specified by the content type.",
                                      CompositeTermInflector.MakeSingular(controllerName),
                                      profileContentTypeDetails.Profile)));
                }

                return(controllerDescriptor);
            }

            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
 private static bool IsProfilesAssembly(Assembly assembly)
 {
     return(EdFiConventions.IsProfileAssembly(assembly));
 }
        protected override object Build()
        {
            string ColumnNamesFor(IEnumerable <string> columnNames) => string.Join(", ", columnNames.Select(c => $@"""{c}"""));

            bool EntityInSchema(Entity e) => TemplateContext.SchemaPhysicalName.Equals(e.FullName.Schema);

            bool AssociationInSchema(Association a) => TemplateContext.SchemaPhysicalName.Equals(a.FullName.Schema);

            bool AssociationIsNotOneToOne(Association a)
            => a.Cardinality != Cardinality.OneToOne &&
            a.Cardinality != Cardinality.OneToOneInheritance &&
            a.Cardinality != Cardinality.OneToOneExtension;

            DatabaseMetadata DatabaseMetadataForEntity(Entity e)
            => new DatabaseMetadata
            {
                Name        = e.Identifier.Name,
                TableName   = e.Name,
                ColumnNames = ColumnNamesFor(e.Identifier.Properties.Select(p => p.PropertyName)),
            };

            IEnumerable <DatabaseMetadata> DatabaseMetadataForAlternativeIdentities(Entity e)
            => e.AlternateIdentifiers.Select(
                ai => new DatabaseMetadata
            {
                Name        = ai.Name,
                TableName   = e.Name,
                ColumnNames = ColumnNamesFor(ai.Properties.Select(p => p.PropertyName)),
            });

            DatabaseMetadata DatabaseMetadataForAssociation(Association a)
            => new DatabaseMetadata
            {
                Name        = a.FullName.Name,
                TableName   = a.SecondaryEntity.Name,
                ColumnNames = ColumnNamesFor(a.SecondaryEntityAssociationProperties.Select(p => p.PropertyName)),
            };

            var databaseMetadata = new List <DatabaseMetadata>();

            var domainModel = TemplateContext.DomainModelProvider.GetDomainModel();

            databaseMetadata.AddRange(
                domainModel.Entities
                .Where(EntityInSchema)
                .Select(DatabaseMetadataForEntity));

            databaseMetadata.AddRange(
                domainModel.Entities
                .Where(EntityInSchema)
                .SelectMany(DatabaseMetadataForAlternativeIdentities));

            databaseMetadata.AddRange(
                domainModel.Associations
                .Where(AssociationInSchema)
                .Where(AssociationIsNotOneToOne)
                .Select(DatabaseMetadataForAssociation));

            return(new
            {
                NamespaceName = EdFiConventions.BuildNamespace(
                    Namespaces.CodeGen.ExceptionHandling, TemplateContext.SchemaProperCaseName),
                IndexMetaData = databaseMetadata.OrderBy(x => x.TableName).ThenBy(x => x.Name)
            });
        }
Пример #29
0
        protected override object Build()
        {
            var domainModel = TemplateContext.DomainModelProvider.GetDomainModel();

            var orderedAggregates = domainModel
                                    .Aggregates.Where(
                a => a.Members.Any(
                    e => _shouldRenderEntityForSchema(e) ||
                    e.Extensions.Any(ex => _shouldRenderEntityForSchema(ex))))
                                    .OrderBy(x => x.FullName.Name)
                                    .ToList();

            //Initialize.
            _classMappingsForEntities = new Dictionary <Entity, List <ClassMappingContext> >();

            var distinctOrderedAggregates = orderedAggregates
                                            .SelectMany(
                x => x.Members.Where(e => _shouldRenderEntityForSchema(e))
                .Concat(
                    x.Members.SelectMany(m => m.Extensions)
                    .Where(ex => _shouldRenderEntityForSchema(ex))))
                                            .Distinct();

            foreach (Entity entity in distinctOrderedAggregates)
            {
                _classMappingsForEntities[entity] = CreateContextsForGeneratingMultipleClassMappings(entity, GenerateQueryModel);
            }

            return
                (new OrmMapping
            {
                Assembly = TemplateContext.IsExtension
                        ? PathHelper.GetProjectNameFromProjectPath(TemplateContext.ProjectPath)
                        : Namespaces.Standard.BaseNamespace,
                Namespace = GenerateQueryModel
                        ? Namespaces.Entities.NHibernate.QueryModels.BaseNamespace
                        : Namespaces.Entities.NHibernate.BaseNamespace,
                Aggregates =
                    orderedAggregates
                    .Select(
                        aggregate => new OrmAggregate
                {
                    Classes = aggregate
                              .Members

                              // Derived classes are mapped within their base entity mapping, so exclude top level mappings for these classes
                              .Where(c => !c.IsDerived && _shouldRenderEntityForSchema(c))
                              .Concat(
                        aggregate.Members.SelectMany(m => m.Extensions)
                        .Where(ex => _shouldRenderEntityForSchema(ex)))
                              .SelectMany(GetClassMappings)
                              .ToList()
                })
                    .ToList()
            });

            List <ClassMappingContext> CreateContextsForGeneratingMultipleClassMappings(Entity entity, bool isQueryModel)
            {
                var contexts = new List <ClassMappingContext>
                {
                    // Add the default context
                    new ClassMappingContext {
                        IsQueryModel = isQueryModel
                    }
                };

                if (entity.IsBase && !entity.IsAbstract)
                {
                    // Concrete base classes need an additional specialized mapping created
                    contexts.Add(
                        new ClassMappingContext
                    {
                        IsConcreteEntityBaseMapping = true,
                        IsQueryModel = isQueryModel
                    });
                }

                if (entity.Parent != null && entity.Parent.IsBase && !entity.Parent.IsAbstract && !entity.IsEntityExtension)
                {
                    // Children of concrete base classes need an additional specialized mapping created
                    contexts.Add(
                        new ClassMappingContext
                    {
                        IsConcreteEntityChildMappingForBase = true,
                        IsQueryModel = isQueryModel
                    });
                }

                return(contexts);
            }

            IEnumerable <OrmClass> GetClassMappings(Entity entity)
            {
                var contexts = _classMappingsForEntities[entity];

                bool hasDiscriminator = entity.HasDiscriminator();

                foreach (var classMappingContext in contexts)
                {
                    string fullyQualifiedClassName = GetEntityFullNameForContext(entity, classMappingContext);

                    yield return(new OrmClass
                    {
                        ClassName = fullyQualifiedClassName,
                        ReferenceClassName = fullyQualifiedClassName + "ReferenceData",
                        TableName = entity.TableName(TemplateContext.TemplateSet.DatabaseEngine, entity.Name),
                        SchemaName =
                            EdFiConventions.IsEdFiPhysicalSchemaName(entity.Schema)
                                ? null
                                : entity.Schema,
                        IsAggregateRoot = entity.IsAggregateRoot,
                        IsAbstract = entity.IsAbstract,
                        Id = !HasKeyRequiringUseOfCompositeId(entity)
                            ? CreateId()
                            : null,
                        CompositeId = HasKeyRequiringUseOfCompositeId(entity)
                            ? CreateCompositeId(classMappingContext)
                            : null,
                        Properties = GetOrderedNonIdentifyingProperties(entity, classMappingContext)
                                     .ToList(),
                        HasOneToOneChildMappings = entity.NavigableOneToOnes.Any(),
                        OneToOneChildMappings = entity.NavigableOneToOnes
                                                .Where(a => _shouldRenderEntityForSchema(a.OtherEntity))
                                                .Select(ch => CreateOrmOneToOne(ch, classMappingContext))
                                                .ToList(),
                        HasBackReferences = classMappingContext.IsQueryModel && entity.NonNavigableParents.Any(),
                        BackReferences =
                            classMappingContext.IsQueryModel
                                ? entity.NonNavigableParents.OrderBy(p => p.Name)
                            .Where(p => _shouldRenderEntityForSchema(p.OtherEntity))
                            .Select(CreateOrmBackReference)
                            .ToList()
                                : null,
                        Collections = entity.NavigableChildren
                                      .Concat(
                            classMappingContext.IsQueryModel
                                    ? entity.NonNavigableChildren
                                    : new AssociationView[0])
                                      .Where(
                            ch => !(classMappingContext.IsQueryModel && ch.IsSelfReferencing) &&
                            _shouldRenderEntityForSchema(ch.OtherEntity))
                                      .OrderBy(ch => ch.Name)
                                      .Select(ch => CreateNHibernateCollectionMapping(ch, classMappingContext))
                                      .ToList(),
                        IsConcreteEntityBaseMapping = classMappingContext.IsConcreteEntityBaseMapping,
                        HasDiscriminator = hasDiscriminator,
                        IsReferenceable = entity.IsReferenceable(),
                        HasDerivedEntities = entity.IsBase,
                        HasDiscriminatorWhereClause = hasDiscriminator && entity.IsBase,
                        DerivedEntities = CreateDerivedEntities()
                                          .ToList(),
                        IsQueryModelContext = classMappingContext.IsQueryModel,
                        AggregateReferences = !classMappingContext.IsQueryModel
                            ? entity.GetAssociationsToReferenceableAggregateRoots()
                                              .OrderBy(a => a.Name)
                                              .Select(CreateOrmAggregateReference)
                                              .ToList()
                            : null
                    });
                }

                OrmCompositeIdentity CreateCompositeId(ClassMappingContext classMappingContext)
                {
                    return(new OrmCompositeIdentity
                    {
                        KeyProperties = entity.Identifier.Properties
                                        .Where(p => !p.IsFromParent)
                                        .OrderBy(p => p.PropertyName)
                                        .Select(
                            p => new OrmProperty
                        {
                            PropertyName = p.PropertyName.MakeSafeForCSharpClass(entity.Name),
                            ColumnName = p.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, p.PropertyName),
                            NHibernateTypeName = p.PropertyType.ToNHibernateType(),
                            MaxLength = GetMaxLength(p)
                        })
                                        .ToList(),
                        KeyManyToOne = entity.ParentAssociation == null
                            ? null
                            : new OrmManyToOne
                        {
                            Name = entity.ParentAssociation.Name,
                            HasClassName = classMappingContext.IsConcreteEntityChildMappingForBase,
                            ClassName =
                                classMappingContext.IsConcreteEntityChildMappingForBase
                                        ? GetEntityFullNameForContext(
                                    entity.Parent,
                                    _classMappingsForEntities[entity.Parent]
                                    .FirstOrDefault(x => x.IsConcreteEntityBaseMapping)
                                    ?? _classMappingsForEntities[entity.Parent]
                                    .First())
                                        : null,
                            OrderedParentColumns = entity.ParentAssociation.Inverse.GetOrderedAssociationTargetColumns()
                                                   .Select(
                                p => new OrmColumn
                            {
                                Name = p.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, p.PropertyName)
                            })
                                                   .ToList()
                        }
                    });
                }

                OrmProperty CreateId()
                {
                    return(new OrmProperty
                    {
                        PropertyName = entity.Identifier.Properties.Single()
                                       .PropertyName,
                        ColumnName = entity.Identifier.Properties.Single()
                                     .ColumnName(
                            TemplateContext.TemplateSet.DatabaseEngine,
                            entity.Identifier.Properties.Single()
                            .PropertyName),
                        NHibernateTypeName = entity.Identifier.Properties.Single()
                                             .PropertyType.ToNHibernateType(),
                        MaxLength = GetMaxLength(entity.Identifier.Properties.Single()),
                        GeneratorClass =
                            entity.Identifier.Properties.Single()
                            .IsServerAssigned
                                ? "identity"
                                : "assigned"
                    });
                }

                OrmOneToOne CreateOrmOneToOne(AssociationView ch, ClassMappingContext classMappingContext)
                {
                    return(new OrmOneToOne
                    {
                        Name = ch.OtherEntity.Name,
                        Access =
                            _propertyAccessor,
                        IsQueryModelMapping = classMappingContext.IsQueryModel,
                        ClassName = GetEntityFullNameForContext(
                            ch.OtherEntity,
                            _classMappingsForEntities[ch.OtherEntity]
                            .First()),
                        Columns = ch.GetOrderedAssociationTargetColumns()
                                  .Select(
                            ep => new OrmColumn
                        {
                            Name = ep.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, ep.PropertyName)
                        })
                                  .ToList()
                    });
                }

                OrmBackReference CreateOrmBackReference(AssociationView p)
                {
                    return(new OrmBackReference
                    {
                        BagName = p.Name,
                        ParentClassName = GetEntityFullNameForContext(
                            p.OtherEntity,
                            _classMappingsForEntities[p.OtherEntity]
                            .First()),
                        Columns = p.Inverse.GetOrderedAssociationTargetColumns()
                                  .Select(
                            ep => new OrmColumn
                        {
                            Name = ep.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, ep.PropertyName)
                        })
                                  .ToList()
                    });
                }

                OrmAggregateReference CreateOrmAggregateReference(AssociationView a)
                {
                    return(new OrmAggregateReference
                    {
                        BagName = a.Name + "ReferenceData",
                        AggregateReferenceClassName =
                            GetEntityFullNameForContext(
                                a.OtherEntity.TypeHierarchyRootEntity,
                                new ClassMappingContext {
                            IsReference = true
                        }),
                        Columns = a.Inverse.GetOrderedAssociationTargetColumns()
                                  .Select(
                            p => new OrmColumn
                        {
                            Name = p.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, p.PropertyName)
                        })
                                  .ToList()
                    });
                }

                IEnumerable <OrmDerivedEntity> CreateDerivedEntities()
                {
                    return(entity
                           .DerivedEntities
                           .Where(
                               e => _shouldRenderEntityForSchema(e))
                           .Select(
                               e => new EntityAndContext
                    {
                        Entity = e,
                        Contexts = _classMappingsForEntities[e]
                    })
                           .SelectMany(
                               entityAndContexts => entityAndContexts
                               .Contexts
                               .Select(context => CreateOrmDerivedEntity(entityAndContexts, context))));

                    OrmDerivedEntity CreateOrmDerivedEntity(EntityAndContext entityAndContexts, ClassMappingContext context)
                    {
                        var e = entityAndContexts.Entity;

                        var derivedEntityClassMappingContext = context;

                        string className = GetEntityFullNameForContext(e, derivedEntityClassMappingContext);

                        return
                            (new OrmDerivedEntity
                        {
                            IsJoinedSubclass = e.IsDescriptorEntity,
                            ClassName = className,
                            ReferenceClassName = className + "ReferenceData",
                            TableName = e.Name,
                            SchemaName = EdFiConventions.IsEdFiPhysicalSchemaName(e.Schema)
                                    ? null
                                    : e.Schema,
                            DiscriminatorValue = $"{e.Schema}.{e.Name}",
                            BaseTableName = e.BaseEntity.Name,
                            BaseTableSchemaName =
                                EdFiConventions.IsEdFiPhysicalSchemaName(e.BaseEntity.Schema)
                                        ? null
                                        : e.BaseEntity.Schema,
                            KeyColumns = e.Identifier.Properties
                                         .OrderBy(p => p.PropertyName)
                                         .Select(p => new OrmColumn {
                                Name = p.PropertyName
                            })
                                         .ToList(),
                            KeyProperties = e.Identifier.Properties
                                            .OrderBy(p => p.PropertyName)
                                            .Select(
                                p => new OrmProperty
                            {
                                PropertyName =
                                    p.PropertyName.MakeSafeForCSharpClass(entity.Name),
                                ColumnName = p.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, p.PropertyName),
                                NHibernateTypeName = p.PropertyType.ToNHibernateType(),
                                MaxLength = GetMaxLength(p)
                            })
                                            .ToList(),
                            Properties = GetOrderedNonIdentifyingProperties(e, derivedEntityClassMappingContext)
                                         .ToList(),
                            AggregateReferences = !derivedEntityClassMappingContext.IsQueryModel
                                    ? e.GetAssociationsToReferenceableAggregateRoots()
                                                  .OrderBy(a => a.Name)
                                                  .Select(
                                a => new OrmAggregateReference
                            {
                                BagName = a.Name + "ReferenceData",
                                AggregateReferenceClassName =
                                    GetEntityFullNameForContext(
                                        a.OtherEntity.TypeHierarchyRootEntity,
                                        new ClassMappingContext {
                                    IsReference = true
                                }),
                                Columns = a.Inverse
                                          .GetOrderedAssociationTargetColumns()
                                          .Select(
                                    ep => new OrmColumn
                                {
                                    Name = ep.ColumnName(
                                        TemplateContext.TemplateSet.DatabaseEngine,
                                        ep.PropertyName)
                                })
                                          .ToList()
                            })
                                                  .ToList()
                                    : null,
                            HasBackReferences = derivedEntityClassMappingContext.IsQueryModel &&
                                                e.NonNavigableParents.Any(
                                r => _shouldRenderEntityForSchema(r.OtherEntity)),
                            BackReferences = derivedEntityClassMappingContext.IsQueryModel
                                    ? e.NonNavigableParents.OrderBy(p => p.Name)
                                             .Where(p => _shouldRenderEntityForSchema(p.OtherEntity))
                                             .Select(
                                p => new OrmBackReference
                            {
                                BagName = p.Name,
                                ParentClassName = GetEntityFullNameForContext(
                                    p.OtherEntity,
                                    _classMappingsForEntities[p.OtherEntity]
                                    .First()),
                                Columns = p.Inverse.GetOrderedAssociationTargetColumns()
                                          .Select(
                                    ep => new OrmColumn
                                {
                                    Name = ep.ColumnName(
                                        TemplateContext.TemplateSet.DatabaseEngine,
                                        ep.PropertyName)
                                })
                                          .ToList()
                            })
                                             .ToList()
                                    : null,
                            Collections = e.NavigableChildren.Concat(
                                derivedEntityClassMappingContext.IsQueryModel
                                            ? e.NonNavigableChildren
                                            : new AssociationView[0])
                                          .Where(
                                ch => !(derivedEntityClassMappingContext.IsQueryModel &&
                                        ch.IsSelfReferencing) &&
                                _shouldRenderEntityForSchema(ch.OtherEntity))
                                          .Select(
                                ch
                                => new OrmCollection
                            {
                                BagName = ch.Name,
                                IsEmbeddedCollection =
                                    !derivedEntityClassMappingContext.IsQueryModel,
                                Columns = ch.GetOrderedAssociationTargetColumns()
                                          .Select(
                                    ep => new OrmColumn
                                {
                                    Name = ep.ColumnName(
                                        TemplateContext.TemplateSet.DatabaseEngine,
                                        ep.PropertyName)
                                })
                                          .ToList(),
                                ClassName = GetEntityFullNameForContext(
                                    ch.OtherEntity,
                                    _classMappingsForEntities[ch.OtherEntity]
                                    .First())
                            })
                                          .ToList()
                        });
                    }
                }
            }

            OrmCollection CreateNHibernateCollectionMapping(
                AssociationView childAssociation,
                ClassMappingContext classMappingContext)
            {
                return(new OrmCollection
                {
                    //Can't use classMappingContext.IsHierarchical here because this method is called 2x in that case.
                    BagName = childAssociation.Name,
                    IsEmbeddedCollection =
                        !classMappingContext.IsQueryModel && childAssociation.IsNavigable,
                    Columns = childAssociation.GetOrderedAssociationTargetColumns()
                              .Select(
                        ep => new OrmColumn
                    {
                        Name = ep.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, ep.PropertyName)
                    })
                              .ToList(),
                    ClassName = GetEntityFullNameForContext(
                        childAssociation.OtherEntity,
                        classMappingContext.IsConcreteEntityBaseMapping
                                ? _classMappingsForEntities[childAssociation.OtherEntity]
                        .FirstOrDefault(x => x.IsConcreteEntityChildMappingForBase) ??
                        _classMappingsForEntities[childAssociation.OtherEntity]
                        .First()
                                : _classMappingsForEntities[childAssociation.OtherEntity]
                        .First())
                });
            }

            IEnumerable <NHibernatePropertyDefinition> GetOrderedNonIdentifyingProperties(
                Entity entity,
                ClassMappingContext classMappingContext)
            {
                return(entity.NonIdentifyingProperties
                       .Where(p => !p.IsPredefinedProperty())
                       .Concat(classMappingContext.ViewProperties) // Add in properties found in the view in context, if any
                       .OrderBy(p => p.PropertyName)
                       .Select(
                           p => new NHibernatePropertyDefinition
                {
                    PropertyName = p.PropertyName,
                    ColumnName = p.ColumnName(TemplateContext.TemplateSet.DatabaseEngine, p.PropertyName),
                    NHibernateTypeName = p.PropertyType.ToNHibernateType(),
                    MaxLength = GetMaxLength(p),
                    IsNullable = p.PropertyType.IsNullable
                }));
            }

            string GetMaxLength(EntityProperty p)
            {
                return(p.PropertyType.ToNHibernateType() == "string"
                    ? p.PropertyType.MaxLength.ToString()
                    : null);
            }

            bool HasKeyRequiringUseOfCompositeId(Entity m)
            {
                return

                    // It has a composite key structure
                    (m.Identifier.Properties.Count > 1

                     // ... or it happens to have a single PK column in a one-to-one relationship
                     || m.Identifier.Properties.Single()
                     .IsFromParent);
            }
        }
Пример #30
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);
        }