123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- namespace InABox.Core
- {
- [Serializable]
- public class CoreRow : ICoreRow
- {
- #region Fields
- [NonSerialized]
- private static Dictionary<int, string> _accessedcolumns = new Dictionary<int, string>();
- [NonSerialized]
- private Dictionary<string, int> _columnindexes = new Dictionary<string, int>();
- #endregion
- #region Properties
- [DoNotSerialize]
- [field: NonSerialized]
- public CoreTable Table { get; private set; }
- public List<object?> Values { get; private set; }
- [DoNotSerialize]
- public int Index => Table.Rows.IndexOf(this);
- #endregion
- protected internal CoreRow(CoreTable owner)
- {
- Table = owner;
- Values = new List<object?>();
- }
- public static CoreRow[] None
- {
- get { return new CoreRow[] { }; }
- }
- //private DynamicObject rowObject;
- public Dictionary<string, object?> ToDictionary(string[]? exclude = null)
- {
- var result = new Dictionary<string, object?>();
-
- var columns = exclude == null
- ? Table.Columns
- : Table.Columns.Where(x => !exclude.Contains(x.ColumnName));
-
- foreach (var column in columns)
- result[column.ColumnName] = this[column.ColumnName];
- return result;
- }
- [DoNotSerialize]
- public object? this[string columnName]
- {
- get =>
- //return this.RowObject.GetValue<object>(columnName);
- Get<object>(columnName);
- set =>
- //this.RowObject.SetValue(columnName, value);
- Set(columnName, value);
- }
- /// <summary>
- /// Fill an object with the data from this row.
- /// </summary>
- /// <remarks>
- /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
- /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
- /// </remarks>
- /// <param name="t">The type of <paramref name="obj"/>.</param>
- /// <param name="obj">The object to fill.</param>
- /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
- public void FillObject(Type t, BaseObject obj, bool overrideExisting = false)
- {
- obj.SetObserving(false);
- if (!Table.Setters.TryGetValue("", out var setters))
- {
- setters = new List<Action<object, object>?>();
- Table.Setters[""] = setters;
- }
- var bFirst = !setters.Any();
- for (var i = 0; i < Table.Columns.Count; i++)
- {
- var column = Table.Columns[i].ColumnName;
- var value = this[column];
- try
- {
- if (obj.LoadedColumns.Add(column) || overrideExisting)
- {
- if (bFirst)
- {
- var prop = DatabaseSchema.Property(t, column);
- setters.Add(prop?.Setter());
- }
- var setter = setters[i];
- if (setter != null && value != null)
- setter.Invoke(obj, value);
- else
- CoreUtils.SetPropertyValue(obj, column, value);
- }
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- }
- obj.CommitChanges();
- obj.SetObserving(true);
- }
- /// <summary>
- /// Fill an object with the data from this row.
- /// </summary>
- /// <remarks>
- /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
- /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
- /// </remarks>
- /// <param name="obj">The object to fill.</param>
- /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
- public void FillObject<T>(T obj, bool overrideExisting = false) where T : BaseObject
- {
- FillObject(typeof(T), obj, overrideExisting: overrideExisting);
- }
- public BaseObject ToObject(Type t)
- {
- var entity = (Activator.CreateInstance(t) as BaseObject)!;
- FillObject(t, entity, overrideExisting: true);
- return entity;
- }
- public T ToObject<T>() where T : BaseObject, new()
- {
- return (ToObject(typeof(T)) as T)!;
- }
- public T Get<T>(int col, bool usedefault = true)
- {
- if (col < 0 || col >= Values.Count)
- {
- if (usedefault)
- return CoreUtils.GetDefault<T>();
- throw new Exception(string.Format("Column [{0}] does not exist!", col));
- }
- return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
- }
-
- public T Get<T>(string columnname, bool usedefault = true)
- {
- var col = GetColumn(columnname);
- if (col < 0 || col >= Values.Count)
- {
- if (usedefault)
- return CoreUtils.GetDefault<T>();
- throw new Exception(string.Format("Column [{0}] does not exist!", columnname));
- }
- return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
- }
- public TType Get<TSource, TType>(Expression<Func<TSource, TType>> expression, bool usedefault = true)
- {
- var colname = GetColName(expression);
- //String colname = CoreUtils.GetFullPropertyName(expression, ".");
- return Get<TType>(colname, usedefault);
- }
- public void Set<TSource, TType>(Expression<Func<TSource, TType>> expression, TType value)
- {
- var colname = GetColName(expression);
- //String colname = CoreUtils.GetFullPropertyName(expression, ".");
- Set(colname, value);
- }
- public void Set<T>(int col, T value)
- {
- while (Values.Count <= col)
- Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
- Values[col] = value;
- }
-
- public void Set<T>(string columnname, T value)
- {
- var col = GetColumn(columnname);
- if (col < 0)
- throw new Exception("Column not found: " + columnname);
- while (Values.Count <= col)
- Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
- Values[col] = value;
- //this.RowObject.SetValue(columnname, value);
- }
- public void LoadValues(IEnumerable<object?> values)
- {
- Values = values.ToList();
- }
- public T ToObject<TSource, TLink, T>(Expression<Func<TSource, TLink>> property)
- where TLink : IEntityLink<T>
- where T : BaseObject, new()
- {
- var entity = new T();
- entity.SetObserving(false);
- var prefix = CoreUtils.GetFullPropertyName(property, ".");
- if (!Table.Setters.TryGetValue(prefix, out var setters))
- {
- setters = new List<Action<object, object>?>();
- Table.Setters[prefix] = setters;
- }
- var bFirst = !setters.Any();
- var cols = Table.Columns.Where(x => x.ColumnName.StartsWith(prefix + ".")).ToArray();
- for (var i = 0; i < cols.Length; i++)
- {
- var column = cols[i].ColumnName;
- var prop = column.Substring((prefix + ".").Length);
- var value = this[column];
- try
- {
- if (bFirst)
- {
- var p2 = DatabaseSchema.Property(typeof(T), prop);
- setters.Add(p2?.Setter());
- }
- var setter = setters[i];
- if (setter != null && value != null)
- setter.Invoke(entity, value);
- else
- CoreUtils.SetPropertyValue(entity, prop, value);
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- }
- entity.CommitChanges();
- entity.SetObserving(true);
- return entity;
- }
- private string GetColName<TSource, TType>(Expression<Func<TSource, TType>> expression)
- {
- //int hash = expression.GetHashCode();
- //if (_accessedcolumns.ContainsKey(hash))
- // return _accessedcolumns[hash];
- var colname = CoreUtils.GetFullPropertyName(expression, ".");
- //_accessedcolumns[hash] = colname;
- return colname;
- }
- private int GetColumn(string columnname)
- {
- if (_columnindexes.ContainsKey(columnname))
- return _columnindexes[columnname];
- for (var i = 0; i < Table.Columns.Count; i++)
- if (Table.Columns[i].ColumnName.Equals(columnname))
- {
- _columnindexes[columnname] = i;
- return i;
- }
- _columnindexes[columnname] = -1;
- return -1;
- }
- }
- public static class CoreRowExtensions
- {
- public static IEnumerable<T> ToObjects<T>(this IEnumerable<CoreRow> rows)
- where T : BaseObject, new()
- {
- return rows.Select(x => x.ToObject<T>());
- }
- }
- }
|