Exemple #1
0
        private void ResolveAssetsUrls(ISchemaEntity schema, IGrouping <DomainId, ContentEntity> contents, ILookup <DomainId, IEnrichedAssetEntity> assets)
        {
            foreach (var field in schema.SchemaDef.ResolvingAssets())
            {
                foreach (var content in contents)
                {
                    content.ReferenceData ??= new ContentData();

                    var fieldReference = content.ReferenceData.GetOrAdd(field.Name, _ => new ContentFieldData()) !;

                    if (content.Data.TryGetValue(field.Name, out var fieldData) && fieldData != null)
                    {
                        foreach (var(partitionKey, partitionValue) in fieldData)
                        {
                            var referencedAsset =
                                field.GetReferencedIds(partitionValue)
                                .Select(x => assets[x])
                                .SelectMany(x => x)
                                .FirstOrDefault();

                            if (referencedAsset != null)
                            {
                                IJsonValue array;

                                if (referencedAsset.Type == AssetType.Image)
                                {
                                    var url = urlGenerator.AssetContent(
                                        referencedAsset.AppId,
                                        referencedAsset.Id.ToString());

                                    array = JsonValue.Array(url, referencedAsset.FileName);
                                }
                                else
                                {
                                    array = JsonValue.Array(referencedAsset.FileName);
                                }

                                requestCache.AddDependency(referencedAsset.UniqueId, referencedAsset.Version);

                                fieldReference.AddLocalized(partitionKey, array);
                            }
                        }
                    }
                }
            }
        }
Exemple #2
0
        public async Task <IResultList <IContentEntity> > QueryAsync(IAppEntity app, ISchemaEntity schema, ODataUriParser odataQuery, Status[] status = null, bool useDraft = false)
        {
            try
            {
                var propertyCalculator = FindExtensions.CreatePropertyCalculator(schema.SchemaDef, useDraft);

                var filter = FindExtensions.BuildQuery(odataQuery, schema.Id, status, propertyCalculator);

                var contentCount = Collection.Find(filter).CountDocumentsAsync();
                var contentItems =
                    Collection.Find(filter)
                    .ContentTake(odataQuery)
                    .ContentSkip(odataQuery)
                    .ContentSort(odataQuery, propertyCalculator)
                    .Not(x => x.DataText)
                    .ToListAsync();

                await Task.WhenAll(contentItems, contentCount);

                foreach (var entity in contentItems.Result)
                {
                    entity.ParseData(schema.SchemaDef);
                }

                return(ResultList.Create <IContentEntity>(contentCount.Result, contentItems.Result));
            }
            catch (NotSupportedException)
            {
                throw new ValidationException("This odata operation is not supported.");
            }
            catch (NotImplementedException)
            {
                throw new ValidationException("This odata operation is not supported.");
            }
            catch (MongoQueryException ex)
            {
                if (ex.Message.Contains("17406"))
                {
                    throw new DomainException("Result set is too large to be retrieved. Use $top parameter to reduce the number of items.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #3
0
        private ClrQuery ParseOData(Context context, ISchemaEntity schema, string odata)
        {
            try
            {
                var model = BuildEdmModel(context, schema);

                return(model.ParseQuery(odata).ToQuery());
            }
            catch (NotSupportedException)
            {
                throw new ValidationException("OData operation is not supported.");
            }
            catch (ODataException ex)
            {
                throw new ValidationException($"Failed to parse query: {ex.Message}", ex);
            }
        }
Exemple #4
0
        public static Task CanChangeStatus(ChangeContentStatus command,
                                           IContentEntity content,
                                           IContentWorkflow contentWorkflow,
                                           IContentRepository contentRepository,
                                           ISchemaEntity schema)
        {
            Guard.NotNull(command, nameof(command));

            if (schema.SchemaDef.IsSingleton)
            {
                if (content.NewStatus == null || command.Status != Status.Published)
                {
                    throw new DomainException(T.Get("contents.singletonNotChangeable"));
                }

                return(Task.CompletedTask);
            }

            return(Validate.It(async e =>
            {
                var status = content.NewStatus ?? content.Status;

                if (!await contentWorkflow.CanMoveToAsync(content, status, command.Status, command.User))
                {
                    var values = new { oldStatus = status, newStatus = command.Status };

                    e(T.Get("contents.statusTransitionNotAllowed", values), nameof(command.Status));
                }

                if (content.Status == Status.Published && command.CheckReferrers)
                {
                    var hasReferrer = await contentRepository.HasReferrersAsync(content.AppId.Id, command.ContentId, SearchScope.Published);

                    if (hasReferrer)
                    {
                        throw new DomainException(T.Get("contents.referenced"));
                    }
                }

                if (command.DueTime.HasValue && command.DueTime.Value < SystemClock.Instance.GetCurrentInstant())
                {
                    e(T.Get("contents.statusSchedulingNotInFuture"), nameof(command.DueTime));
                }
            }));
        }
Exemple #5
0
        public ContentDataGraphType(ISchemaEntity schema, string schemaName, string schemaType, IGraphModel model)
        {
            Name = $"{schemaType}DataDto";

            foreach (var(field, fieldName, typeName) in schema.SchemaDef.Fields.SafeFields())
            {
                var(resolvedType, valueResolver, args) = model.GetGraphType(schema, field, typeName);

                if (valueResolver != null)
                {
                    var displayName = field.DisplayName();

                    var fieldGraphType = new ObjectGraphType
                    {
                        Name = $"{schemaType}Data{typeName}Dto"
                    };

                    var partitioning = model.ResolvePartition(field.Partitioning);

                    foreach (var partitionKey in partitioning.AllKeys)
                    {
                        fieldGraphType.AddField(new FieldType
                        {
                            Name         = partitionKey.EscapePartition(),
                            Arguments    = args,
                            Resolver     = ContentResolvers.Partition(valueResolver, partitionKey),
                            ResolvedType = resolvedType,
                            Description  = field.RawProperties.Hints
                        });
                    }

                    fieldGraphType.Description = $"The structure of the {displayName} field of the {schemaName} content type.";

                    AddField(new FieldType
                    {
                        Name         = fieldName,
                        Resolver     = ContentResolvers.Field(field),
                        ResolvedType = fieldGraphType,
                        Description  = $"The {displayName} field."
                    });
                }
            }

            Description = $"The structure of the {schemaName} data type.";
        }
Exemple #6
0
        public async Task <IResultList <IContentEntity> > QueryAsync(IAppEntity app, ISchemaEntity schema, Status[] status, bool inDraft, Query query, bool includeDraft = true)
        {
            Guard.NotNull(app, nameof(app));
            Guard.NotNull(schema, nameof(schema));
            Guard.NotNull(query, nameof(query));

            using (Profiler.TraceMethod <MongoContentRepository>("QueryAsyncByQuery"))
            {
                var fullTextIds = await indexer.SearchAsync(query.FullText, app, schema.Id, inDraft?Scope.Draft : Scope.Published);

                if (fullTextIds?.Count == 0)
                {
                    return(ResultList.CreateFrom <IContentEntity>(0));
                }

                return(await contents.QueryAsync(schema, query, fullTextIds, status, inDraft, includeDraft));
            }
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Executes the model element constructor for type on a different thread, and waits for the
        ///  result.
        /// </summary>
        /// <exception cref="Exception">
        ///  Thrown when an exception error condition occurs.
        /// </exception>
        /// <param name="schemaElement">
        ///  The schema element.
        /// </param>
        /// <param name="implementedType">
        ///  Type of the implemented.
        /// </param>
        /// <returns>
        ///  An IModelEntity.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------
        protected virtual IModelEntity InvokeModelElementConstructorForType(ISchemaEntity schemaElement, Type implementedType)
        {
            Contract.Requires(schemaElement, "schemaElement");
            var ctor = ReflectionHelper.GetPublicConstructor(implementedType, new[] { typeof(IDomainModel), typeof(ISchemaEntity) });

            if (ctor != null)
            {
                return((IModelEntity)ctor.Invoke(new object[] { DomainModel, schemaElement }));
            }

            ctor = ReflectionHelper.GetPublicConstructor(implementedType, new[] { typeof(IDomainModel) });
            if (ctor != null)
            {
                return((IModelEntity)ctor.Invoke(new object[] { DomainModel }));
            }

            throw new ModelElementCreationException(String.Format(ExceptionMessages.UnableToCreateEntityOfTypeCtorWithIDomainModelRequiredFormat, implementedType));
        }
Exemple #8
0
        public static async Task <ContentsDto> FromContentsAsync(IResultList <IEnrichedContentEntity> contents, Context context, ApiController controller,
                                                                 ISchemaEntity schema, IContentWorkflow workflow)
        {
            var result = new ContentsDto
            {
                Total = contents.Total,
                Items = contents.Select(x => ContentDto.FromContent(context, x, controller)).ToArray()
            };

            if (schema != null)
            {
                await result.AssignStatusesAsync(workflow, schema);

                result.CreateLinks(controller, schema.AppId.Name, schema.SchemaDef.Name);
            }

            return(result);
        }
Exemple #9
0
        public async Task <IContentEntity?> FindContentAsync(ISchemaEntity schema, Guid id, Status[]?status, bool includeDraft)
        {
            var find = Collection.Find(x => x.Id == id);

            var contentEntity = await find.WithoutDraft(includeDraft).FirstOrDefaultAsync();

            if (contentEntity != null)
            {
                if (contentEntity.IndexedSchemaId != schema.Id || status?.Contains(contentEntity.Status) == false)
                {
                    return(null);
                }

                contentEntity?.ParseData(schema.SchemaDef, serializer);
            }

            return(contentEntity);
        }
Exemple #10
0
        private ContentOperation Operation(ContentEntity content, ISchemaEntity operationSchema, ClaimsPrincipal?currentUser)
        {
            var serviceProvider =
                new ServiceCollection()
                .AddSingleton(contentRepository)
                .AddSingleton(contentWorkflow)
                .BuildServiceProvider();

            return(new ContentOperation(serviceProvider, () => content)
            {
                App = Mocks.App(appId),
                Command = new CreateContent {
                    User = currentUser, Actor = actor
                },
                CommandId = content.Id,
                Schema = operationSchema
            });
        }
Exemple #11
0
        public ContentQueryParserTests()
        {
            var options = Options.Create(new ContentOptions {
                DefaultPageSize = 30
            });

            requestContext = new Context(Mocks.FrontendUser(), Mocks.App(appId));

            var schemaDef =
                new Schema(schemaId.Name)
                .AddString(1, "firstName", Partitioning.Invariant);

            schema = Mocks.Schema(appId, schemaId, schemaDef);

            var cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            sut = new ContentQueryParser(cache, JsonHelper.DefaultSerializer, options);
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Creates entity core.
        /// </summary>
        /// <param name="id">
        ///  The identifier.
        /// </param>
        /// <param name="metaClass">
        ///  the meta class.
        /// </param>
        /// <param name="instance">
        ///  The instance.
        /// </param>
        /// <returns>
        ///  The new entity core.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------
        protected virtual IModelElement CreateEntityCore(Identity id, ISchemaEntity metaClass, IModelEntity instance)
        {
            Contract.Requires(id, "id");
            Contract.Requires(metaClass, "metaClass");
            IModelElement result = instance;

            CheckInitialized();

            using (var session = EnsuresRunInSession())
            {
                result = L1Cache.CreateEntity(id, metaClass, instance);
                if (session != null)
                {
                    session.AcceptChanges();
                }
                return(result);
            }
        }
        private OperationContext CreateContext(ContentEntity content, ISchemaEntity contextSchema, ClaimsPrincipal?currentUser)
        {
            var serviceProvider =
                new ServiceCollection()
                .AddSingleton(contentRepository)
                .AddSingleton(contentWorkflow)
                .BuildServiceProvider();

            return(new OperationContext(serviceProvider)
            {
                Actor = actor,
                App = Mocks.App(appId),
                ContentProvider = () => content,
                ContentId = content.Id,
                Schema = contextSchema,
                User = currentUser
            });
        }
Exemple #14
0
        public CachingSchemaProviderTests()
        {
            var schemaV1Mock = new Mock <ISchemaEntity>();
            var schemaV2Mock = new Mock <ISchemaEntity>();

            schemaV1Mock.Setup(x => x.Id).Returns(schemaId.Id);
            schemaV1Mock.Setup(x => x.Name).Returns(schemaId.Name);
            schemaV1Mock.Setup(x => x.AppId).Returns(appId.Id);

            schemaV2Mock.Setup(x => x.Id).Returns(schemaId.Id);
            schemaV2Mock.Setup(x => x.Name).Returns(schemaId.Name);
            schemaV2Mock.Setup(x => x.AppId).Returns(appId.Id);

            schemaV1 = schemaV1Mock.Object;
            schemaV2 = schemaV2Mock.Object;

            sut = new CachingSchemaProvider(cache, repository.Object);
        }
Exemple #15
0
        public ContentDomainObjectTests()
        {
            app = Mocks.App(AppNamedId, Language.DE);

            var scripts = new SchemaScripts
            {
                Change = "<change-script>",
                Create = "<create-script>",
                Delete = "<delete-script>",
                Update = "<update-script>"
            };

            var schemaDef =
                new Schema("my-schema")
                .AddNumber(1, "my-field1", Partitioning.Invariant,
                           new NumberFieldProperties {
                IsRequired = true
            })
                .AddNumber(2, "my-field2", Partitioning.Invariant,
                           new NumberFieldProperties {
                IsRequired = false
            })
                .SetScripts(scripts);

            schema = Mocks.Schema(AppNamedId, SchemaNamedId, schemaDef);

            A.CallTo(() => appProvider.GetAppAsync(AppName, false))
            .Returns(app);

            A.CallTo(() => appProvider.GetAppWithSchemaAsync(AppId, SchemaId, false))
            .Returns((app, schema));

            A.CallTo(() => scriptEngine.TransformAsync(A <ScriptVars> ._, A <string> ._, ScriptOptions()))
            .ReturnsLazily(x => Task.FromResult(x.GetArgument <ScriptVars>(0) !.Data !));

            patched = patch.MergeInto(data);

            var validators = Enumerable.Repeat(new DefaultValidatorsFactory(), 1);

            var context = new ContentOperationContext(appProvider, validators, scriptEngine, A.Fake <ISemanticLog>());

            sut = new ContentDomainObject(Store, A.Dummy <ISemanticLog>(), contentWorkflow, contentRepository, context);
            sut.Setup(Id);
        }
Exemple #16
0
        public ContentDataInputGraphType(ISchemaEntity schema, string schemaName, string schemaType, IGraphModel model)
        {
            Name = $"{schemaType}DataInputDto";

            foreach (var(field, fieldName, typeName) in schema.SchemaDef.Fields.SafeFields().Where(x => x.Field.IsForApi(true)))
            {
                var resolvedType = model.GetInputGraphType(schema, field, typeName);

                if (resolvedType != null)
                {
                    var displayName = field.DisplayName();

                    var fieldGraphType = new InputObjectGraphType
                    {
                        Name = $"{schemaType}Data{typeName}InputDto"
                    };

                    var partitioning = model.ResolvePartition(field.Partitioning);

                    foreach (var partitionKey in partitioning.AllKeys)
                    {
                        fieldGraphType.AddField(new FieldType
                        {
                            Name         = partitionKey.EscapePartition(),
                            ResolvedType = resolvedType,
                            Resolver     = null,
                            Description  = field.RawProperties.Hints
                        }).WithSourceName(partitionKey);
                    }

                    fieldGraphType.Description = $"The structure of the {displayName} field of the {schemaName} content input type.";

                    AddField(new FieldType
                    {
                        Name         = fieldName,
                        ResolvedType = fieldGraphType,
                        Resolver     = null,
                        Description  = $"The {displayName} field."
                    }).WithSourceName(field.Name);
                }
            }

            Description = $"The structure of the {schemaName} data input type.";
        }
Exemple #17
0
        public static async Task CanDelete(ISchemaEntity schema, ContentState content, IContentRepository contentRepository, DeleteContent command)
        {
            Guard.NotNull(command, nameof(command));

            if (schema.SchemaDef.IsSingleton)
            {
                throw new DomainException(T.Get("contents.singletonNotDeletable"));
            }

            if (command.CheckReferrers)
            {
                var hasReferrer = await contentRepository.HasReferrersAsync(content.AppId.Id, command.ContentId);

                if (hasReferrer)
                {
                    throw new DomainException(T.Get("contents.referenced"));
                }
            }
        }
        public async Task <IResultList <IContentEntity> > QueryAsync(IAppEntity app, ISchemaEntity schema, Q q)
        {
            using (Profiler.TraceMethod <MongoContentRepository>())
            {
                if (q.Ids != null && q.Ids.Count > 0)
                {
                    return(await queryByIds.QueryAsync(app.Id, new List <ISchemaEntity> {
                        schema
                    }, q));
                }

                if (q.Referencing == default)
                {
                    return(await queryByQuery.QueryAsync(app, schema, q));
                }

                return(ResultList.CreateFrom <IContentEntity>(0));
            }
        }
        public async Task <IResultList <IContentEntity> > QueryAsync(IAppEntity app, ISchemaEntity schema, HashSet <Guid> ids, Status[] status = null)
        {
            var find =
                status != null && status.Length > 0 ?
                Collection.Find(x => x.IndexedSchemaId == schema.Id && ids.Contains(x.Id) && x.IsDeleted != true && status.Contains(x.Status)) :
                Collection.Find(x => x.IndexedSchemaId == schema.Id && ids.Contains(x.Id));

            var contentItems = find.Not(x => x.DataText).ToListAsync();
            var contentCount = find.CountDocumentsAsync();

            await Task.WhenAll(contentItems, contentCount);

            foreach (var entity in contentItems.Result)
            {
                entity.ParseData(schema.SchemaDef, Serializer);
            }

            return(ResultList.Create <IContentEntity>(contentCount.Result, contentItems.Result));
        }
        public ContentQueryParserTests()
        {
            var options = Options.Create(new ContentOptions {
                DefaultPageSize = 30
            });

            requestContext = new Context(Mocks.FrontendUser(), Mocks.App(appId));

            var schemaDef =
                new Schema(schemaId.Name)
                .AddString(1, "firstName", Partitioning.Invariant)
                .AddGeolocation(2, "geo", Partitioning.Invariant);

            schema = Mocks.Schema(appId, schemaId, schemaDef);

            var cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            sut = new ContentQueryParser(appProvider, textIndex, options, cache, TestUtils.DefaultSerializer);
        }
Exemple #21
0
        public static async Task CanCreate(ISchemaEntity schema, IContentWorkflow contentWorkflow, CreateContent command)
        {
            Guard.NotNull(command, nameof(command));

            if (schema.SchemaDef.IsSingleton && command.ContentId != schema.Id)
            {
                throw new DomainException(T.Get("contents.singletonNotCreatable"));
            }

            if (command.Publish && !await contentWorkflow.CanPublishOnCreateAsync(schema, command.Data, command.User))
            {
                throw new DomainException(T.Get("contents.workflowErorPublishing"));
            }

            Validate.It(e =>
            {
                ValidateData(command, e);
            });
        }
Exemple #22
0
        public static async Task CanCreate(ISchemaEntity schema, IContentWorkflow contentWorkflow, CreateContent command)
        {
            Guard.NotNull(command, nameof(command));

            if (schema.SchemaDef.IsSingleton && command.ContentId != schema.Id)
            {
                throw new DomainException("Singleton content cannot be created.");
            }

            if (command.Publish && !await contentWorkflow.CanPublishOnCreateAsync(schema, command.Data, command.User))
            {
                throw new DomainException("Content workflow prevents publishing.");
            }

            Validate.It(() => "Cannot created content.", e =>
            {
                ValidateData(command, e);
            });
        }
Exemple #23
0
        public async Task <IResultList <IContentEntity> > QueryAsync(IAppEntity app, ISchemaEntity schema, Q q, SearchScope scope)
        {
            using (Profiler.TraceMethod <MongoContentRepository>())
            {
                if (q.Ids != null && q.Ids.Count > 0l)
                {
                    return(await queryByIds.QueryAsync(app.Id, new List <ISchemaEntity> {
                        schema
                    }, q));
                }

                if (q.Referencing == default)
                {
                    return(await queryByQuery.QueryAsync(app, schema, q, scope));
                }

                throw new NotSupportedException();
            }
        }
        public async Task <IContentEntity?> DoAsync(ISchemaEntity schema, Guid id, Status[]?status, bool includeDraft)
        {
            Guard.NotNull(schema);

            var find = Collection.Find(x => x.Id == id).WithoutDraft(includeDraft);

            var contentEntity = await find.FirstOrDefaultAsync();

            if (contentEntity != null)
            {
                if (contentEntity.IndexedSchemaId != schema.Id || !contentEntity.HasStatus(status))
                {
                    return(null);
                }

                contentEntity?.ParseData(schema.SchemaDef, serializer);
            }

            return(contentEntity);
        }
Exemple #25
0
        public async Task <IContentEntity?> QueryAsync(ISchemaEntity schema, DomainId id)
        {
            Guard.NotNull(schema, nameof(schema));

            var documentId = DomainId.Combine(schema.AppId, id);

            var find = Collection.Find(x => x.DocumentId == documentId);

            var contentEntity = await find.FirstOrDefaultAsync();

            if (contentEntity != null)
            {
                if (contentEntity.IndexedSchemaId != schema.Id)
                {
                    return(null);
                }
            }

            return(contentEntity);
        }
Exemple #26
0
        public static void CanCreate(CreateContent command, ISchemaEntity schema)
        {
            Guard.NotNull(command, nameof(command));

            if (schema.SchemaDef.IsSingleton)
            {
                if (command.ContentId != schema.Id)
                {
                    throw new DomainException(T.Get("contents.singletonNotCreatable"));
                }
            }

            Validate.It(e =>
            {
                if (command.Data == null)
                {
                    e(Not.Defined(nameof(command.Data)), nameof(command.Data));
                }
            });
        }
Exemple #27
0
        public async Task <IContentEntity?> DoAsync(ISchemaEntity schema, Guid id)
        {
            Guard.NotNull(schema, nameof(schema));

            var find = Collection.Find(x => x.Id == id);

            var contentEntity = await find.FirstOrDefaultAsync();

            if (contentEntity != null)
            {
                if (contentEntity.IndexedSchemaId != schema.Id)
                {
                    return(null);
                }

                contentEntity?.ParseData(schema.SchemaDef, converter);
            }

            return(contentEntity);
        }
Exemple #28
0
        private IEnumerable <IContentEntity> TransformCore(QueryContext context, ISchemaEntity schema, IEnumerable <IContentEntity> contents)
        {
            using (Profiler.TraceMethod <ContentQueryService>())
            {
                var converters = GenerateConverters(context).ToArray();

                var scriptText = schema.SchemaDef.Scripts.Query;

                var isScripting = !string.IsNullOrWhiteSpace(scriptText);

                foreach (var content in contents)
                {
                    var result = SimpleMapper.Map(content, new ContentEntity());

                    if (result.Data != null)
                    {
                        if (!context.IsFrontendClient && isScripting)
                        {
                            var ctx = new ScriptContext {
                                User = context.User, Data = content.Data, ContentId = content.Id
                            };

                            result.Data = scriptEngine.Transform(ctx, scriptText);
                        }

                        result.Data = result.Data.ConvertName2Name(schema.SchemaDef, converters);
                    }

                    if (result.DataDraft != null && (context.Unpublished || context.IsFrontendClient))
                    {
                        result.DataDraft = result.DataDraft.ConvertName2Name(schema.SchemaDef, converters);
                    }
                    else
                    {
                        result.DataDraft = null;
                    }

                    yield return(result);
                }
            }
        }
Exemple #29
0
        public async Task<ISchemaEntity> GetSchemaAsync(QueryContext context)
        {
            ISchemaEntity schema = null;

            if (Guid.TryParse(context.SchemaIdOrName, out var id))
            {
                schema = await appProvider.GetSchemaAsync(context.App.Id, id);
            }

            if (schema == null)
            {
                schema = await appProvider.GetSchemaAsync(context.App.Id, context.SchemaIdOrName);
            }

            if (schema == null)
            {
                throw new DomainObjectNotFoundException(context.SchemaIdOrName, typeof(ISchemaEntity));
            }

            return schema;
        }
Exemple #30
0
        private List <IContentEntity> TransformContent(ClaimsPrincipal user, ISchemaEntity schema, List <IContentEntity> contents)
        {
            var scriptText = schema.ScriptQuery;

            if (!string.IsNullOrWhiteSpace(scriptText))
            {
                for (var i = 0; i < contents.Count; i++)
                {
                    var content     = contents[i];
                    var contentData = scriptEngine.Transform(new ScriptContext {
                        User = user, Data = content.Data, ContentId = content.Id
                    }, scriptText);

                    contents[i] = SimpleMapper.Map(content, new Content {
                        Data = contentData
                    });
                }
            }

            return(contents);
        }
 private void GetEntity(ISchemaEntity entity)
 {
     CreateStorageEntity(entity);
     CreateConceptualEntity(entity);
 }
        private EntityContainer.EntitySetLocalType CreateStorageEntitySet(ISchemaEntity entity, out bool isNewView)
        {
            //<EntitySet Name="Category" EntityType="PetShopModel1.Store.Category" store:Type="Tables" Schema="dbo" />
            //<EntitySet Name="vw_aspnet_Applications" EntityType="PetShopModel1.Store.vw_aspnet_Applications" store:Type="Views" store:Schema="dbo" store:Name="vw_aspnet_Applications">
            var entitySet = StorageSchemaEntityContainer.EntitySets.Where(e =>
                (entity.EntityKeyName.Equals(e.Name, StringComparison.OrdinalIgnoreCase) && entity.SchemaName.Equals(e.Schema, StringComparison.OrdinalIgnoreCase)) ||
                (entity.EntityKeyName.Equals(e.Name1, StringComparison.OrdinalIgnoreCase) && entity.SchemaName.Equals(e.Schema1, StringComparison.OrdinalIgnoreCase)) ||
                entity.EntityKeyName.Equals(e.Name1, StringComparison.OrdinalIgnoreCase) || entity.EntityKeyName.Equals(e.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            isNewView = entitySet == null && entity is ViewEntity;
            if (entitySet == null) {
                entitySet = new EntityContainer.EntitySetLocalType {
                    Name = entity.EntityKeyName
                };
                StorageSchemaEntityContainer.EntitySets.Add(entitySet);
            }

            _storageEntityNames[entity.EntityKeyName] = entitySet.Name;

            // Set or sync the default values.
            // http://msdn.microsoft.com/en-us/library/bb387152.aspx
            entitySet.Name = entity.EntityKeyName;
            entitySet.EntityType = String.Concat(StorageSchema.Namespace, ".", entity.EntityKeyName);
            entitySet.Type = entity is TableEntity ? EdmxConstants.StorageSchemaGenerationTypeAttributeValueTables : null;
            entitySet.Schema = entity is TableEntity ? entity.SchemaName : null;

            if (entity is ViewEntity) {
                entitySet.Type = EdmxConstants.StorageSchemaGenerationTypeAttributeValueViews;
                entitySet.DefiningQuery = ((ViewEntity)entity).SourceText.Remove(0, ((ViewEntity)entity).SourceText.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase));
            } else
                entitySet.Table = entity.EntityKeyName;

            if (!String.IsNullOrEmpty(entitySet.Schema1))
                entitySet.Schema1 = entity.SchemaName;
            if (!String.IsNullOrEmpty(entitySet.Name1))
                entitySet.Name1 = entity.EntityKeyName;

            return entitySet;
        }
        private void CreateStorageEntityTypeProperties(ISchemaEntity entity, EntityTypeStore entityType)
        {
            //<Property Name="CategoryId" Type="varchar" Nullable="false" MaxLength="10"  />
            foreach (ISchemaProperty property in entity.Properties) {
                var entityProperty = entityType.Properties.Where(p => property.KeyName.Equals(p.Name, StringComparison.OrdinalIgnoreCase) || property.KeyName.Equals(p.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (entityProperty == null) {
                    if (ExcludeProperty(property))
                        continue;

                    entityProperty = new EntityProperty() {
                        Name = property.KeyName
                    };
                    entityType.Properties.Add(entityProperty);

                    _newStorageEntityProperties.Add(String.Format("{0}-{1}", entity.Name, property.Name));
                } else if (ExcludeProperty(property)) {
                    entityType.Properties.Remove(entityProperty);
                    continue;
                }

                entityProperty.Name = property.KeyName;
                entityProperty.Type = GetNativeType(property);

                if (!property.IsNullable)
                    entityProperty.Nullable = property.IsNullable;

                if (String.IsNullOrEmpty(entityProperty.DefaultValue) && !String.IsNullOrEmpty(property.DefaultValue)) {
                    if (property.DefaultValue.ToLowerInvariant().Contains("autoincrement")) // Needed for sql anywhere
                        entityProperty.DefaultValue = null;
                    else if (String.Equals(property.BaseSystemType, "System.Boolean", StringComparison.OrdinalIgnoreCase))
                        entityProperty.DefaultValue = property.DefaultValue.ToLower();
                    else if (String.Equals(property.BaseSystemType, "System.Single", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Int16", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Int32", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Int64", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Byte", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Decimal", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.Double", StringComparison.OrdinalIgnoreCase)
                             || String.Equals(property.BaseSystemType, "System.String", StringComparison.OrdinalIgnoreCase))
                        entityProperty.DefaultValue = property.DefaultValue;
                    else
                        entityProperty.DefaultValue = null;
                } else {
                    entityProperty.DefaultValue = null;
                }

                entityProperty.MaxLength = !String.IsNullOrEmpty(GetMaxLength(property)) && !GetMaxLength(property).Equals("Max", StringComparison.OrdinalIgnoreCase) && !GetNativeType(property).Equals("timestamp", StringComparison.OrdinalIgnoreCase) ? GetMaxLength(property) : null;

                entityProperty.StoreGeneratedPattern = property.IsIdentity ? EdmxConstants.StoreGeneratedPatternIdentity : property.IsComputed ? EdmxConstants.StoreGeneratedPatternComputed : null;
            }
        }
        private EntityTypeStore CreateStorageEntityType(ISchemaEntity entity, string name, ref bool isNewView)
        {
            EntityTypeStore entityType = StorageSchema.EntityTypeStores.Where(e => ResolveStorageEntityName(entity.EntityKeyName).Equals(e.Name, StringComparison.OrdinalIgnoreCase) || name.Equals(e.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (entityType == null) {
                entityType = new EntityTypeStore() {
                    Name = name,
                    Key = new EntityKeyElement()
                };

                StorageSchema.EntityTypeStores.Add(entityType);

                isNewView = entity is ViewEntity;
            }

            // Sync the name.
            entityType.Name = name;

            return entityType;
        }
        private void CreateStorageEntity(ISchemaEntity entity)
        {
            // Check to see if this has already been processed.
            if (_storageEntitys.Contains(entity.EntityKey()))
                return;

            bool isNewView;

            var entitySet = CreateStorageEntitySet(entity, out isNewView);
            var entityType = CreateStorageEntityType(entity, entitySet.Name, ref isNewView);

            // Remove the duplicate properties.
            RemoveDuplicateStorageEntityTypeKeysAndProperties(entityType);

            // Remove extra properties values.
            var properties = from property in entityType.Properties
                where !(from prop in entity.Properties select prop.KeyName).Contains(property.Name)
                select property;

            // Remove all of the key properties that don't exist in the table entity.
            foreach (var property in properties) {
                var propertyName = ResolveConceptualPropertyNameFromStorageColumnName(entityType.Name, property.Name);
                _removedStorageEntityProperties.Add(String.Format(PROPERTY_KEY, entity.EntityKeyName, propertyName).ToLower());
                entityType.Properties.Remove(property);
            }

            CreateStorageEntityTypeKeys(entity, isNewView, entityType);
            CreateStorageEntityTypeProperties(entity, entityType);

            _storageEntitys.Add(entity.EntityKeyName);
        }
        private static void CreateStorageEntityTypeKeys(ISchemaEntity entity, bool isNewView, EntityTypeStore entityType)
        {
            //<Key>
            //  <PropertyRef Name="CategoryId"  />
            //</Key>
            if (entity.HasKey || isNewView) {
                #region Remove extra key values.

                var items = from property in entityType.Key.PropertyRefs
                    where !(from prop in entity.Key.Properties select prop.KeyName).Contains(property.Name)
                    select property;

                // Remove all of the key properties that don't exist in the table entity.
                foreach (var property in items) {
                    entityType.Key.PropertyRefs.Remove(property);
                }

                #endregion

                foreach (var property in entity.Key.Properties.Where(p => entityType.Key.PropertyRefs.Count(pr => pr.Name == p.Name) == 0)) {
                    entityType.Key.PropertyRefs.Add(new PropertyRef() {
                        Name = property.KeyName
                    });
                }
            } else if (entity is TableEntity) {
                entityType.Key.PropertyRefs.Clear();
            }
        }