Ejemplo n.º 1
0
        /// <summary>Populates the metadata.</summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="resultItem">The result item.</param>
        private void PopulateMetadata(IEntityMetadata metadata, IExternalSearchQueryResult <MappingResponse> resultItem)
        {
            var code  = this.GetOriginEntityCode(resultItem);
            var vocab = new OpenfigiVocabulary();

            metadata.EntityType       = EntityType.Organization;
            metadata.Name             = resultItem.Data.Response.Name;
            metadata.Description      = resultItem.Data.Response.SecurityDescription;
            metadata.OriginEntityCode = code;

            metadata.Codes.Add(code);

            metadata.Properties[vocab.Figi]                = resultItem.Data.Response.Figi.PrintIfAvailable();
            metadata.Properties[vocab.Name]                = resultItem.Data.Response.Name.PrintIfAvailable();
            metadata.Properties[vocab.Ticker]              = resultItem.Data.Response.Ticker.PrintIfAvailable();
            metadata.Properties[vocab.ExchCode]            = resultItem.Data.Response.ExchCode.PrintIfAvailable();
            metadata.Properties[vocab.CompositeFIGI]       = resultItem.Data.Response.CompositeFIGI.PrintIfAvailable();
            metadata.Properties[vocab.UniqueID]            = resultItem.Data.Response.UniqueID.PrintIfAvailable();
            metadata.Properties[vocab.SecurityType]        = resultItem.Data.Response.SecurityType.PrintIfAvailable();
            metadata.Properties[vocab.MarketSector]        = resultItem.Data.Response.MarketSector.PrintIfAvailable();
            metadata.Properties[vocab.ShareClassFIGI]      = resultItem.Data.Response.ShareClassFIGI.PrintIfAvailable();
            metadata.Properties[vocab.UniqueIDFutOpt]      = resultItem.Data.Response.UniqueIDFutOpt.PrintIfAvailable();
            metadata.Properties[vocab.SecurityType2]       = resultItem.Data.Response.SecurityType2.PrintIfAvailable();
            metadata.Properties[vocab.SecurityDescription] = resultItem.Data.Response.SecurityDescription.PrintIfAvailable();
        }
Ejemplo n.º 2
0
 public virtual void Validate(IEntityMetadata metadata, IAuthentication authentication)
 {
     if (!metadata.AllowAnonymous && !authentication.Identity.IsAuthenticated)
     {
         throw new DomainServiceException(new UnauthorizedAccessException("未登录。"));
     }
 }
Ejemplo n.º 3
0
        public static void DocumentCreation([NotNull] IEntityMetadata metadata,
                                            [NotNull] IList <object> state,
                                            [NotNull] IList <string> propertyNames)
        {
            Assert.ArgumentNotNull(metadata, nameof(metadata));

            var newState = new NewEntityState(state, propertyNames);

            if (metadata.CreatedByUser == null)
            {
                metadata.CreatedByUser = metadata.LastChangedByUser ?? GetUserName();
                newState.Update(_createdByUserProperty, metadata.CreatedByUser);
            }

            if (metadata.CreatedDate == null)
            {
                metadata.CreatedDate = metadata.LastChangedDate ?? DateTime.Now;
                newState.Update(_createdDateProperty, metadata.CreatedDate);
            }

            if (metadata.LastChangedByUser == null)
            {
                metadata.LastChangedByUser = metadata.CreatedByUser;
                newState.Update(_lastChangedByUserProperty, metadata.LastChangedByUser);
            }

            if (metadata.LastChangedDate == null)
            {
                metadata.LastChangedDate = metadata.CreatedDate;
                newState.Update(_lastChangedDateProperty, metadata.LastChangedDate);
            }
        }
Ejemplo n.º 4
0
        private DeleteStatement BuildSlave(TableDefinition master, IEntityMetadata entity)
        {
            var statement = new DeleteStatement(entity);
            var reference = TableIdentifier.Temporary(master.Name, TEMPORARY_ALIAS);

            if (entity.Key.Length == 1)
            {
                var select = new SelectStatement(reference);
                select.Select.Members.Add(reference.CreateField(master.Fields.First().Name));
                statement.Where = Expression.In(statement.Table.CreateField(entity.Key[0]), select);
            }
            else
            {
                var join = new JoinClause(TEMPORARY_ALIAS, reference, JoinType.Inner);

                foreach (var key in entity.Key)
                {
                    join.Condition.Add(
                        Expression.Equal(
                            statement.Table.CreateField(key),
                            reference.CreateField(key)));
                }

                statement.From.Add(join);
            }

            master.Slaves.Add(statement);

            return(statement);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 获取指定实体元素的继承链(所有的继承元素),从最顶级的根元素开始一直到当前元素本身。
        /// </summary>
        /// <param name="entity">指定的实体元素。</param>
        /// <returns>返回的继承链(即继承关系的实体元素数组)。</returns>
        public static IEnumerable <IEntityMetadata> GetInherits(this IEntityMetadata entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (string.IsNullOrEmpty(entity.BaseName))
            {
                yield return(entity);

                yield break;
            }

            var super = entity;
            var stack = new Stack <IEntityMetadata>();

            while (super != null)
            {
                stack.Push(super);
                super = GetBaseEntity(super);
            }

            while (stack.Count > 0)
            {
                yield return(stack.Pop());
            }
        }
Ejemplo n.º 6
0
        public static void SetMetadataForCreation(this IEntityMetadata entityMetadata)
        {
            long currentSuperEpoch = DateTime.Now.ToSuperEpochUtc();

            entityMetadata.MetaCreatedTimeCode  = currentSuperEpoch;
            entityMetadata.MetaModifiedTimeCode = currentSuperEpoch;
        }
Ejemplo n.º 7
0
        IEntityMetadata IEntityDescriptor.GetMetadata(Type type)
        {
            while (type.GetTypeInfo().Assembly.IsDynamic)
            {
                type = type.GetTypeInfo().BaseType;
            }
            if (!typeof(IEntity).IsAssignableFrom(type))
            {
                throw new NotSupportedException("该类型没有继承IEntity接口。");
            }
            IEntityMetadata metadata = _Metadata.GetOrAdd(type, s =>
            {
                var metadataField = type.GetField("Metadata", BindingFlags.Static | BindingFlags.Public);
                IEntityMetadata m;
                if (metadataField != null)
                {
                    m = (IEntityMetadata)metadataField.GetValue(null);
                }
                else
                {
                    m = new ClrEntityMetadata(type);
                }
                foreach (var interfaceType in type.GetInterfaces().Where(t => t != typeof(IEntity) && t.GetTypeInfo().GetCustomAttribute <EntityInterfaceAttribute>() != null && typeof(IEntity).IsAssignableFrom(t)))
                {
                    _Metadata.TryAdd(interfaceType, m);
                }
                return(m);
            });

            return(metadata);
        }
Ejemplo n.º 8
0
        /// <summary>Populates the metadata.</summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="resultItem">The result item.</param>
        private void PopulateMetadata(IEntityMetadata metadata, IExternalSearchQueryResult <Result> resultItem, IExternalSearchRequest request)
        {
            if (resultItem == null)
            {
                throw new ArgumentNullException(nameof(resultItem));
            }

            var code = GetOriginEntityCode(resultItem);
            var data = resultItem.Data;

            metadata.Name        = request.QueryParameters.GetValue(Core.Data.Vocabularies.Vocabularies.CluedInOrganization.OrganizationName, new HashSet <string>()).FirstOrDefault();
            metadata.EntityType  = EntityType.Organization;
            metadata.CreatedDate = resultItem.CreatedDate;

            metadata.OriginEntityCode = code;
            metadata.Codes.Add(code);

            metadata.Properties[DamaVocabularies.Organization.AdressingStreetName] = data.ActualAddress.AdressingStreetName.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.Door]               = data.ActualAddress.Door.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.Floor]              = data.ActualAddress.Floor.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.HouseNumber]        = data.ActualAddress.HouseNumber.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.Id]                 = data.ActualAddress.Id.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.Zipcode]            = data.ActualAddress.Zipcode.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.ZipcodeName]        = data.ActualAddress.Zipcodename.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.Status]             = data.ActualAddress.Status.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.AdditionalCityName] = data.ActualAddress.AdditionalCityName.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.StreetName]         = data.ActualAddress.StreetName.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.EffectiveEnd]       = data.ActualAddress.EffectiveEnd.PrintIfAvailable();
            metadata.Properties[DamaVocabularies.Organization.EffectiveStart]     = data.ActualAddress.EffectiveStart.PrintIfAvailable();

            metadata.Uri = new Uri(data.ActualAddress.Href);
        }
Ejemplo n.º 9
0
 private void PopulateOrgAddressMetadata(IEntityMetadata metadata, CompanyHouseOrgAddressVocabulary vocab, CompanyNew resultCompany)
 {
     metadata.Properties[vocab.AddressLine1] = resultCompany.registered_office_address.address_line_1.PrintIfAvailable();
     metadata.Properties[vocab.AddressLine2] = resultCompany.registered_office_address.address_line_2.PrintIfAvailable();
     metadata.Properties[vocab.Locality]     = resultCompany.registered_office_address.locality.PrintIfAvailable();
     metadata.Properties[vocab.PostCode]     = resultCompany.registered_office_address.postal_code.PrintIfAvailable();
 }
Ejemplo n.º 10
0
        private void PopulateContactMetadata(IEntityMetadata metadata, Contact resultItem)
        {
            var code = new EntityCode(EntityType.Person, GetCodeOrigin(), resultItem.regNumber);

            metadata.EntityType       = EntityType.Person;
            metadata.Name             = resultItem.name.PrintIfAvailable();
            metadata.OriginEntityCode = code;

            metadata.Properties[CompanyHouseVocabulary.Person.Name]         = resultItem.name.PrintIfAvailable();
            metadata.Properties[CompanyHouseVocabulary.Person.Officer_role] = resultItem.officer_role.PrintIfAvailable();
            metadata.Properties[CompanyHouseVocabulary.Person.Appointed_on] = resultItem.appointed_on.PrintIfAvailable();

            if (resultItem.address != null)
            {
                PopulatePersonAddressMetadata(metadata, CompanyHouseVocabulary.Person.Address, resultItem.address);
            }

            if (resultItem.date_of_birth != null)
            {
                metadata.Properties[CompanyHouseVocabulary.Person.Date_of_birth] = $"{resultItem.date_of_birth.year}.{resultItem.date_of_birth.month}.1";
            }

            metadata.Properties[CompanyHouseVocabulary.Person.Country_of_residence] = resultItem.country_of_residence.PrintIfAvailable();
            metadata.Properties[CompanyHouseVocabulary.Person.Occupation]           = resultItem.occupation.PrintIfAvailable();
            metadata.Properties[CompanyHouseVocabulary.Person.Nationality]          = resultItem.nationality.PrintIfAvailable();
            metadata.Properties[CompanyHouseVocabulary.Person.Resigned_on]          = resultItem.resigned_on.PrintIfAvailable();
        }
Ejemplo n.º 11
0
        public static void DocumentUpdate([NotNull] IEntityMetadata metadata,
                                          [NotNull] IList <object> newValues,
                                          [CanBeNull] IList <object> oldValues,
                                          [NotNull] IList <string> propertyNames)
        {
            Assert.ArgumentNotNull(metadata, nameof(metadata));
            Assert.ArgumentNotNull(newValues, nameof(newValues));
            Assert.ArgumentNotNull(propertyNames, nameof(propertyNames));

            var changes = new UpdatedEntityState(newValues, oldValues, propertyNames);

            if (changes.OldValuesAreKnown)
            {
                if (changes.IsKnownUpdated(_lastChangedByUserProperty) ||
                    changes.IsKnownUpdated(_lastChangedDateProperty))
                {
                    // one or both of the properties were explicitly assigned as part of the update, keep them
                    return;
                }
            }

            string   userName = GetUserName();
            DateTime now      = DateTime.Now;

            metadata.LastChangedByUser = userName;
            metadata.LastChangedDate   = now;

            changes.Update(_lastChangedDateProperty, metadata.LastChangedDate);
            changes.Update(_lastChangedByUserProperty, metadata.LastChangedByUser);
        }
Ejemplo n.º 12
0
        public ExpressionEntityValueAccessor(IEntityMetadata entity)
        {
            _entity = entity;

            var param = Expression.Parameter(typeof(object), "p");

            var isOfTypeExpression = Expression.Lambda <Func <object, bool> >(
                Expression.TypeIs(param, entity.ClrType),
                param);

            _isOfTypeDelegate = isOfTypeExpression.Compile();

            _primaryKeys = entity.GetProperties().Where(p => p.IsPrimaryKey).ToList();

            if (_primaryKeys.Count == 1)
            {
                _keyType = _primaryKeys[0].PropertyType;
            }
            else if (_primaryKeys.Count > 1)
            {
                var keyTypes = _primaryKeys.Select(p => p.PropertyType).ToArray();
                _keyType = EntityKey.Get(keyTypes);
                _createEntityKeyDelegate = GetCreateEntityKeyDelegate(_keyType);
            }

            if (_primaryKeys.Count > 0)
            {
                this._keyEqualsDelegate = GetKeyEqualsDelegate(_entity.ClrType, _primaryKeys);
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 ///     Extension of Sitecore.Commerce.Plugin.Rules.ModelExtensions.ConvertToAction to allow boolean values
 /// </summary>
 internal static IAction ConvertToActionExtended(
     this ActionModel model,
     IEntityMetadata metaData,
     IEntityRegistry registry,
     IServiceProvider services)
 {
     return(model.Properties.Convert <IAction>(metaData, registry, services));
 }
Ejemplo n.º 14
0
 /// <summary>
 ///     使用实体元数据更新模型状态。
 /// </summary>
 /// <param name="metadata">实体元数据。</param>
 /// <param name="bindingContext">绑定模型的上下文。上下文包含模型对象、模型名称、模型类型、属性筛选器和值提供程序等信息。</param>
 /// <param name="modelStateDic">模型状态键值对。在模型绑定时发生错误的模型状态。</param>
 protected virtual void UpdateModelStateWithEntityMetadata(IEntityMetadata entityMetadata, ModelBindingContext bindingContext, KeyValuePair <string, ModelState> modelStateDic)
 {
     // 当前授权用户没有此属性的编辑权限时,清除模型错误信息。
     if (!HasEditProperty(entityMetadata.EditPropertyMetadatas, modelStateDic.Key))
     {
         modelStateDic.Value.Errors.Clear();
     }
 }
        private IEnumerable <InsertStatement> BuildStatements(IEntityMetadata entity, SchemaMember owner, IEnumerable <SchemaMember> schemas)
        {
            var inherits = entity.GetInherits();

            foreach (var inherit in inherits)
            {
                var statement = new InsertStatement(inherit, owner);

                foreach (var schema in schemas)
                {
                    if (!inherit.Properties.Contains(schema.Name))
                    {
                        continue;
                    }

                    if (schema.Token.Property.IsSimplex)
                    {
                        var simplex = (IEntitySimplexPropertyMetadata)schema.Token.Property;

                        if (simplex.Sequence != null && simplex.Sequence.IsBuiltin)
                        {
                            statement.Sequence = new SelectStatement(owner?.FullPath);
                            statement.Sequence.Select.Members.Add(SequenceExpression.Current(simplex.Sequence.Name, simplex.Name));
                        }
                        else
                        {
                            var field = statement.Table.CreateField(schema.Token);
                            statement.Fields.Add(field);

                            var parameter = this.IsLinked(owner, simplex) ?
                                            Expression.Parameter(schema.Token.Property.Name, simplex.Type) :
                                            Expression.Parameter(ParameterExpression.Anonymous, schema, field);

                            statement.Values.Add(parameter);
                            statement.Parameters.Add(parameter);
                        }
                    }
                    else
                    {
                        if (!schema.HasChildren)
                        {
                            throw new DataException($"Missing members that does not specify '{schema.FullPath}' complex property.");
                        }

                        var complex = (IEntityComplexPropertyMetadata)schema.Token.Property;
                        var slaves  = this.BuildStatements(complex.Foreign, schema, schema.Children);

                        foreach (var slave in slaves)
                        {
                            slave.Schema = schema;
                            statement.Slaves.Add(slave);
                        }
                    }
                }

                yield return(statement);
            }
        }
Ejemplo n.º 16
0
 public GenericRepository(ISqlDeleteGenerator <TEntity> sqlDeleteGenerator, ISqlInsertGenerator <TEntity> sqlInsertGenerator, ISqlSelectGenerator <TEntity> sqlSelectGenerator, ISqlUpdateGenerator <TEntity> sqlUpdateGenerator, IEntityMetadata <TEntity> entityMetadata, IDbConnectionFactory dbConnectionFactory)
 {
     SqlDeleteGenerator  = sqlDeleteGenerator;
     SqlInsertGenerator  = sqlInsertGenerator;
     SqlSelectGenerator  = sqlSelectGenerator;
     SqlUpdateGenerator  = sqlUpdateGenerator;
     EntityMetadata      = entityMetadata;
     DbConnectionFactory = dbConnectionFactory;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// 获取指定实体元素的表名。
        /// </summary>
        /// <param name="entity">指定的实体元素。</param>
        /// <returns>如果实体元素未声明表名则返回该实体元素名。</returns>
        public static string GetTableName(this IEntityMetadata entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            return(string.IsNullOrEmpty(entity.Alias) ? entity.Name : entity.Alias);
        }
Ejemplo n.º 18
0
        public MetadataEntityComplexProperty(IEntityMetadata entity, string name, string role) : base(entity, name, System.Data.DbType.Object)
        {
            if (string.IsNullOrWhiteSpace(role))
            {
                throw new ArgumentNullException(nameof(role));
            }

            this.Role = role;
        }
Ejemplo n.º 19
0
 private static T Convert <T>(
     this IList <PropertyModel> modelProperties,
     IEntityMetadata metaData,
     IEntityRegistry registry,
     IServiceProvider services) where T : IMappableRuleEntity
 {
     if (metaData.Type.GetCustomAttributes(typeof(ObsoleteAttribute), false).Any())
     {
         return(default);
Ejemplo n.º 20
0
        private static void AddTypeToDbContext(IEntityMetadata type, CodeTypeDeclaration codeDbContext)
        {
            var snippet = new CodeSnippetTypeMember
            {
                Text = $"		public DbSet<{type.Name}> {type.TableName ?? type.Name.Pluralize()} {{ get; set; }}"
            };

            codeDbContext.Members.Add(snippet);
        }
Ejemplo n.º 21
0
 public EntityController(IEntityContextBuilder builder)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     EntityBuilder   = builder;
     EntityQueryable = EntityBuilder.GetContext <TEntity>();
     Metadata        = EntityAnalyzer.GetMetadata <TEntity>();
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Validates the specified value with respect to the current validation attribute.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(null);
            }
            object entity = validationContext.ObjectInstance;
            Type   type   = validationContext.ObjectType;

            while (type.GetTypeInfo().Assembly.IsDynamic)
            {
                type = type.GetTypeInfo().BaseType;
            }
            var databaseContext = validationContext.GetRequiredService <IDatabaseContext>();
            var entityContext   = databaseContext.GetDynamicContext(type);

            if (value is string && !IsCaseSensitive)
            {
                value = ((string)value).ToLower();
            }
            ParameterExpression parameter = Expression.Parameter(type);
            IEntityMetadata     metadata  = EntityDescriptor.GetMetadata(type);
            Expression          left      = Expression.NotEqual(Expression.Property(parameter, metadata.KeyProperty.ClrName), Expression.Constant(metadata.KeyProperty.GetValue(entity)));
            Expression          right;

            if (value is string && IsCaseSensitive)
            {
                right = Expression.Equal(Expression.Property(parameter, validationContext.MemberName), Expression.Constant(value));
            }
            else
            {
                right = Expression.Equal(Expression.Call(Expression.Property(parameter, validationContext.MemberName), typeof(string).GetMethod("ToLower")), Expression.Constant(value));
            }
            Expression expression = Expression.And(left, right);

            expression    = Expression.Lambda(typeof(Func <,>).MakeGenericType(type, typeof(bool)), expression, parameter);
            dynamic where = _QWhereMethod.MakeGenericMethod(type).Invoke(null, new[] { entityContext.Query(), expression });
            int count = ((Task <int>)entityContext.CountAsync(where)).Result;;

            if (count != 0)
            {
                if (ErrorMessage != null)
                {
                    return(new ValidationResult(ErrorMessage));
                }
                else
                {
                    return(new ValidationResult(string.Format("{0}不能为“{1}”,因为数据库已存在同样的值。", validationContext.DisplayName, value)));
                }
            }
            else
            {
                return(ValidationResult.Success);
            }
        }
Ejemplo n.º 23
0
        private void PopulateMetadata(IEntityMetadata metadata, IExternalSearchQueryResult <User> resultItem)
        {
            var code = GetOriginEntityCode(resultItem);

            metadata.EntityType       = EntityType.Person;
            metadata.Name             = resultItem.Data.name;
            metadata.OriginEntityCode = code;

            metadata.Codes.Add(code);
            metadata.Properties[HelloWorldVocabularies.User.Email] = resultItem.Data.email;
        }
Ejemplo n.º 24
0
 private void PopulatePersonAddressMetadata(IEntityMetadata metadata, CompanyHousePersonAddressVocabulary vocab, ContactAddress address)
 {
     metadata.Properties[vocab.CareOf]       = address.care_of.PrintIfAvailable();
     metadata.Properties[vocab.Region]       = address.region.PrintIfAvailable();
     metadata.Properties[vocab.Postal_code]  = address.postal_code.PrintIfAvailable();
     metadata.Properties[vocab.Premises]     = address.premises.PrintIfAvailable();
     metadata.Properties[vocab.Country]      = address.country.PrintIfAvailable();
     metadata.Properties[vocab.Locality]     = address.locality.PrintIfAvailable();
     metadata.Properties[vocab.AddressLine1] = address.address_line_1.PrintIfAvailable();
     metadata.Properties[vocab.AddressLine2] = address.address_line_2.PrintIfAvailable();
 }
        protected MetadataEntityProperty(IEntityMetadata entity, string name, System.Data.DbType type)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            _entity = entity ?? throw new ArgumentNullException(nameof(entity));
            _name   = name.Trim();
            _type   = type;
        }
Ejemplo n.º 26
0
        public static IEntityPropertyMetadata Find(this IEntityMetadata entity, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            int index, last = 0;
            IEntityPropertyMetadata property;
            var properties = entity.Properties;

            int GetLast(int position)
            {
                return(position > 0 ? position + 1 : position);
            }

            while ((index = path.IndexOf('.', last + 1)) > 0)
            {
                if (properties.TryGet(path.Substring(GetLast(last), index - GetLast(last)), out property) && property.IsComplex)
                {
                    var complex = (IEntityComplexPropertyMetadata)property;

                    if (complex.ForeignProperty == null)
                    {
                        properties = complex.Foreign.Properties;
                    }
                    else
                    {
                        properties = complex.ForeignProperty.Entity.Properties;
                    }
                }
                else
                {
                    if (property == null)
                    {
                        throw new InvalidOperationException($"The specified '{path}' member does not exist in the '{entity}' entity.");
                    }
                    else
                    {
                        throw new InvalidOperationException($"The specified '{path}' member does not exist in the '{entity}' entity.");
                    }
                }

                last = index;
            }

            if (properties.TryGet(path.Substring(GetLast(last)), out property))
            {
                return(property);
            }

            throw new InvalidOperationException($"The specified '{path}' member does not exist in the '{entity}' entity.");
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Initialize entity context.
        /// </summary>
        /// <param name="dbContext">Database context of entity framework.</param>
        public EntityContext(DbContext dbContext)
        {
            DbContext = dbContext;
            var dbset = DbContext.GetType().GetProperties().FirstOrDefault(t => t.PropertyType == typeof(DbSet <TEntity>));

            if (dbset == null)
            {
                throw new ArgumentException("dbContext doesn't contains DbSet<" + typeof(TEntity).Name + ">");
            }
            DbSet    = (DbSet <TEntity>)dbset.GetValue(DbContext, null);
            Metadata = EntityAnalyzer.GetMetadata <TEntity>();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 获取指定实体元素对应于指定数据类型的成员标记集。
        /// </summary>
        /// <param name="entity">指定的实体元素。</param>
        /// <param name="type">指定的数据类型,即实体元素对应到的输入或输出的数据类型。</param>
        /// <returns>返回实体元素对应指定数据类型的成员标记集。</returns>
        public static IReadOnlyNamedCollection <EntityPropertyToken> GetTokens(this IEntityMetadata entity, Type type)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            return(_cache.GetOrAdd(entity, e => new EntityTokenCache(e)).GetTokens(type));
        }
Ejemplo n.º 29
0
        private void UpdateForeign()
        {
            var index = this.Role.IndexOf(':');

            if (index < 0)
            {
                _foreign = this.Entity.Metadata.Manager.Entities.Get(this.Role);
            }
            else
            {
                _foreign         = this.Entity.Metadata.Manager.Entities.Get(this.Role.Substring(0, index));
                _foreignProperty = _foreign.Properties.Get(this.Role.Substring(index + 1));
            }
        }
Ejemplo n.º 30
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            IEntityMetadata metadata = (IEntityMetadata)value;

            writer.WriteStartObject();

            writer.WritePropertyName("Name");
            writer.WriteValue(metadata.Name);

            writer.WritePropertyName("Key");
            writer.WriteValue(metadata.KeyProperty.ClrName);

            writer.WriteEndObject();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.Controller is EntityController)
                EntityBuilder = ((EntityController)filterContext.Controller).EntityBuilder;
            else
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

                    if (filterContext.RouteData.DataTokens["loginUrl"] == null)
                        filterContext.Result = new RedirectResult(ComBoostAuthentication.LoginUrl + "?returnUrl=" + Uri.EscapeDataString(filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery));
                    else
                        filterContext.Result = new RedirectResult(filterContext.RouteData.DataTokens["loginUrl"].ToString() + "?returnUrl=" + Uri.EscapeDataString(filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery));
                return;
            }
            if (filterContext.Controller is IHaveEntityMetadata)
                Metadata = ((IHaveEntityMetadata)filterContext.Controller).Metadata;
            RouteData = filterContext.RouteData;

            if (!Authorize(filterContext))
            {
                if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                    filterContext.Result = new HttpUnauthorizedResult();
                else
                    if (filterContext.RouteData.DataTokens["loginUrl"] == null)
                        filterContext.Result = new RedirectResult(ComBoostAuthentication.LoginUrl + "?returnUrl=" + Uri.EscapeDataString(filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery));
                    else
                        filterContext.Result = new RedirectResult(filterContext.RouteData.DataTokens["loginUrl"].ToString() + "?returnUrl=" + Uri.EscapeDataString(filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery));
            }
        }