FindField() public method

public FindField ( string fieldName ) : Field
fieldName string
return Field
 public static List<PropertyItem> GetCustomFieldPropertyItems(IEnumerable<ICustomFieldDefinition> definitions, Row row, string fieldPrefix)
 {
     var list = new List<PropertyItem>();
     foreach (var def in definitions)
     {
         string name = fieldPrefix + def.Name;
         var field = row.FindFieldByPropertyName(name) ?? row.FindField(name);
         list.Add(GetCustomFieldPropertyItem(def, field));
     }
     return list;
 }
        public bool ActivateFor(Row row)
        {
            if (ReferenceEquals(null, Target))
                return false;

            attr = Target.GetAttribute<ImageUploadEditorAttribute>();
            if (attr == null || attr.DisableDefaultBehavior || attr.EditorType != "ImageUpload")
                return false;

            if (!(Target is StringField))
                throw new ArgumentException(String.Format(
                    "Field '{0}' on row type '{1}' has a UploadEditor attribute but it is not a String field!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));

            if (!(row is IIdRow))
                throw new ArgumentException(String.Format(
                    "Field '{0}' on row type '{1}' has a UploadEditor attribute but Row type doesn't implement IIdRow!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));

            if (!attr.OriginalNameProperty.IsEmptyOrNull())
            {
                var originalNameField = row.FindFieldByPropertyName(attr.OriginalNameProperty) ??
                    row.FindField(attr.OriginalNameProperty);

                if (ReferenceEquals(null, originalNameField))
                    throw new ArgumentException(String.Format(
                        "Field '{0}' on row type '{1}' has a UploadEditor attribute but " +
                        "a field with OriginalNameProperty '{2}' is not found!",
                            Target.PropertyName ?? Target.Name, 
                            row.GetType().FullName,
                            attr.OriginalNameProperty));

                this.originalNameField = (StringField)originalNameField;
            }

            var format = attr.FilenameFormat;

            if (format == null)
            {
                format = row.GetType().Name;
                if (format.EndsWith("Row"))
                    format = format.Substring(0, format.Length - 3);
                format += "/~";
            }

            this.fileNameFormat = format.Replace("~", SplittedFormat);
            this.replaceFields = ParseReplaceFields(fileNameFormat, row, Target);
            this.uploadHelper = new UploadHelper((attr.SubFolder.IsEmptyOrNull() ? "" : (attr.SubFolder + "/")) + (this.fileNameFormat));

            return true;
        }
Esempio n. 3
0
        /// <summary>
        ///   Converts a list of FilterLine objects to a WHERE clause usable in a SQL select query.</summary>
        /// <param name="lines">
        ///   List of FilterLine objects to convert to a WHERE clause.</param>
        /// <param name="filterFields">
        ///   Collection of FilterField objects to determine field types and check filterability of fields.
        ///   This list is usually the filter field options list that is sent to a filter panel object.
        ///   If this list is specified, for a filter to be considered valid, its fieldname must be
        ///   found in the list. If the list is given null, field name is looked up in fieldExpressions,
        ///   query or row and field type is determined by the field object in the row.</param>
        /// <param name="fieldExpressions">
        ///   An optional dictionary of field expressions. If a field's corresponding SQL expression like
        ///   "join.field_name" is not determinable by reading in the query or the row, this list must be specified.
        ///   When specified, this list takes priority over the query and row objects to determine the field
        ///   expression.</param>
        /// <param name="query">
        ///   An optional SqlSelect query to determine field expressions. If a field's expression is not found
        ///   in "fieldExpressions" dictionary, it is looked up in query object.</param>
        /// <param name="row">
        ///   An optional Row object to determine field types and expressions.</param>
        /// <param name="process">
        ///   An optional delegate to preprocess a filter line and return a filter. It should return an empty
        ///   filter if this line should be ignored. Null if this line should be processed as usual.</param>
        /// <returns>
        ///   WHERE clause.</returns>
        /// <remarks>
        ///   Invalid filter lines are simply skipped, no error occurs.</remarks>
        public static string ToWhereString(SqlQuery query, IEnumerable <FilterLine> lines, FilterFields filterFields,
                                           IDictionary <string, string> fieldExpressions = null, Row row = null, Func <FilterLine, BaseCriteria> process = null)
        {
            if (lines == null)
            {
                throw new ArgumentNullException("lines");
            }

            const string AND    = " AND ";
            const string OR     = " OR ";
            const string LPAREN = "(";
            const string RPAREN = ")";
            //const string TRUE = "1=1";

            // build a dictionary of FilterField objects if the list is specified
            // this list is usually the filter field options list that is sent to FilterPanel object.

            /*Dictionary<string, FilterField> filterFieldDict = null;
             * if (filterFields != null)
             * {
             *  filterFieldDict = new Dictionary<string, FilterField>(StringComparer.OrdinalIgnoreCase);
             *  foreach (FilterField f in filterFields)
             *  {
             *      filterFieldDict[f.GetName()] = f;
             *
             *      if (f.GetTextual() != null)
             *          filterFieldDict[f.GetTextual()] = f;
             *  }
             * }*/

            bool inParens = false;
            bool hasOr    = false;

            StringBuilder sb = new StringBuilder();

            foreach (FilterLine line in lines)
            {
                if (inParens &&
                    (line._rightParen || line._leftParen))
                {
                    sb.Append(RPAREN);
                    inParens = false;
                }

                if (sb.Length > 0)
                {
                    sb.Append(line._or ? OR : AND);
                    if (line._or)
                    {
                        hasOr = true;
                    }
                }

                if (line._leftParen)
                {
                    sb.Append(LPAREN);
                    inParens = true;
                }

                if (!line.IsValid)
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                    //sb.Append(TRUE);
                    //continue;
                }

                if (process != null)
                {
                    var filter = process(line);
                    if (!Object.ReferenceEquals(filter, null))
                    {
                        if (filter.IsEmpty)
                        {
                            //sb.Append(TRUE);
                            throw new ArgumentOutOfRangeException("EmptyFilterLine", line.ToJson());
                        }
                        else
                        {
                            sb.Append(filter.ToStringIgnoreParams()); // FIX!!!!
                        }
                        continue;
                    }
                }

                string fieldName = line.Field;

                // if filter fields list is specified, the fieldname must exist in this list, otherwise
                // it may be an hacking attempt, as user tries to filter a field that he is not
                // represented with
                IFilterField filterField = null;
                if (filterFields != null)
                {
                    filterField = filterFields.ByNameOrTextual(fieldName);
                    if (filterField == null)
                    {
                        throw new ArgumentOutOfRangeException("UnknownFilterField", line.ToJson());
                    }
                    //sb.Append(TRUE);
                    //continue;
                }

                Field field = null;
                if (row != null)
                {
                    field = row.FindField(fieldName);
                }


                /*// by default, suppose fields are string typed
                 * FilterFieldType type = FilterFieldType.String;
                 * // if given, determine field type by looking up in the filter field options
                 * if (filterField != null)
                 *  type = filterField.GetType();
                 * // otherwise, determine field type by the class of field object
                 * else if (field != null)
                 *  type = FilterField.ToFilterFieldType(field);*/

                // to determine field expression, first look it up in fieldExpressions dictionary
                string fieldExpr;
                if (fieldExpressions == null ||
                    !fieldExpressions.TryGetValue(fieldName, out fieldExpr))
                {
                    fieldExpr = null;
                }

                if (fieldExpr == null)
                {
                    if (field != null)
                    {
                        fieldExpr = field.Expression;
                    }
                    else if (query != null)
                    {
                        fieldExpr = query.GetExpression(fieldName);
                    }
                }

                if (fieldExpr == null)
                {
                    // field is not found anywhere, don't allow unknown fields as it may cause a script injection
                    // attack or other types of security threats!
                    //sb.Append(TRUE);
                    throw new ArgumentOutOfRangeException("UnknownFilterField", line.ToJson());
                    //continue;
                }

                bool isNumeric =
                    (filterField != null && (filterField.Handler == "Integer" || filterField.Handler == "Decimal")) ||
                    (filterField == null && field != null &&
                     (field is Int16Field || field is Int32Field || field is Int64Field || field is DoubleField || field is DecimalField));

                // determine expression for this filter by operator type
                FilterOp op    = line.Op;
                string   sqlOp = SqlConditionOperators[(int)(op)];

                if (op == FilterOp.IN)
                {
                    StringBuilder vs = new StringBuilder();

                    var values = line.Values;
                    if (line.Values != null)
                    {
                        foreach (var s in line.Values)
                        {
                            if (isNumeric)
                            {   // parse invariant decimal value for integer and float fields
                                decimal d;
                                if (Decimal.TryParse(s, NumberStyles.Float, Invariants.NumberFormat, out d))
                                {
                                    if (vs.Length > 0)
                                    {
                                        vs.Append(",");
                                    }
                                    vs.Append(d.ToInvariant());
                                }
                            }
                            else
                            {
                                if (vs.Length > 0)
                                {
                                    vs.Append(",");
                                }
                                vs.Append(s.ToSql());
                            }
                        }
                    }

                    if (vs.Length == 0)
                    {
                        //sb.Append(TRUE);
                        throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                    }
                    else
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, vs.ToString());
                    }

                    continue;
                }

                // operator needs value if not one of "true", "false", "is null", "is not null"
                if (op.IsNeedsValue())
                {
                    // starts with and contains operators requires special care, as their sql expressions
                    // already contains single quotes, so .ToSql() cannot be used
                    if (op.IsLike())
                    {
                        if (line.Value != null)
                        {
                            sb.AppendFormat(SqlConditionOperators[(int)(op)],
                                            fieldExpr, line.Value.Replace("'", "''"));
                        }
                        continue;
                    }

                    // parse value1 and value2
                    string value1 = "";
                    string value2 = "";

                    // simple loop to parse value1 and value2 in one turn
                    for (int phase = 0; phase <= 1; phase++)
                    {
                        string valueText;

                        if (phase == 0)
                        {
                            valueText = line.Value;
                        }
                        else
                        {
                            valueText = line.Value2;
                        }

                        valueText = valueText.TrimToNull();

                        // value must be entered
                        if (valueText == null)
                        {
                            throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                        }

                        bool isDateTime =
                            (filterField != null && (filterField.Handler == "Date")) ||
                            (filterField == null && field != null &&
                             (field is DateTimeField));

                        if (isNumeric)
                        {   // parse invariant decimal value for integer and float fields
                            decimal d;
                            if (!Decimal.TryParse(valueText, NumberStyles.Float, Invariants.NumberFormat, out d))
                            {
                                throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                            }

                            valueText = d.ToInvariant();
                        }
                        else if (isDateTime)
                        {   // parse iso date-time string
                            DateTime d;
                            if (!DateHelper.TryParseISO8601DateTime(valueText, out d))
                            {
                                throw new ArgumentOutOfRangeException("InvalidFilterLine", line.ToJson());
                            }

                            DateTimeKind kind = DateTimeKind.Unspecified;
                            object       dateKindObj;
                            if (filterField != null && filterField.Params != null && filterField.Params.TryGetValue("DateKind", out dateKindObj))
                            {
                                var dateKind = ((DateFilterKind)Convert.ToInt32(dateKindObj));
                                kind = dateKind == DateFilterKind.DateTimeLocal ? DateTimeKind.Local : (dateKind == DateFilterKind.DateTimeUTC ? DateTimeKind.Utc : DateTimeKind.Unspecified);
                            }
                            else if (field != null && field is DateTimeField)
                            {
                                kind = ((DateTimeField)field).DateTimeKind;
                            }

                            d = DateTimeField.ToDateTimeKind(d, kind);

                            if (op == FilterOp.BW)
                            {
                                if (phase == 1)
                                {
                                    sqlOp = "{0} >= {1} AND {0} < {2}";
                                    d     = d.AddDays(1);
                                }
                            }
                            else if (phase == 0)
                            {
                                if (op == FilterOp.NE || op == FilterOp.EQ)
                                {
                                    value1 = d.ToSql();
                                    value2 = d.AddDays(1).ToSql();
                                    if (op == FilterOp.NE)
                                    {
                                        sqlOp = "NOT ({0} >= {1} AND {0} < {2})";
                                    }
                                    else
                                    {
                                        sqlOp = "{0} >= {1} AND {0} < {2}";
                                    }
                                    op = FilterOp.BW;
                                    break;
                                }
                                else
                                {
                                    if (op == FilterOp.GT)
                                    {
                                        op = FilterOp.GE;
                                        d  = d.AddDays(1);
                                    }
                                    else if (op == FilterOp.LE)
                                    {
                                        op = FilterOp.LT;
                                        d  = d.AddDays(1);
                                    }
                                }
                            }

                            valueText = d.ToSql();
                        }
                        else // convert simple string value to sql string (duplicate quotes)
                        {
                            valueText = valueText.ToSql();
                        }

                        if (phase == 0)
                        {
                            value1 = valueText;
                        }
                        else
                        {
                            value2 = valueText;
                        }

                        // use second phase to parse value2 if operator is BW
                        if (op != FilterOp.BW)
                        {
                            break;
                        }
                    }

                    // format sql operator text with values
                    if (op == FilterOp.BW)
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, value1, value2);
                    }
                    else
                    {
                        sb.AppendFormat(sqlOp, fieldExpr, value1);
                    }
                }
                else
                {
                    sb.AppendFormat(sqlOp, fieldExpr);
                }
            }

            if (inParens)
            {
                sb.Append(RPAREN);
            }

            if (hasOr)
            {
                sb.Append(RPAREN);
                sb.Insert(0, LPAREN);
            }

            return(sb.ToString());
        }
        private BaseCriteria Convert(BasicFilter filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("criteria");
            }

            if (!filter.IsValid)
            {
                throw new ArgumentOutOfRangeException("InvalidFilterCriteria", filter.ToJson());
            }

            if (_processCriteria != null)
            {
                var processed = _processCriteria(filter);
                if (!Object.ReferenceEquals(processed, null))
                {
                    if (processed.IsEmpty)
                    {
                        throw new ArgumentOutOfRangeException("EmptyFilterLine", filter.ToJson());
                    }

                    return(processed);
                }
            }

            string fieldName = filter.Field;

            Field field = null;

            if (_row != null)
            {
                field = _row.FindField(fieldName);
            }

            // if filter fields list is specified, the fieldname must exist in this list, otherwise
            // it may be an hacking attempt, as user tries to filter a field that he is not
            // represented with
            IFilterField filterField = null;

            if (filterFields != null)
            {
                filterField = filterFields.ByNameOrTextual(fieldName);
                if (filterField == null &&
                    (field == null || field.Flags.HasFlag(FieldFlags.DenyFiltering)))
                {
                    throw new ArgumentOutOfRangeException("UnknownFilterField", fieldName);
                }
            }

            //var type = GetFilterFieldType(field, fieldName);
            var fieldExpr = GetFieldExpression(field, fieldName);

            if (fieldExpr == null)
            {
                // field is not found anywhere, don't allow unknown fields as it may cause a script injection
                // attack or other types of security threats!
                throw new ArgumentOutOfRangeException("UnknownFilterField", filter.ToJson());
            }

            bool isInteger = (filterField != null && (filterField.Handler == "Integer")) ||
                             (filterField == null && field != null && (field is Int16Field || field is Int32Field || field is Int64Field));

            bool isDecimal = (filterField != null && (filterField.Handler == "Decimal")) ||
                             (filterField == null && field != null && (field is DoubleField || field is DecimalField));

            bool isNumeric = isInteger || isDecimal;

            bool isDateTime =
                (filterField != null && (filterField.Handler == "Date")) ||
                (filterField == null && field != null &&
                 (field is DateTimeField));

            var op = filter.Operator;

            switch (op)
            {
            case FilterOp.True:
                return(new Criteria(fieldExpr) == 1);

            case FilterOp.False:
                return(new Criteria(fieldExpr) == 0);

            case FilterOp.IsNull:
                return(new Criteria(fieldExpr).IsNull());

            case FilterOp.IsNotNull:
                return(new Criteria(fieldExpr).IsNotNull());

            case FilterOp.Like:
                return(new Criteria(fieldExpr).Like(filter.Value));

            case FilterOp.NotLike:
                return(new Criteria(fieldExpr).NotLike(filter.Value));

            case FilterOp.Contains:
                return(new Criteria(fieldExpr).Contains(filter.Value));

            case FilterOp.NotContains:
                return(new Criteria(fieldExpr).NotContains(filter.Value));

            case FilterOp.StartsWith:
                return(new Criteria(fieldExpr).StartsWith(filter.Value));

            case FilterOp.EndsWith:
                return(new Criteria(fieldExpr).EndsWith(filter.Value));

            case FilterOp.IN:
            case FilterOp.NotIN:
            {
                var values = new List <object>();
                foreach (var s in filter.Values)
                {
                    if (isDecimal)
                    {
                        values.Add(ParseDoubleValue(s));
                    }
                    else if (isInteger)
                    {
                        values.Add(ParseIntegerValue(field, s));
                    }
                    else
                    {
                        values.Add(s);
                    }
                }

                if (values.Count == 0)
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", filter.ToJson());
                }

                if (op == FilterOp.IN)
                {
                    return(new Criteria(fieldExpr).In(values.ToArray()));
                }
                else
                {
                    return(new Criteria(fieldExpr).NotIn(values.ToArray()));
                }
            }
            }

            // parse value1 and value2
            string value1Text = filter.Value.TrimToEmpty();
            string value2Text = filter.Value2.TrimToEmpty();

            if ((op == FilterOp.BW || op == FilterOp.NotBW))
            {
                if (value1Text.IsNullOrEmpty() || value2Text.IsNullOrEmpty())
                {
                    throw new ArgumentOutOfRangeException("InvalidFilterLine", filter.ToJson());
                }

                if (isInteger)
                {
                    return(new Criteria(fieldExpr) >= ParseIntegerValue(field, value1Text) &
                           new Criteria(fieldExpr) <= ParseIntegerValue(field, value2Text));
                }
                else if (isDecimal)
                {
                    return(new Criteria(fieldExpr) >= ParseDoubleValue(value1Text) &
                           new Criteria(fieldExpr) <= ParseDoubleValue(value2Text));
                }
                else if (isDateTime)
                {
                    var d1 = ParseDateTimeValue(value1Text);
                    var d2 = ParseDateTimeValue(value2Text);

                    if (d1.Date == d1 && d2.Date == d2)
                    {
                        if (op == FilterOp.BW)
                        {
                            return(new Criteria(fieldExpr) >= d1.Date & new Criteria(fieldExpr) < d2.Date.AddDays(1));
                        }
                        else
                        {
                            return(~(new Criteria(fieldExpr) < d1.Date | new Criteria(fieldExpr) >= d2.Date.AddDays(1)));
                        }
                    }
                    else
                    {
                        if (op == FilterOp.BW)
                        {
                            return(new Criteria(fieldExpr) >= d1 & new Criteria(fieldExpr) <= d2);
                        }
                        else
                        {
                            return(~((new Criteria(fieldExpr) < d1 | new Criteria(fieldExpr) > d2)));
                        }
                    }
                }
                else
                {
                    if (op == FilterOp.BW)
                    {
                        return(new Criteria(fieldExpr) >= value1Text & new Criteria(fieldExpr) <= value2Text);
                    }
                    else
                    {
                        return(~((new Criteria(fieldExpr) < value2Text | new Criteria(fieldExpr) > value2Text)));
                    }
                }
            }

            var result = new Criteria(fieldExpr);

            if (isInteger)
            {
                var i = ParseIntegerValue(field, value1Text);
                if (op == FilterOp.EQ)
                {
                    return(result == i);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != i);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > i);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= i);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < i);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= i);
                }
            }
            else if (isDecimal)
            {
                var o = ParseIntegerValue(field, value1Text);
                if (op == FilterOp.EQ)
                {
                    return(result == o);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != o);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > o);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= o);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < o);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= o);
                }
            }
            else if (isDateTime)
            {
                var d = ParseDateTimeValue(value1Text);
                if (d.Date == d)
                {
                    if (op == FilterOp.EQ)
                    {
                        return(result >= d & result < d.AddDays(1));
                    }
                    else if (op == FilterOp.NE)
                    {
                        return(~(result < d | result >= d.AddDays(1)));
                    }
                    else if (op == FilterOp.GT)
                    {
                        return(result >= d.AddDays(1));
                    }
                    else if (op == FilterOp.GE)
                    {
                        return(result >= d);
                    }
                    else if (op == FilterOp.LT)
                    {
                        return(result < d);
                    }
                    else if (op == FilterOp.LE)
                    {
                        return(result < d.AddDays(1));
                    }
                }
                else
                {
                    if (op == FilterOp.EQ)
                    {
                        return(result == d);
                    }
                    else if (op == FilterOp.NE)
                    {
                        return(result != d);
                    }
                    else if (op == FilterOp.GT)
                    {
                        return(result > d);
                    }
                    else if (op == FilterOp.GE)
                    {
                        return(result >= d);
                    }
                    else if (op == FilterOp.LT)
                    {
                        return(result < d);
                    }
                    else if (op == FilterOp.LE)
                    {
                        return(result <= d);
                    }
                }
            }
            else
            {
                if (op == FilterOp.EQ)
                {
                    return(result == value1Text);
                }
                else if (op == FilterOp.NE)
                {
                    return(result != value1Text);
                }
                else if (op == FilterOp.GT)
                {
                    return(result > value1Text);
                }
                else if (op == FilterOp.GE)
                {
                    return(result >= value1Text);
                }
                else if (op == FilterOp.LT)
                {
                    return(result < value1Text);
                }
                else if (op == FilterOp.LE)
                {
                    return(result <= value1Text);
                }
            }

            throw new InvalidOperationException();
        }
        public bool ActivateFor(Row row)
        {
            var attrs = row.GetType().GetCustomAttributes<UpdatableExtensionAttribute>();

            if (attrs == null || !attrs.Any())
                return false;

            var sourceByExpression = row.GetFields().ToLookup(x =>
                BracketLocator.ReplaceBrackets(x.Expression.TrimToEmpty(), BracketRemoverDialect.Instance));

            this.infoList = attrs.Select(attr =>
            {
                var info = new RelationInfo();
                info.Attr = attr;

                var rowType = attr.RowType;
                if (rowType.GetIsAbstract() ||
                    !typeof(Row).IsAssignableFrom(rowType))
                {
                    throw new ArgumentException(String.Format(
                        "Row type '{1}' has an ExtensionRelation attribute " +
                        "but its specified extension row type '{0}' is not a valid row class!",
                            rowType.FullName,
                            row.GetType().FullName));
                }

                info.RowFactory = FastReflection.DelegateForConstructor<Row>(rowType);

                info.ListHandlerFactory = FastReflection.DelegateForConstructor<IListRequestProcessor>(
                    typeof(ListRequestHandler<>).MakeGenericType(rowType));

                info.SaveHandlerFactory = FastReflection.DelegateForConstructor<ISaveRequestProcessor>(
                    typeof(SaveRequestHandler<>).MakeGenericType(rowType));

                info.SaveRequestFactory = FastReflection.DelegateForConstructor<ISaveRequest>(
                    typeof(SaveRequest<>).MakeGenericType(rowType));

                info.DeleteHandlerFactory = FastReflection.DelegateForConstructor<IDeleteRequestProcessor>(
                    typeof(DeleteRequestHandler<>).MakeGenericType(rowType));

                var thisKey = attr.ThisKey;
                if (string.IsNullOrEmpty(thisKey))
                {
                    if (!(row is IIdRow))
                    {
                        throw new ArgumentException(String.Format(
                            "Row type '{0}' has an ExtensionRelation attribute " +
                            "but its ThisKey is not specified!",
                                row.GetType().FullName));
                    }

                    info.ThisKeyField = (Field)(((IIdRow)row).IdField);
                }
                else
                {
                    info.ThisKeyField = row.FindFieldByPropertyName(attr.ThisKey) ?? row.FindField(attr.ThisKey);
                    if (ReferenceEquals(info.ThisKeyField, null))
                        throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                            "This field is specified for an ExtensionRelation attribute",
                            attr.ThisKey,
                            row.GetType().FullName));
                }

                var ext = info.RowFactory();

                var otherKey = attr.OtherKey;
                if (string.IsNullOrEmpty(otherKey))
                {
                    info.OtherKeyField = ext.FindField(info.ThisKeyField.Name);

                    if (ReferenceEquals(info.OtherKeyField, null) && ext is IIdRow)
                        info.OtherKeyField = (Field)(((IIdRow)row).IdField);

                    if (ReferenceEquals(info.OtherKeyField, null))
                        throw new ArgumentException(String.Format(
                            "Row type '{1}' has an ExtensionRelation attribute " +
                            "but its OtherKey is not specified!",
                                row.GetType().FullName));
                }
                else
                {
                    info.OtherKeyField = ext.FindFieldByPropertyName(attr.OtherKey) ?? ext.FindField(attr.OtherKey);
                    if (ReferenceEquals(info.OtherKeyField, null))
                        throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                            "This field is specified for an ExtensionRelation attribute on '{2}'",
                            attr.OtherKey,
                            ext.GetType().FullName,
                            row.GetType().FullName));
                }

                if (!string.IsNullOrEmpty(attr.FilterField))
                {
                    info.FilterField = ext.FindFieldByPropertyName(attr.FilterField) ?? ext.FindField(attr.FilterField);
                    if (ReferenceEquals(info.FilterField, null))
                        throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                            "This field is specified as FilterField for an ExtensionRelation attribute on '{2}'",
                            attr.OtherKey,
                            ext.GetType().FullName,
                            row.GetType().FullName));

                    info.FilterValue = info.FilterField.ConvertValue(attr.FilterValue, CultureInfo.InvariantCulture);
                }

                if (!string.IsNullOrEmpty(attr.PresenceField))
                {
                    info.PresenceField = ext.FindFieldByPropertyName(attr.PresenceField) ?? ext.FindField(attr.PresenceField);
                    if (ReferenceEquals(info.PresenceField, null))
                        throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                            "This field is specified as PresenceField as an ExtensionRelation attribute.",
                            attr.PresenceField,
                            row.GetType().FullName));

                    info.PresenceValue = attr.PresenceValue;
                }

                var extFields = ext.GetFields();
                var alias = attr.Alias;
                var aliasPrefix = attr.Alias + "_";

                var joinByKey = new HashSet<string>(extFields.Joins.Keys, StringComparer.OrdinalIgnoreCase);

                Func<string, string> mapAlias = x =>
                {
                    if (x == "t0" || x == "T0")
                        return alias;

                    if (!joinByKey.Contains(x))
                        return x;

                    return aliasPrefix + x;
                };

                Func<string, string> mapExpression = x =>
                {
                    if (x == null)
                        return null;

                    return JoinAliasLocator.ReplaceAliases(x, mapAlias);
                };

                info.Mappings = new List<Tuple<Field, Field>>();
                foreach (var field in extFields)
                {
                    if (ReferenceEquals(info.OtherKeyField, field))
                        continue;

                    if (ReferenceEquals(info.FilterField, field))
                        continue;

                    var expression = field.Expression.TrimToEmpty();

                    if (string.IsNullOrEmpty(expression))
                        continue;

                    expression = mapExpression(expression);
                    expression = BracketLocator.ReplaceBrackets(expression, 
                        BracketRemoverDialect.Instance);

                    var match = sourceByExpression[expression].FirstOrDefault();
                    if (ReferenceEquals(null, match))
                        continue;

                    if (match.IsTableField())
                        continue;

                    if (ReferenceEquals(info.ThisKeyField, match))
                        continue;

                    if (field.GetType() != match.GetType())
                        throw new ArgumentException(String.Format(
                            "Row type '{0}' has an ExtensionRelation attribute to '{1}'." +
                            "Their '{2}' and '{3}' fields are matched but they have different types ({4} and {5})!",
                                row.GetType().FullName,
                                ext.GetType().FullName,
                                field.PropertyName ?? field.Name,
                                match.PropertyName ?? match.Name,
                                field.GetType().Name,
                                match.GetType().Name));

                    info.Mappings.Add(new Tuple<Field, Field>(match, field));
                }

                if (info.Mappings.Count == 0)
                    throw new ArgumentException(String.Format(
                        "Row type '{0}' has an ExtensionRelation attribute " +
                        "but no view fields could be matched to extension row '{1}'!",
                            row.GetType().FullName,
                            ext.GetType().FullName));

                return info;
            }).ToList();

            return true;
        }
        internal static Dictionary<string, Field> ParseReplaceFields(string fileNameFormat, Row row, Field target)
        {
            if (fileNameFormat.IndexOf('|') < 0)
                return null;

            var replaceFields = new Dictionary<string, Field>();

            int start = 0;
            while ((start = fileNameFormat.IndexOf('|', start)) >= 0)
            {
                var end = fileNameFormat.IndexOf('|', start + 1);
                if (end <= start + 1)
                    throw new ArgumentException(String.Format(
                        "Field '{0}' on row type '{1}' has a UploadEditor attribute " +
                        "with invalid format string '{2}'!",
                            target.PropertyName ?? target.Name,
                            row.GetType().FullName,
                            fileNameFormat));

                var fieldName = fileNameFormat.Substring(start + 1, end - start - 1);
                var actualName = fieldName;
                var colon = fieldName.IndexOf(":");
                if (colon >= 0)
                    actualName = fieldName.Substring(0, colon);

                var replaceField = row.FindFieldByPropertyName(actualName) ??
                    row.FindField(actualName);

                if (ReferenceEquals(null, replaceField))
                {
                    throw new ArgumentException(String.Format(
                        "Field '{0}' on row type '{1}' has a UploadEditor attribute that " +
                        "references field '{2}', but no such field is found!'",
                            target.PropertyName ?? target.Name,
                            row.GetType().FullName,
                            actualName));
                }

                replaceFields['|' + fieldName + '|'] = replaceField;

                start = end + 1;
            }

            return replaceFields;
        }