Пример #1
0
        public override bool Perform(object instance, object fieldValue)
        {
            ActiveRecordValidationBase arInstance = (ActiveRecordValidationBase)instance;
            ActiveRecordModel          model      = ActiveRecordBase.GetModel(arInstance.GetType());

            while (model != null)
            {
                if (model.Ids.Count != 0)
                {
                    _pkModel = model.Ids[0] as PrimaryKeyModel;
                }

                model = model.Parent;
            }

            if (_pkModel == null)
            {
                throw new ValidationFailure("We couldn't find the primary key for " + arInstance.GetType().FullName +
                                            " so we can't ensure the uniqueness of any field. Validatior failed");
            }

            _fieldValue = fieldValue;

            return((bool)arInstance.Execute(new NHibernateDelegate(CheckUniqueness)));
        }
Пример #2
0
        private void CreateMappedInstances(object instance, PropertyInfo prop,
                                           PrimaryKeyModel keyModel, ActiveRecordModel otherModel, DataBindContext context)
        {
            object container = InitializeRelationPropertyIfNull(instance, prop);

            // TODO: Support any kind of key

            String paramName = String.Format("{0}.{1}", prop.Name, keyModel.Property.Name);

            String[] values = context.ParamList.GetValues(paramName);

            int[] ids = (int[])ConvertUtils.Convert(typeof(int[]), values, paramName, null, context.ParamList);

            if (ids != null)
            {
                foreach (int id in ids)
                {
                    object item = Activator.CreateInstance(otherModel.Type);

                    keyModel.Property.SetValue(item, id, EmptyArg);

                    AddToContainer(container, item);
                }
            }
        }
Пример #3
0
        private object ObtainPrimaryKeyValue(ActiveRecordModel model, CompositeNode node, String prefix,
                                             out PrimaryKeyModel pkModel)
        {
            pkModel = ObtainPrimaryKey(model);

            var pkPropName = pkModel.Property.Name;

            var idNode = node.GetChildNode(pkPropName);

            if (idNode == null)
            {
                return(null);
            }

            if (idNode != null && idNode.NodeType != NodeType.Leaf)
            {
                throw new BindingException("Expecting leaf node to contain id for ActiveRecord class. " +
                                           "Prefix: {0} PK Property Name: {1}", prefix, pkPropName);
            }

            var lNode = (LeafNode)idNode;

            if (lNode == null)
            {
                throw new BindingException("ARDataBinder autoload failed as element {0} " +
                                           "doesn't have a primary key {1} value", prefix, pkPropName);
            }

            bool conversionSuc;

            return(Converter.Convert(pkModel.Property.PropertyType, lNode.ValueType, lNode.Value, out conversionSuc));
        }
Пример #4
0
        private object LoadActiveRecord(Type type, object pk, ARFetchAttribute attr, ActiveRecordModel model)
        {
            object obj = null;

            if (pk != null && !String.Empty.Equals(pk))
            {
                PrimaryKeyModel pkModel = (PrimaryKeyModel)model.Ids[0];

                Type pkType = pkModel.Property.PropertyType;

                if (pk.GetType() != pkType)
                {
                    pk = Convert.ChangeType(pk, pkType);
                }

                obj = SupportingUtils.FindByPK(type, pk, attr.Required);
            }

            if (obj == null && attr.Create)
            {
                obj = Activator.CreateInstance(type);
            }

            return(obj);
        }
Пример #5
0
        protected internal static bool Exists(Type t, object pk, ICriterion criteria)
        {
            PrimaryKeyModel pkModel = ActiveRecordModel.GetModel(t).PrimaryKey;
            string          pkField = pkModel.Property.Name;
            object          o       = FindFirst(t, Expression.And(criteria, Expression.Not(Expression.Eq(pkField, pk))));

            return(o != null);
        }
Пример #6
0
        /// <summary>
        /// Gets the property that represents the Primary key
        /// for the current <see cref="ActiveRecordModel"/>
        /// </summary>
        /// <returns></returns>
        protected PropertyInfo ObtainPKProperty()
        {
            PrimaryKeyModel keyModel = ARCommonUtils.ObtainPKProperty(model);

            if (keyModel != null)
            {
                return(keyModel.Property);
            }

            return(null);
        }
Пример #7
0
        /// <summary>
        /// Perform the check that the property value is unqiue in the table
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="fieldValue"></param>
        /// <returns><c>true</c> if the field is OK</returns>
        public override bool IsValid(object instance, object fieldValue)
        {
            Type instanceType       = instance.GetType();
            ActiveRecordModel model = ActiveRecordBase.GetModel(instance.GetType());

            while (model != null)
            {
                if (model.PrimaryKey != null)
                {
                    pkModel = model.PrimaryKey;
                }

                model = model.Parent;
            }

            if (pkModel == null)
            {
                throw new ValidationFailure("We couldn't find the primary key for " + instanceType.FullName +
                                            " so we can't ensure the uniqueness of any field. Validatior failed");
            }

            IsUniqueValidator.fieldValue = fieldValue;

            SessionScope scope        = null;
            FlushMode?   originalMode = null;

            if (SessionScope.Current == null /*||
                                              * SessionScope.Current.ScopeType != SessionScopeType.Transactional*/)
            {
                scope = new SessionScope();
            }
            else
            {
                originalMode = ActiveRecordBase.holder.CreateSession(instanceType).FlushMode;
                ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = FlushMode.Never;
            }

            try
            {
                return((bool)ActiveRecordMediator.Execute(instanceType, CheckUniqueness, instance));
            }
            finally
            {
                if (scope != null)
                {
                    scope.Dispose();
                }

                if (originalMode != null)
                {
                    ActiveRecordBase.holder.CreateSession(instanceType).FlushMode = originalMode ?? FlushMode.Commit;
                }
            }
        }
Пример #8
0
        protected override object CreateInstance(Type instanceType, String paramPrefix, NameValueCollection paramsList)
        {
            object instance = null;

            bool shouldLoad = autoLoad || paramsList[paramPrefix + AutoLoadAttribute] == Yes;

            if (shouldLoad && paramsList[paramPrefix + AutoLoadAttribute] == No)
            {
                shouldLoad = false;
            }

            if (shouldLoad)
            {
                if (instanceType.IsArray)
                {
                    throw new RailsException("ARDataBinder autoload does not support arrays");
                }

                if (!typeof(ActiveRecordBase).IsAssignableFrom(instanceType))
                {
                    throw new RailsException("ARDataBinder autoload only supports classes that inherit from ActiveRecordBase");
                }

                ActiveRecordModel model = ActiveRecordModel.GetModel(instanceType);

                // NOTE: as of right now we only support one PK
                if (model.Ids.Count == 1)
                {
                    PrimaryKeyModel pkModel = model.Ids[0] as PrimaryKeyModel;

                    string propName    = pkModel.Property.Name;
                    string paramListPk = (paramPrefix == String.Empty) ? propName : paramPrefix + "." + propName;
                    string propValue   = paramsList.Get(paramListPk);

                    if (propValue != null)
                    {
                        object id = ConvertUtils.Convert(pkModel.Property.PropertyType, propValue, propName, null, null);
                        instance = SupportingUtils.FindByPK(instanceType, id);
                    }
                    else
                    {
                        throw new RailsException("ARDataBinder autoload failed as element {0} doesn't have a primary key {1} value", paramPrefix, propName);
                    }
                }
            }
            else
            {
                instance = base.CreateInstance(instanceType, paramPrefix, paramsList);
            }

            return(instance);
        }
Пример #9
0
        private bool CheckModelAndKeyAreAccessible(Type type)
        {
            ActiveRecordModel otherModel = ActiveRecordModel.GetModel(type);

            PrimaryKeyModel keyModel = ObtainPKProperty(otherModel);

            if (otherModel == null || keyModel == null)
            {
                return(false);
            }

            return(true);
        }
Пример #10
0
        protected void SaveManyMappings(object instance, ActiveRecordModel model, DataBindContext context)
        {
            foreach (HasManyModel hasManyModel in model.HasMany)
            {
                if (hasManyModel.HasManyAtt.Inverse)
                {
                    continue;
                }
                if (hasManyModel.HasManyAtt.RelationType != RelationType.Bag &&
                    hasManyModel.HasManyAtt.RelationType != RelationType.Set)
                {
                    continue;
                }

                ActiveRecordModel otherModel = ActiveRecordModel.GetModel(hasManyModel.HasManyAtt.MapType);

                PrimaryKeyModel keyModel = ARCommonUtils.ObtainPKProperty(otherModel);

                if (otherModel == null || keyModel == null)
                {
                    continue;                     // Impossible to save
                }

                CreateMappedInstances(instance, hasManyModel.Property, keyModel, otherModel, context);
            }

            foreach (HasAndBelongsToManyModel hasManyModel in model.HasAndBelongsToMany)
            {
                if (hasManyModel.HasManyAtt.Inverse)
                {
                    continue;
                }
                if (hasManyModel.HasManyAtt.RelationType != RelationType.Bag &&
                    hasManyModel.HasManyAtt.RelationType != RelationType.Set)
                {
                    continue;
                }

                ActiveRecordModel otherModel = ActiveRecordModel.GetModel(hasManyModel.HasManyAtt.MapType);

                PrimaryKeyModel keyModel = ARCommonUtils.ObtainPKProperty(otherModel);

                if (otherModel == null || keyModel == null)
                {
                    continue;                     // Impossible to save
                }

                CreateMappedInstances(instance, hasManyModel.Property, keyModel, otherModel, context);
            }
        }
Пример #11
0
        public String CreateControl(ActiveRecordModel model, BelongsToModel belongsToModel, object instance)
        {
            stringBuilder.Length = 0;

            PropertyInfo prop = belongsToModel.Property;

            ActiveRecordModel otherModel = ActiveRecordModel.GetModel(belongsToModel.BelongsToAtt.Type);

            PrimaryKeyModel keyModel = ObtainPKProperty(otherModel);

            if (otherModel == null || keyModel == null)
            {
                return("Model not found or PK not found");
            }

            object[] items = CommonOperationUtils.FindAll(otherModel.Type);

            String propName = String.Format("{0}.{1}", prop.Name, keyModel.Property.Name);

            object value = null;

            if (instance != null)
            {
                if (model.IsNestedType)
                {
                    instance = model2nestedInstance[model];
                }

                if (instance != null)
                {
                    value = prop.GetValue(instance, null);
                }
            }

            stringBuilder.Append(LabelFor(propName, prop.Name + ": &nbsp;"));

            stringBuilder.Append(Select(propName));

            if (!belongsToModel.BelongsToAtt.NotNull)
            {
                stringBuilder.Append(CreateOption("Empty", 0));
            }

            stringBuilder.Append(CreateOptionsFromArray(items, null, keyModel.Property.Name, value));

            stringBuilder.Append(EndSelect());

            return(stringBuilder.ToString());
        }
Пример #12
0
 public TableModel(string name,
                   string schema,
                   PropertyModel property,
                   ImmutableArray <ColumnModel> columns,
                   PrimaryKeyModel primaryKey,
                   ImmutableArray <ForeignKeyModel> foreignKeys,
                   ImmutableArray <IndexModel> indexes)
 {
     Name        = name;
     Schema      = schema;
     Property    = property;
     Columns     = columns;
     PrimaryKey  = primaryKey;
     ForeignKeys = foreignKeys;
     Indexes     = indexes;
 }
Пример #13
0
        public ICreateTableBuilder <TColumns> PrimaryKey(Expression <Func <TColumns, object> > keyExpression, bool identity = false, string name = null,
                                                         bool clustered = true)
        {
            var pkCols = ExtractColumnList(keyExpression.Compile()(_columns));

            if (identity == true && pkCols.Count > 1)
            {
                throw new TooManyColumnsForIdentityException(pkCols);
            }
            var notInTable = pkCols.Where(pkc => !_columnsList.Contains(pkc)).ToList();

            if (notInTable.Any())
            {
                throw new PKContainsColumnsNotInTableException(notInTable);
            }
            var pkModel = new PrimaryKeyModel(pkCols, identity, name, clustered);

            _operation.AddPrimaryKey(pkModel);
        }
Пример #14
0
        private static Array CreateArrayFromExistingIds(PrimaryKeyModel keyModel, ICollection container)
        {
            if (container == null || container.Count == 0)
            {
                return(null);
            }

            Array array = Array.CreateInstance(keyModel.Property.PropertyType, container.Count);

            int index = 0;

            foreach (object item in container)
            {
                object val = keyModel.Property.GetValue(item, Empty);

                array.SetValue(val, index++);
            }

            return(array);
        }
Пример #15
0
        public String CreateControl(ActiveRecordModel model, HasAndBelongsToManyModel hasAndBelongsModel, object instance)
        {
            stringBuilder.Length = 0;

            PropertyInfo prop = hasAndBelongsModel.Property;

            ActiveRecordModel otherModel = ActiveRecordModel.GetModel(hasAndBelongsModel.HasManyAtt.MapType);

            PrimaryKeyModel keyModel = ObtainPKProperty(otherModel);

            if (otherModel == null || keyModel == null)
            {
                return("Model not found or PK not found");
            }

            object container = InitializeRelationPropertyIfNull(instance, prop);

            object value = null;

            if (container != null)
            {
                value = CreateArrayFromExistingIds(keyModel, container as ICollection);
            }

            object[] items = CommonOperationUtils.FindAll(otherModel.Type, hasAndBelongsModel.HasManyAtt.Where);

            String propName = String.Format("{0}.{1}", prop.Name, keyModel.Property.Name);

            stringBuilder.Append(LabelFor(propName, prop.Name + ": &nbsp;"));
            stringBuilder.Append("<br/>");
            stringBuilder.Append(Select(propName, new DictHelper().CreateDict("size=6", "multiple")));
            stringBuilder.Append(CreateOptionsFromArray(items, null, keyModel.Property.Name, value));
            stringBuilder.Append(EndSelect());

            return(stringBuilder.ToString());
        }
 public void AddPrimaryKey(PrimaryKeyModel pkModel)
 {
 }
Пример #17
0
 public ARLoaderEnumerator(Type arType, IEnumerable keys)
     : base(keys.GetEnumerator())
 {
     this.pkModel = ActiveRecordModel.GetModel(arType).PrimaryKey;
     this.arType  = arType;
 }