Наследование: IFieldWithJoinInfo
        private static string AutoDetermineIdField(Field basedOnField)
        {
            if (ReferenceEquals(null, basedOnField))
                return null;

            Field idField;

            if (basedOnField.Join == null && (basedOnField.ReferencedAliases == null || basedOnField.ReferencedAliases.Count != 1))
                return null;

            if (basedOnField.Join == null)
            {
                idField = basedOnField.Fields.FirstOrDefault(x => x.ForeignJoinAlias != null &&
                    (x.TextualField == basedOnField.PropertyName ||
                     x.TextualField == basedOnField.Name));
            }
            else
            {
                var joinName = basedOnField.Join != null ? basedOnField.Join.Name : basedOnField.ReferencedAliases.Single();
                idField = basedOnField.Fields.FirstOrDefault(x => x.ForeignJoinAlias != null &&
                    x.ForeignJoinAlias.Name == joinName);
            }

            return ReferenceEquals(null, idField) ? null : (idField.PropertyName ?? idField.Name);
        }
Пример #2
0
        protected AuditSaveRequest GetAuditSaveRequest(ISaveRequestHandler handler)
        {
            var auditFields = new HashSet<Field>();
            var flag = handler.IsCreate ? FieldFlags.Insertable : FieldFlags.Updatable;
            foreach (var field in handler.Row.GetFields())
                if (field.Flags.HasFlag(flag))
                    auditFields.Add(field);

            Field[] array = new Field[auditFields.Count];
            auditFields.CopyTo(array);

            var auditRequest = new AuditSaveRequest(handler.Row.Table, (IIdRow)handler.Old, (IIdRow)handler.Row, array);

            var parentIdRow = handler.Row as IParentIdRow;
            if (parentIdRow != null)
            {
                var parentIdField = (Field)parentIdRow.ParentIdField;

                if (!parentIdField.ForeignTable.IsTrimmedEmpty())
                {
                    auditRequest.ParentTypeId = parentIdField.ForeignTable;
                    auditRequest.OldParentId = handler.IsCreate ? null : parentIdRow.ParentIdField[handler.Old];
                    auditRequest.NewParentId = parentIdRow.ParentIdField[handler.Row];
                }
            }

            return auditRequest;
        }
        private static int AutoWidth(Field field)
        {
            var name = field.Name;

            switch (field.Type)
            {
                case FieldType.String:
                    if (field.Size != 0 && field.Size <= 25)
                        return Math.Max(field.Size * 6, 150);
                    else if (field.Size == 0)
                        return 250;
                    else
                        return 150;
                case FieldType.Boolean:
                    return 40;
                case FieldType.DateTime:
                    return 85;
                case FieldType.Time:
                    return 70;
                case FieldType.Int16:
                    return 55;
                case FieldType.Int32:
                    return 65;
                case FieldType.Single:
                case FieldType.Double:
                case FieldType.Decimal:
                    return 85;
                default:
                    return 80;
            }
        }
        private bool ShouldConvertValues(BinaryCriteria criteria, out Field field, out object value)
        {
            field = null;
            value = null;

            if (ReferenceEquals(null, criteria) ||
                criteria.Operator < CriteriaOperator.EQ ||
                criteria.Operator > CriteriaOperator.NotIn)
                return false;

            var left = criteria.LeftOperand as Criteria;
            if (ReferenceEquals(null, left))
                return false;

            field = FindField(left.Expression);
            if (ReferenceEquals(null, field))
                return false;

            if (field is StringField)
                return false;

            var right = criteria.RightOperand as ValueCriteria;
            if (ReferenceEquals(null, right))
                return false;

            value = right.Value;
            return value != null;
        }
Пример #5
0
        public static GetNextNumberResponse GetNextNumber(IDbConnection connection, GetNextNumberRequest request,
            Field field)
        {
            var prefix = request.Prefix ?? "";

            var max = connection.Query<string>(new SqlQuery()
                .From(field.Fields)
                .Select(Sql.Max(field.Expression))
                .Where(
                    field.StartsWith(prefix) &&
                    field >= prefix.PadRight(request.Length, '0') &&
                    field <= prefix.PadRight(request.Length, '9')))
                .FirstOrDefault();

            var response = new GetNextNumberResponse();

            long l;
            response.Number = max == null ||
                !long.TryParse(max.Substring(prefix.Length), out l) ? 1 : l + 1;

            response.Serial = prefix + response.Number.ToString()
                .PadLeft(request.Length - prefix.Length, '0');

            return response;
        }
        protected virtual bool CanFilterField(Field field)
        {
            if (field.Flags.HasFlag(FieldFlags.DenyFiltering))
                return false;

            if (field.MinSelectLevel == SelectLevel.Never)
                return false;

            return true;
        }
        public bool ActivateFor(Row row)
        {
            if (ReferenceEquals(null, Target))
                return false;

            attr = Target.GetAttribute<MasterDetailRelationAttribute>();
            if (attr == null)
                return false;

            var rowListType = Target.ValueType;
            if (!rowListType.IsGenericType ||
                rowListType.GetGenericTypeDefinition() != typeof(List<>))
            {
                throw new ArgumentException(String.Format("Field '{0}' in row type '{1}' has a MasterDetailRelationAttribute " +
                    "but its property type is not a generic List (e.g. List<Row>)!",
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            var rowType = rowListType.GetGenericArguments()[0];
            if (rowType.IsAbstract ||
                !typeof(Row).IsAssignableFrom(rowType))
            {
                throw new ArgumentException(String.Format(
                    "Field '{0}' in row type '{1}' has a MasterDetailRelationAttribute " +
                    "but its property type is not a generic list of rows (e.g. List<Row>)!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            rowListFactory = FastReflection.DelegateForConstructor<IList>(rowListType);
            rowFactory = FastReflection.DelegateForConstructor<Row>(rowType);

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

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

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

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

            var detailRow = rowFactory();
            foreignKeyField = detailRow.FindFieldByPropertyName(attr.ForeignKey) ??
                detailRow.FindField(attr.ForeignKey);

            if (ReferenceEquals(foreignKeyField, null))
                throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                    "This field is specified for a master detail relation in field '{2}' of row type '{3}'.",
                    attr.ForeignKey, detailRow.GetType().FullName,
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));

            return true;
        }
Пример #8
0
        public static ReportColumn FromField(Field field)
        {
            var column = new ReportColumn();
            column.Name = field.Name;
            column.Title = field.Title;

            if (field is StringField)
                if (field.Size != 0)
                    column.Width = field.Size;

            return column;
        }
Пример #9
0
        public AuditSaveRequest(EntityType entityType, IIdRow oldEntity, IIdRow newEntity, Field[] auditFields)
        {
            if (newEntity == null)
                throw new ArgumentNullException("newEntity");

            if (auditFields == null)
                throw new ArgumentNullException("auditFields");

            EntityType = entityType;
            OldEntity = oldEntity;
            NewEntity = newEntity;
            AuditFields = auditFields;
        }
Пример #10
0
        private ReportColumn FromPropertyItem(PropertyItem item, Field field)
        {
            var result = new ReportColumn();
            result.Name = item.Name;
            result.Title = item.Title ?? item.Name;
            if (result.Title != null)
                result.Title = LocalText.TryGet(result.Title) ?? result.Title;

            if (item.Width != null)
                result.Width = item.Width;

            if (!string.IsNullOrWhiteSpace(item.DisplayFormat))
                result.Format = item.DisplayFormat;
            else
            {
                var dtf = field as DateTimeField;
                if (!ReferenceEquals(null, dtf) &&
                    dtf.DateTimeKind != DateTimeKind.Unspecified)
                {
                    result.Format = "dd/MM/yyyy HH:mm";
                }
                else if (!ReferenceEquals(null, dtf))
                {
                    result.Format = "dd/MM/yyyy";
                }
            }

            var enumField = field as IEnumTypeField;
            if (enumField != null && enumField.EnumType != null)
            {
                result.Decorator = new EnumDecorator(enumField.EnumType);
            }

            if (!ReferenceEquals(null, field))
            {
                if (result.Title == null)
                    result.Title = field.Title;

                if (result.Width == null && field is StringField && field.Size != 0)
                    result.Width = field.Size;
            }

            result.DataType = !ReferenceEquals(null, field) ? field.ValueType : null;

            return result;
        }
Пример #11
0
        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;
        }
Пример #12
0
        internal void RaisePropertyChanged(Field field)
        {
            if (fields.propertyChangedEventArgs == null)
            {
                var args = new PropertyChangedEventArgs[fields.Count + 1];
                for (var i = 0; i < fields.Count; i++)
                {
                    var f = fields[i];
                    args[i] = new PropertyChangedEventArgs(f.propertyName ?? f.Name);
                }
                args[fields.Count] = new PropertyChangedEventArgs("__ROW__");
                fields.propertyChangedEventArgs = args;
            }

            if (ReferenceEquals(null, field))
                propertyChanged(this, fields.propertyChangedEventArgs[fields.Count]);
            else
                propertyChanged(this, fields.propertyChangedEventArgs[field.Index]);
        }
Пример #13
0
        /// <summary>
        ///   Gets the next display order value for a table or a group of records.</summary>
        /// <param name="connection">
        ///   Connection (required).</param>
        /// <param name="tableName">
        ///   Table name (required).</param>
        /// <param name="orderField">
        ///   Display order field meta (required).</param>
        /// <param name="filter">
        ///   Filter for records (can be null).</param>
        /// <returns>
        ///   One more of maximum display order values of records in the group. 
        ///   If none, 1.</returns>
        public static int GetNextValue(IDbConnection connection, string tableName, 
            Field orderField, ICriteria filter)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            if (tableName == null || tableName.Length == 0)
                throw new ArgumentNullException("tableName");
            if (ReferenceEquals(null, orderField))
                throw new ArgumentNullException("orderField");

            using (IDataReader reader = SqlHelper.ExecuteReader(connection,
                new SqlQuery().Select(
                    Sql.Max(orderField.Name))
                .From(
                    tableName, Alias.T0)
                .Where(
                    filter)))
            {
                if (reader.Read() && !reader.IsDBNull(0))
                    return Convert.ToInt32(reader.GetValue(0)) + 1;
                else
                    return 1;
            }
        }
Пример #14
0
 internal FieldDescriptor(Field field)
     : base(field.PropertyName ?? field.Name, null)
 {
     _field = field;
 }
Пример #15
0
        public static bool UpdateOrders(IDbConnection connection, List<OrderRecord> orderRecords, 
            string tableName, Field keyField, Field orderField, bool hasUniqueConstraint = false)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            if (tableName.IsEmptyOrNull())
                throw new ArgumentNullException("tableName");

            if (ReferenceEquals(null, keyField))
                throw new ArgumentNullException("keyField");

            if (ReferenceEquals(null, orderField))
                throw new ArgumentNullException("orderField");

            // StringBuilder that will contain query(s)
            StringBuilder queries = new StringBuilder();

            if (connection.GetDialect().NeedsExecuteBlockStatement)
            {
                queries.AppendLine("EXECUTE BLOCK AS");
                queries.AppendLine("BEGIN");
            }

            int updateCount = 0;

            Action<long, long> appendSingleUpdate = delegate(long id, long newOrder)
            {
                queries.AppendLine(String.Format(
                    "UPDATE {0} SET {1} = {2} WHERE {3} = {4};", tableName,
                    orderField.Name, newOrder, keyField.Name, id));
                updateCount++;
            };

            if (hasUniqueConstraint)
            {
                var byCurrentOrder = new Dictionary<Int64, OrderRecord>();
                foreach (var rec in orderRecords)
                    byCurrentOrder[rec.oldOrder] = rec;

                var list = new List<OrderRecord>();
                list.AddRange(orderRecords);
                list.Sort((x, y) => (x.newOrder - y.newOrder));

                foreach (var rec in list)
                {
                    if (rec.oldOrder != rec.newOrder)
                    {
                        byCurrentOrder.Remove(rec.oldOrder);

                        OrderRecord congestion;
                        if (byCurrentOrder.TryGetValue(rec.newOrder, out congestion))
                        {
                            var empty = list.Count * 2;
                            while (byCurrentOrder.ContainsKey(empty))
                                empty++;

                            congestion.oldOrder = empty;
                            appendSingleUpdate(congestion.recordID, empty);
                            byCurrentOrder[empty] = congestion;
                        }

                        appendSingleUpdate(rec.recordID, rec.newOrder);
                        byCurrentOrder[rec.newOrder] = rec;
                    }
                }
            }
            else
            {
                // StringBuilder that will contain IN(...) part of the latest query
                StringBuilder sb = new StringBuilder();

                // scan all display order changing records
                int start = 0;
                while (start < orderRecords.Count)
                {
                    OrderRecord rs = orderRecords[start];

                    // if this records display order is not changed, skip it
                    if (rs.oldOrder == rs.newOrder)
                    {
                        start++;
                        continue;
                    }

                    // find the difference between old and new display orders
                    int difference = rs.oldOrder - rs.newOrder;

                    // clear the IN(...) list
                    sb.Length = 0;

                    // add this records ID to the IN (...) part
                    sb.Append(rs.recordID);

                    // now we'll find all following records whose display orders are changed same amount
                    // (difference between old and new is same), so we will update them with just one query
                    // like UPDATE ORDER = ORDER + 1 WHERE ID IN (X, Y, Z....).
                    int finish = start;

                    while (finish + 1 < orderRecords.Count)
                    {
                        // if we found more than 100 records whose display orders changed same amount, to
                        // limit IN(...) part to overgrow, break searching and run the query. Collect the
                        // rest in another query. If query is too complex, might result in performance
                        // degration in SQL server
                        if (finish - start >= 100)
                            break;

                        OrderRecord rf = orderRecords[finish + 1];

                        // is this records display order value changed same amount
                        if (rf.oldOrder - rf.newOrder != difference)
                            break;

                        sb.Append(',');
                        sb.Append(rf.recordID);

                        finish++;
                    }

                    // if only one record in batch, no need to use IN clause
                    if (start == finish)
                    {
                        queries.AppendLine(String.Format(
                            "UPDATE {0} SET {1} = {2} WHERE {3} = {4};", tableName,
                            orderField.Name, rs.newOrder, keyField.Name, rs.recordID));
                        updateCount++;
                    }
                    else
                    {
                        // batch update, use IN (...)
                        OrderRecord rf = orderRecords[finish];

                        queries.AppendLine(String.Format(
                            "UPDATE {0} SET {1} = {1} - ({2}) WHERE ({3} IN ({4}));",
                            tableName,
                            orderField.Name,
                            rs.oldOrder - rs.newOrder,
                            keyField.Name,
                            sb.ToString()));
                        updateCount++;
                    }

                    start = finish + 1;
                }
            }

            if (queries.Length > 0 && updateCount > 0)
            {
                if (connection.GetDialect().NeedsExecuteBlockStatement)
                    queries.AppendLine("END;");

                SqlHelper.ExecuteNonQuery(connection, queries.ToString());
                // one ore more records has changed display order values

                return true;
            }
            else
            {
                // nothing changed, all display orders are same
                return false;
            }
        }
Пример #16
0
 public static ReportColumn FromFieldInfo(FieldInfo field, Field baseField = null)
 {
     return FromMember(field, field.FieldType, baseField);
 }
Пример #17
0
 public static ReportColumn FromPropertyInfo(PropertyInfo property, Field baseField = null)
 {
     return FromMember(property, property.PropertyType, baseField);
 }
Пример #18
0
        private static ReportColumn FromMember(MemberInfo member, Type dataType, Field baseField)
        {
            if (member == null)
                throw new ArgumentNullException("member");

            var result = new ReportColumn();
            result.Name = member.Name;
            var displayAttr = member.GetCustomAttribute<DisplayNameAttribute>();
            if (displayAttr != null)
                result.Title = displayAttr.DisplayName;

            var sizeAttr = member.GetCustomAttribute<SizeAttribute>();
            if (sizeAttr != null && sizeAttr.Value != 0)
                result.Width = sizeAttr.Value;

            var formatAttr = member.GetCustomAttribute<DisplayFormatAttribute>();
            if (formatAttr != null)
                result.Format = formatAttr.Value;
            else
            {
                var dtf = baseField as DateTimeField;
                if (!ReferenceEquals(null, dtf) &&
                    dtf.DateTimeKind != DateTimeKind.Unspecified)
                {
                    result.Format = "dd/MM/yyyy HH:mm";
                }
                else if (!ReferenceEquals(null, dtf) ||
                         dataType == typeof (DateTime) ||
                         dataType == typeof (DateTime?))
                {
                    result.Format = "dd/MM/yyyy";
                }
            }

            if (!ReferenceEquals(null, baseField))
            {
                if (result.Title == null)
                    result.Title = baseField.Title;

                if (result.Width == null && baseField is StringField && baseField.Size != 0)
                    result.Width = baseField.Size;
            }

            result.DataType = dataType;

            return result;
        }
Пример #19
0
        public static Type GetEnumType(Field field)
        {
            var fint32 = field as IEnumTypeField;
            if (fint32 != null &&
                fint32.EnumType != null &&
                fint32.EnumType.GetIsEnum())
            {
                return fint32.EnumType;
            }

            return null;
        }
        public static PropertyItem GetCustomFieldPropertyItem(ICustomFieldDefinition definition, Field basedOnField)
        {
            PropertyItem pi = new PropertyItem();
            pi.Name = !ReferenceEquals(null, basedOnField) ? (basedOnField.PropertyName ?? basedOnField.Name) : definition.Name;
            pi.Category = definition.Category.TrimToNull();
            pi.ReadOnly = false;
            pi.Title = !ReferenceEquals(null, basedOnField) ? basedOnField.Title : definition.Title;
            pi.DefaultValue = definition.DefaultValue;
            pi.Insertable = ReferenceEquals(null, basedOnField) || ((basedOnField.Flags & FieldFlags.Insertable) == FieldFlags.Insertable);
            pi.Updatable = ReferenceEquals(null, basedOnField) || ((basedOnField.Flags & FieldFlags.Updatable) == FieldFlags.Updatable);
            pi.Localizable = definition.IsLocalizable;

            Type enumType = null;
            if (!ReferenceEquals(null, basedOnField) && basedOnField is IEnumTypeField)
            {
                enumType = (basedOnField as IEnumTypeField).EnumType;
                if (enumType != null && !enumType.IsEnum)
                    enumType = null;
            }

            if (!definition.EditorType.IsTrimmedEmpty())
            {
                pi.EditorType = definition.EditorType.TrimToNull();
            }
            else
            {
                if (enumType != null)
                    pi.EditorType = "Enum";
                else if (definition.FieldType == CustomFieldType.Date ||
                    definition.FieldType == CustomFieldType.DateTime)
                    pi.EditorType = "Date";
                else if (definition.FieldType == CustomFieldType.Boolean)
                    pi.EditorType = "Boolean";
                else if (definition.FieldType == CustomFieldType.Decimal)
                    pi.EditorType = "Decimal";
                else if (definition.FieldType == CustomFieldType.Int32 || definition.FieldType == CustomFieldType.Int64)
                    pi.EditorType = "Integer";
                else
                    pi.EditorType = "String";
            }

            if (enumType != null)
            {
                pi.EditorParams["enumKey"] = EnumMapper.GetEnumTypeKey(enumType);
            }

            if (!ReferenceEquals(null, basedOnField))
            {
                if (basedOnField is StringField &&
                    basedOnField.Size > 0)
                {
                    pi.EditorParams["maxLength"] = basedOnField.Size;
                    pi.MaxLength = basedOnField.Size;
                }

                if ((basedOnField.Flags & FieldFlags.NotNull) == FieldFlags.NotNull)
                    pi.Required = true;
            }

            if (definition.IsRequired)
                pi.Required = true;

            if (definition.Size != 0 &&
                definition.FieldType == CustomFieldType.String)
            {
                pi.MaxLength = definition.Size;
                pi.EditorParams["maxLength"] = definition.Size;
            }

            var editorOptionsJson = definition.EditorOptions.TrimToNull();
            if (editorOptionsJson != null &&
                editorOptionsJson.StartsWith("{"))
            {
                var editorOptions = JsonConvert.DeserializeObject<Dictionary<string, object>>(editorOptionsJson, JsonSettings.Tolerant);
                foreach (var option in editorOptions)
                    pi.EditorParams[option.Key] = option.Value;
            }

            return pi;
        }
Пример #21
0
        /// <summary>
        ///   Sets a records display order to to requested value, and also renumbers other records
        ///   in the group as required.</summary>
        /// <param name="connection">
        ///   Connection (required).</param>
        /// <param name="tableName">
        ///   Tablename (required).</param>
        /// <param name="keyField">
        ///   ID field meta that will be used to locate the record (required).</param>
        /// <param name="orderField">
        ///   Display order field meta.</param>
        /// <param name="filter">
        ///   Filter that will determine the record group (can be null).</param>
        /// <param name="recordID">
        ///   ID value of the record.</param>
        /// <param name="newDisplayOrder">
        ///   New display order of the record.</param>
        /// <param name="descendingKeyOrder">
        ///   Will records with same display order values be sorted in ascending or descending ID order?
        ///   For example, if records with ID's 1, 2, 3 has display order value of "0", their actual display
        ///   orders are 1, 2 and 3. If this parameter is set to true (descending), their display orders will
        ///   become 3, 2, 1. This parameter controls if records that are added recently and has no display
        ///   order value assigned (or 0) be shown at start or at the end.</param>
        /// <returns>
        ///   If any of the display order values is changed true.</returns>
        public static bool ReorderValues(IDbConnection connection, string tableName, Field keyField, Field orderField,
            ICriteria filter = null, Int64? recordID = null, int newDisplayOrder = 1,
            bool descendingKeyOrder = false, bool hasUniqueConstraint = false)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            if (tableName == null || tableName.Length == 0)
                throw new ArgumentNullException("tableName");
            if (ReferenceEquals(null, keyField))
                throw new ArgumentNullException("keyField");
            if (ReferenceEquals(null, orderField))
                throw new ArgumentNullException("orderField");

            // last assigned display order value
            int order = 0;

            // a list that will contain an element for each record, and hold old and new display
            // order values of records
            List<OrderRecord> orderRecords = new List<OrderRecord>();

            // link to the order entry for record whose display order value is asked to be changed
            OrderRecord changing = null;

            // query to fetch id and display order values of the records in the group
            SqlQuery query = new SqlQuery()
                .Select(
                    keyField,
                    orderField)
                .From(
                    tableName, Alias.T0)
                .Where(
                    filter)
                .OrderBy(
                    orderField);

            // determine display order for records with same display order values
            // based on ID ordering set
            query.OrderBy(keyField.Name, desc : descendingKeyOrder);

            // read all existing records
            using (IDataReader reader = SqlHelper.ExecuteReader(connection, query))
            {
                while (reader.Read())
                {
                    // each records actual display order value is one more than previous one
                    order++;
                    // create an entry to hold current and new display order value of the record
                    OrderRecord r = new OrderRecord();
                    // record ID
                    r.recordID = Convert.ToInt64(reader.GetValue(0));
                    // old display order field value (not the actual display order!)
                    r.oldOrder = Convert.ToInt32(reader.GetValue(1));
                    // new display order value (actual one to be set)
                    r.newOrder = order;

                    orderRecords.Add(r);

                    // if this is the one that is requested to be changed, hold a link to its entry
                    if (recordID == r.recordID)
                        changing = r;
                }
            }

            // ensure that the new display order is within limits
            // if its lower than 1 or bigger than record count, fix it
            if (newDisplayOrder <= 0)
                newDisplayOrder = 1;
            else if (newDisplayOrder > order)
                newDisplayOrder = order;

            // if the record whose display order is to be changed can be found, and its display order value is different
            // than the one in database
            if (changing != null && changing.newOrder != newDisplayOrder)
            {
                // let's say record had a display order value of 6and now it will become 10, the records with actual
                // display orders of 7, 8, 9, 10 will become 6, 7, 8, 9 orders.
                //
                // WARNING: notice that array is 0 based, so record with actual display order of 7 is in the
                // 6th index in the array)
                for (int i = changing.newOrder; i < newDisplayOrder; i++)
                    orderRecords[i].newOrder = i;

                // if the records display order is to be changed from 9 to 5, the records with actual orders of 5, 6, 7, 8
                // is going to be 6, 7, 8, 9 ordered.
                for (int i = newDisplayOrder - 1; i < changing.newOrder - 1; i++)
                    orderRecords[i].newOrder = i + 2;

                // as the records that will be changing are assigned new orders, we may assign new display order
                // directly.
                changing.newOrder = newDisplayOrder;
            }

            return UpdateOrders(connection, orderRecords, tableName, keyField, orderField, hasUniqueConstraint);
        }
Пример #22
0
 public bool IsFieldChanged(Field field)
 {
     return (originalValues != null &&
             field.IndexCompare(originalValues, this) != 0);
 }
        public bool ActivateFor(Row row)
        {
            if (ReferenceEquals(null, Target))
                return false;

            attr = Target.GetAttribute<LinkingSetRelationAttribute>();
            if (attr == null)
                return false;

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


            var listType = Target.ValueType;
            if (!listType.GetIsGenericType() ||
                listType.GetGenericTypeDefinition() != typeof(List<>))
            {
                throw new ArgumentException(String.Format("Field '{0}' in row type '{1}' has a LinkingSetRelationBehavior " +
                    "but its property type is not a generic List (e.g. List<int>)!",
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            var rowType = attr.RowType;
            if (rowType.GetIsAbstract() ||
                !typeof(Row).IsAssignableFrom(rowType))
            {
                throw new ArgumentException(String.Format(
                    "Field '{0}' in row type '{1}' has a LinkingSetRelationBehavior " +
                    "but specified row type is not valid row class!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            if (!typeof(IIdRow).IsAssignableFrom(rowType))
            {
                throw new ArgumentException(String.Format(
                    "Field '{0}' in row type '{1}' has a LinkingSetRelationBehavior " +
                    "but specified row type doesn't implement IIdRow!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            listFactory = FastReflection.DelegateForConstructor<IList>(listType);
            rowFactory = FastReflection.DelegateForConstructor<Row>(rowType);

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

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

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

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

            var detailRow = rowFactory();

            thisKeyField = detailRow.FindFieldByPropertyName(attr.ThisKey) ??
                detailRow.FindField(attr.ThisKey);

            if (ReferenceEquals(thisKeyField, null))
                throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                    "This field is specified for a linking set relation in field '{2}' of row type '{3}'.",
                    attr.ThisKey, detailRow.GetType().FullName,
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));

            this.thisKeyCriteria = new Criteria(thisKeyField.PropertyName ?? thisKeyField.Name);

            itemKeyField = detailRow.FindFieldByPropertyName(attr.ItemKey) ??
                detailRow.FindField(attr.ItemKey);

            if (ReferenceEquals(itemKeyField, null))
                throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                    "This field is specified for a linking set relation in field '{2}' of row type '{3}'.",
                    attr.ItemKey, detailRow.GetType().FullName,
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));

            if (!string.IsNullOrEmpty(attr.FilterField))
            {
                this.filterField = detailRow.FindFieldByPropertyName(attr.FilterField) ?? detailRow.FindField(attr.FilterField);
                if (ReferenceEquals(null, this.filterField))
                    throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                        "This field is specified for a linking set relation as FilterField in field '{2}' of row type '{3}'.",
                        attr.FilterField, detailRow.GetType().FullName,
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));

                this.filterCriteria = new Criteria(filterField.PropertyName ?? filterField.Name);
                this.filterValue = filterField.ConvertValue(attr.FilterValue, CultureInfo.InvariantCulture);
                if (this.filterValue == null)
                {
                    this.filterCriteria = this.filterCriteria.IsNull();
                    this.filterCriteriaT0 = this.filterField.IsNull();
                }
                else
                {
                    this.filterCriteria = this.filterCriteria == new ValueCriteria(this.filterValue);
                    this.filterCriteriaT0 = this.filterField == new ValueCriteria(this.filterValue);
                }
            }

            return true;
        }
        public bool ActivateFor(Row row)
        {
            if (ReferenceEquals(null, Target))
                return false;

            attr = Target.GetAttribute<MasterDetailRelationAttribute>();
            if (attr == null)
                return false;

            var rowListType = Target.ValueType;
            if (!rowListType.GetIsGenericType() ||
                rowListType.GetGenericTypeDefinition() != typeof(List<>))
            {
                throw new ArgumentException(String.Format("Field '{0}' in row type '{1}' has a MasterDetailRelationAttribute " +
                    "but its property type is not a generic List (e.g. List<Row>)!",
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            var rowType = rowListType.GetGenericArguments()[0];
            if (rowType.GetIsAbstract() ||
                !typeof(Row).IsAssignableFrom(rowType))
            {
                throw new ArgumentException(String.Format(
                    "Field '{0}' in row type '{1}' has a MasterDetailRelationAttribute " +
                    "but its property type is not a generic list of rows (e.g. List<Row>)!",
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            rowListFactory = FastReflection.DelegateForConstructor<IList>(rowListType);
            rowFactory = FastReflection.DelegateForConstructor<Row>(rowType);

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

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

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

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

            var detailRow = rowFactory();
            foreignKeyField = detailRow.FindFieldByPropertyName(attr.ForeignKey) ??
                detailRow.FindField(attr.ForeignKey);

            if (ReferenceEquals(foreignKeyField, null))
                throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                    "This field is specified for a master detail relation in field '{2}' of row type '{3}'.",
                    attr.ForeignKey, detailRow.GetType().FullName,
                    Target.PropertyName ?? Target.Name, row.GetType().FullName));

            this.foreignKeyCriteria = new Criteria(foreignKeyField.PropertyName ?? foreignKeyField.Name);

            if (!string.IsNullOrEmpty(attr.FilterField))
            {
                this.filterField = detailRow.FindFieldByPropertyName(attr.FilterField) ?? detailRow.FindField(attr.FilterField);
                if (ReferenceEquals(null, this.filterField))
                    throw new ArgumentException(String.Format("Field '{0}' doesn't exist in row of type '{1}'." +
                        "This field is specified for a master detail relation as FilterField in field '{2}' of row type '{3}'.",
                        attr.FilterField, detailRow.GetType().FullName,
                        Target.PropertyName ?? Target.Name, row.GetType().FullName));

                this.filterCriteria = new Criteria(filterField.PropertyName ?? filterField.Name);
                this.filterValue = filterField.ConvertValue(attr.FilterValue, CultureInfo.InvariantCulture);
                if (this.filterValue == null)
                {
                    this.filterCriteria = this.filterCriteria.IsNull();
                    this.filterCriteriaT0 = this.filterField.IsNull();
                }
                else
                {
                    this.filterCriteria = this.filterCriteria == new ValueCriteria(this.filterValue);
                    this.filterCriteriaT0 = this.filterField == new ValueCriteria(this.filterValue);
                }
            }

            this.includeColumns = new HashSet<string>();

            if (!string.IsNullOrEmpty(attr.IncludeColumns))
                foreach (var s in attr.IncludeColumns.Split(','))
                {
                    var col = s.TrimToNull();
                    if (col != null)
                        this.includeColumns.Add(col);
                }

            return true;
        }
Пример #25
0
        internal void FieldAssignedValue(Field field)
        {
            if (assignedFields == null)
                assignedFields = new bool[fields.Count];

            assignedFields[field.index] = true;

            if (validationErrors != null)
                RemoveValidationError(field.PropertyName ?? field.Name);

            if (propertyChanged != null)
            {
                if (field.IndexCompare(previousValues, this) != 0)
                {
                    RaisePropertyChanged(field);
                    field.Copy(this, previousValues);
                }
            }
        }
Пример #26
0
        public bool IsAssigned(Field field)
        {
            if (assignedFields == null)
                return false;

            return assignedFields[field.index];
        }
Пример #27
0
        public void ClearAssignment(Field field)
        {
            if (assignedFields == null)
                return;

            assignedFields[field.index] = false;

            for (var i = 0; i < assignedFields.Length; i++)
                if (assignedFields[i])
                    return;

            assignedFields = null;
        }
Пример #28
0
        public static void PopulateSheet(ExcelWorksheet worksheet, List<ReportColumn> columns, IList rows,
            string tableName = "Table1", TableStyles tableStyle = TableStyles.Medium2)
        {
            if (columns == null)
                throw new ArgumentNullException("columns");

            if (rows == null)
                throw new ArgumentNullException("rows");

            Field[] fields = null;
            TypeAccessor accessor = null;

            var colCount = columns.Count;

            int endCol = colCount;
            int endRow = rows.Count + 1;

            var header = worksheet.Cells[1, 1, 1, columns.Count];
            header.LoadFromArrays(new List<object[]>
            {
                columns.ConvertAll(x => (x.Title ?? x.Name)).ToArray()
            });

            var dataList = new List<object[]>();
            foreach (var obj in rows)
            {
                var data = new object[colCount];
                var row = obj as Row;
                if (row != null)
                {
                    if (fields == null)
                    {
                        fields = new Field[colCount];
                        for (var i = 0; i < columns.Count; i++)
                        {
                            var n = columns[i].Name;
                            fields[i] = row.FindFieldByPropertyName(n) ?? row.FindField(n);
                        }
                    }
                }
                else if (obj != null)
                {
                    if (accessor == null)
                        accessor = TypeAccessor.Create(obj.GetType());
                }

                for (var c = 0; c < colCount; c++)
                {
                    if (row != null)
                    {
                        data[c] = fields[c].AsObject(row);
                    }
                    else if (obj != null)
                    {
                        data[c] = accessor[obj, columns[c].Name];
                    }
                }

                dataList.Add(data);
            }

            if (rows.Count > 0)
            {
                var dataRange = worksheet.Cells[2, 1, endRow, endCol];
                dataRange.LoadFromArrays(dataList);
            }

            var tableRange = worksheet.Cells[1, 1, endRow, endCol];
            var table = worksheet.Tables.Add(tableRange, tableName);
            table.TableStyle = tableStyle;

            for (var i = 1; i <= endCol; i++)
            {
                var column = columns[i - 1];
                if (!column.Format.IsEmptyOrNull())
                    worksheet.Column(i).Style.Numberformat.Format = column.Format;
            }

            worksheet.Cells[1, 1, Math.Min(endRow, 250), endCol].AutoFitColumns(1, 100);

            for (var colNum = 1; colNum <= endCol; colNum++)
            {
                var col = columns[colNum - 1];
                var decorator = col.Decorator;
                if (decorator != null)
                {
                    for (var rowNum = 2; rowNum <= endRow; rowNum++)
                    {
                        var obj = rows[rowNum - 2];
                        var row = obj as Row;

                        decorator.Item = obj;
                        decorator.Name = col.Name;
                        decorator.Format = null;
                        decorator.Background = Color.Empty;
                        decorator.Foreground = Color.Empty;

                        object value;
                        if (row != null)
                        {
                            value = fields[colNum - 1].AsObject(row);
                        }
                        else if (obj != null)
                        {
                            value = accessor[obj, col.Name];
                        }
                        else
                            continue;

                        decorator.Value = value;
                        decorator.Decorate();

                        if (decorator.Background != Color.Empty ||
                            decorator.Foreground != Color.Empty ||
                            !Object.Equals(decorator.Value, value) ||
                            decorator.Format != null)
                        {
                            var cell = worksheet.Cells[rowNum, colNum];

                            if (decorator.Background != Color.Empty)
                            {
                                cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                                cell.Style.Fill.BackgroundColor.SetColor(decorator.Background);
                            }

                            if (decorator.Foreground != Color.Empty)
                                cell.Style.Font.Color.SetColor(decorator.Foreground);

                            if (decorator.Format != null)
                                cell.Style.Numberformat.Format = decorator.Format;

                            if (!Object.Equals(decorator.Value, value))
                                cell.Value = decorator.Value;
                        }
                    }
                }
            }
        }