using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Tango.BL.Entities; namespace Tango.PPC.Shared.SQL { /// /// Represents a row. /// /// /// /// /// The following example demonstrates how to set the connected machine's demo state and query for the connected machine's jobs. /// /// /// /// public class RemoteSqlRow { private Func _getFuncKey; private Func _getFuncIndex; /// /// Gets or sets the row values. /// public List Values { get; set; } /// /// Initializes a new instance of the class. /// public RemoteSqlRow() { Values = new List(); } /// /// Gets a row value by its column name. /// /// Name of the column. /// The column value. public Object Get(String columnName) { return _getFuncKey.Invoke(columnName); } /// /// Gets a row value by its column index. /// /// Index of the column. /// The column value. public Object Get(int columnIndex) { return _getFuncIndex.Invoke(columnIndex); } /// /// Gets a row value as type T by its column name. /// /// Expected column type. /// Name of the column. /// The column value. public T Get(String columnName) { var value = _getFuncKey.Invoke(columnName); if (typeof(T) != value.GetType()) { return (T)Convert.ChangeType(value, typeof(T)); } else { return (T)value; } } /// /// Gets a row value by its column index. /// /// Expected column type /// Index of the column. /// The column value. public T Get(int columnIndex) { var value = _getFuncIndex.Invoke(columnIndex); if (typeof(T) != value.GetType()) { return (T)Convert.ChangeType(value, typeof(T)); } else { return (T)value; } } internal void Init(Func getFuncKey, Func getFuncIndex) { _getFuncKey = getFuncKey; _getFuncIndex = getFuncIndex; } /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() { return String.Join(", ", Values); } /// /// Creates an object of type T and maps this row to it based on its properties decorated with . /// /// /// public T Map() where T : class, new() { var obj = Activator.CreateInstance(); Map(obj); return obj; } /// /// Maps this row to the specified object based on its properties decorated with . /// /// Model type /// The object. public void Map(T obj) where T : class { foreach (var prop in typeof(T).GetPropertiesWithAttribute()) { try { var columnName = prop.GetCustomAttribute().Name; var value = Get(columnName).ToStringSafe(); prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType)); } catch (Exception ex) { Debug.WriteLine(ex); } } } } }