예제 #1
0
 public void Test_Mapping()
 {
     using (NT.XUnit.TestMeta.TestContext ctx = new NT.XUnit.TestMeta.TestContext(ContextUtil.GetOptions()))
     {
         DbMapping map = DbMapper.GetDbMapping(ctx);
     }
 }
예제 #2
0
        public static DBFields GetDbFields <TEntityType>(this TEntityType entity) where TEntityType : IDbEntity
        {
            if (entity == null)
            {
                return(null);
            }
            var map = DbMapping.Get(entity.GetType());

            if (map?.PropertiesInfos == null || map.PropertiesInfos.Count == 0)
            {
                return(null);
            }
            var fields = new DBFields();

            foreach (var property in map.PropertiesInfos)
            {
                var value = property.GetValue(entity);
                if (value == null)
                {
                    continue;
                }
                fields.SetEx(property.Name, value);
            }
            return(fields);
        }
예제 #3
0
 /// <summary>
 /// Returns the identifier of a specified node.
 /// </summary>
 /// <param name="node">Is the node object.</param>
 public static Identifier I(this DbNode node)
 {
     // check null
     if (node == null)
     {
         throw new QueryTalkException("I", QueryTalkExceptionType.ArgumentNull, "node = null", Text.Method.I);
     }
     return(DbMapping.GetNodeName(node.NodeID));
 }
예제 #4
0
        public static DbRecord ToDbRecord(this DBRecord record)
        {
            if (record == null)
            {
                return(null);
            }
            var map = DbMapping.Get(record.Table.TableId);

            return(new DbRecord(record));
        }
        internal AuditLog CreateLogRecord(object userName, EventType eventType, ITrackerContext context, ExpandoObject metadata)
        {
            Type entityType = _dbEntry.Entity.GetType().GetEntityType();

            if (!EntityTrackingConfiguration.IsTrackingEnabled(entityType))
            {
                return(null);
            }

            DateTime changeTime = DateTime.UtcNow;

            //todo: make this a static class
            DbMapping mapping = new DbMapping(context, entityType);
            List <PropertyConfiguerationKey> keyNames = mapping.PrimaryKeys().ToList();

            AuditLog newlog = new AuditLog
            {
                UserName     = userName?.ToString(),
                EventDateUTC = changeTime,
                EventType    = eventType,
                TypeFullName = entityType.FullName,
                RecordId     = GetPrimaryKeyValuesOf(_dbEntry, keyNames).ToString()
            };

            List <LogMetadata> logMetadata = metadata
                                             .Where(x => x.Value != null)
                                             .Select(m => new LogMetadata
            {
                AuditLog = newlog,
                Key      = m.Key,
                Value    = m.Value?.ToString()
            })
                                             .ToList();

            newlog.Metadata = logMetadata;

            ChangeLogDetailsAuditor detailsAuditor = GetDetailsAuditor(eventType, newlog);

            newlog.LogDetails = detailsAuditor.CreateLogDetails().ToList();

            if (newlog.LogDetails.Any())
            {
                return(newlog);
            }
            else
            {
                return(null);
            }
        }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static DbMapping Get(DbContext context)
        {
            var cackeKey = context.GetType().FullName;

#if EF6
            var iDbModelCacheKeyProvider = context as IDbModelCacheKeyProvider;
            if (iDbModelCacheKeyProvider != null)
            {
                cackeKey = iDbModelCacheKeyProvider.CacheKey;
            }
#endif

            if (Mappings.ContainsKey(cackeKey))
            {
                return(Mappings[cackeKey]);
            }

            var mapping = new DbMapping(context);
            return(Mappings.TryAdd(cackeKey, mapping)? mapping : Mappings[cackeKey]);
        }
예제 #7
0
        public void Sync()
        {
            var changes = DropboxDatastore?.Sync();

            if (changes != null && changes.Count > 0)
            {
                foreach (var change in changes)
                {
                    var map = DbMapping.Get(change.Key);
                    if (map == null)
                    {
                        continue;
                    }
                    foreach (var record in change.Value)
                    {
                        DbRecordChanged?.Invoke(this, new DbRecordChangedEventArgs(record.ToDbRecord()));
                    }
                }
            }
        }
예제 #8
0
        public static Dictionary <string, object> ToDictionary(this DBRecord record, DbMapping mapping)
        {
            var dictionary = new Dictionary <string, object>();

            foreach (var fieldName in record.FieldNames())
            {
                var property = mapping.PropertiesInfos.SingleOrDefault(p => p.Name.Equals(fieldName));
                if (property != null)
                {
                    object value = null;
                    var    type  = property.PropertyType;
                    if (type.IsLong())
                    {
                        value = record.GetLong(fieldName);
                    }
                    else if (type.IsNumeric())
                    {
                        value = record.GetDouble(fieldName);
                    }
                    else if (type.IsBool())
                    {
                        value = record.GetBoolean(fieldName);
                    }
                    else if (type.IsDateTime())
                    {
                        var date = record.GetDate(fieldName);
                        value = date.ToDateTime();
                    }
                    else if (type == typeof(string))
                    {
                        value = record.GetString(fieldName);
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                    dictionary.Add(fieldName, value);
                }
            }
            return(dictionary);
        }
        internal AuditLog CreateLogRecord(object userName, EventType eventType, ITrackerContext context)
        {
            Type entityType = _dbEntry.Entity.GetType().GetEntityType();

            if (!EntityTrackingConfiguration.IsTrackingEnabled(entityType))
            {
                return(null);
            }

            DateTime changeTime = DateTime.UtcNow;

            //todo: make this a static class
            var mapping = new DbMapping(context, entityType);

            List <PropertyConfiguerationKey> keyNames = mapping.PrimaryKeys().ToList();

            var newlog = new AuditLog
            {
                UserName     = userName?.ToString(),
                EventDateUTC = changeTime,
                EventType    = eventType,
                TypeFullName = entityType.FullName,
                RecordId     = GetPrimaryKeyValuesOf(_dbEntry, keyNames).ToString()
            };

            var detailsAuditor = GetDetailsAuditor(eventType, newlog);

            newlog.LogDetails = detailsAuditor.CreateLogDetails().ToList();


            if (newlog.LogDetails.Any())
            {
                return(newlog);
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static DbMapping Get(DbContext context)
        {
            var cackeKey = context.GetType().FullName;

            var iDbModelCacheKeyProvider = context as IDbModelCacheKeyProvider;

            if (iDbModelCacheKeyProvider != null)
            {
                cackeKey = iDbModelCacheKeyProvider.CacheKey;
            }

            if (Mappings.ContainsKey(cackeKey))
            {
                return(Mappings[cackeKey]);
            }

            var mapping = new DbMapping(context);

            //var mapping = Map(context);

            Mappings[cackeKey] = mapping;
            return(mapping);
        }
예제 #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static DbMapping Get(DbContext context)
        {
            var cacheKey = context.GetType().FullName;

            var iDbModelCacheKeyProvider = context as IDbModelCacheKeyProvider;

            if (iDbModelCacheKeyProvider != null)
            {
                cacheKey = iDbModelCacheKeyProvider.CacheKey;
            }

            DbMapping mapping;

            if (Mappings.TryGetValue(cacheKey, out mapping))
            {
                return(mapping);
            }

            mapping = new DbMapping(context);

            Mappings[cacheKey] = mapping;
            return(mapping);
        }
예제 #12
0
        /// <summary>
        /// Specifies the foreign key that is to be used in relation.
        /// The foreign key should be explicitly given when there is more than one relation between two tables.
        /// </summary>
        /// <typeparam name="T">The type of the node.</typeparam>
        /// <param name="node">The node to which belongs the foreign key.</param>
        /// <param name="column">The column that is part of the foreign key.</param>
        public static DbTable <T> By <T>(this DbTable <T> node, string column)
            where T : DbRow
        {
            // null check
            if (node == null)
            {
                throw new QueryTalkException(".By", QueryTalkExceptionType.ArgumentNull, "node", Text.Method.By);
            }
            if (column == null)
            {
                throw new QueryTalkException(".By", QueryTalkExceptionType.ArgumentNull, "column", Text.Method.By);
            }

            var       nodeMap   = DbMapping.GetNodeMap(node.NodeID);
            ColumnMap columnMap = null;

            foreach (var col in nodeMap.Columns)
            {
                if (Api.IsEqual(col.Name.Part1, column))
                {
                    columnMap = col;
                    break;
                }
            }

            if (columnMap == null)
            {
                throw new QueryTalkException(".By", QueryTalkExceptionType.ColumnNotFound,
                                             String.Format("node = {0}{1}   column = {2}", node.Name, Environment.NewLine, column), Text.Method.By)
                      .SetObjectName(node.Name);
            }

            ((IRelation)node).FK = columnMap.ID;

            return(node);
        }
예제 #13
0
        internal static DataTable ToDataTable <U>(IEnumerable <U> collection)
        {
            string collectionTypeName;
            Type   tableType = typeof(U);

            if (collection == null)
            {
                throw new QueryTalkException("ToDataTable<T>", QueryTalkExceptionType.CollectionNullOrEmpty,
                                             String.Format("data class = {0}", tableType), Text.Method.ToDataTable);
            }

            collectionTypeName = collection.GetType().Name;
            if (collection is Wall.IResult)
            {
                collectionTypeName = Text.Class.ResultSet;
            }

            if (collectionTypeName == Text.Class.ResultSet)
            {
                var resultSet = (ResultSet <U>)collection;

                if (resultSet.DataTable != null)
                {
                    return(resultSet.DataTable);
                }

                // check dynamic - not convertable
                if (tableType == typeof(System.Object))
                {
                    if (collection.Count() == 0)
                    {
                        throw new QueryTalkException("ResultSet.getTableType", QueryTalkExceptionType.EmptyResultset,
                                                     "table type = dynamic", Text.Method.ToDataTable);
                    }

                    // infer type from the item
                    using (var enumerator = collection.GetEnumerator())
                    {
                        enumerator.MoveNext();
                        tableType = enumerator.Current.GetType();
                    }
                }
            }

            DataTable dataTable = new DataTable();

            dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;

            // always build new getters (not using cache)
            var getters = new List <IPropertyAccessor>();

            var props = tableType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                        .Where(prop => prop.GetGetMethod() != null)
                        .ToArray();

            PropertyInfo[] properties;

            if (tableType.IsDbRow())
            {
                var node = DbMapping.GetNodeMap(tableType);
                var propsByDatabaseOrder = new List <PropertyInfo>();
                foreach (var column in node.SortedColumnsByDatabaseOrder)
                {
                    var prop = props.Where(a => a.Name.EqualsCS(column.ClrName)).Select(a => a).FirstOrDefault();
                    if (prop != null)
                    {
                        propsByDatabaseOrder.Add(prop);
                    }
                }

                properties = propsByDatabaseOrder.ToArray();
            }
            else
            {
                properties = props;
            }

            if (properties.Length == 0)
            {
                throw new QueryTalkException("ResultSet.ToDataTable", QueryTalkExceptionType.InvalidDataClass,
                                             String.Format("data class = {0}", tableType), Text.Method.ToDataTable);
            }

            int numberOfPropertiesUsed = 0;

            foreach (PropertyInfo property in properties)
            {
                Type clrType;
                QueryTalkException exception;

                var clrTypeMatch = Mapping.CheckClrCompliance(property.PropertyType, out clrType, out exception);
                if (clrTypeMatch == Mapping.ClrTypeMatch.NodeMatch)
                {
                    continue;
                }

                if (clrTypeMatch != Mapping.ClrTypeMatch.ClrMatch)
                {
                    ThrowNotClrCompliantException(exception, property.PropertyType);
                }

                dataTable.Columns.Add(property.Name, clrType);

                getters.Add(PropertyAccessor.Create(tableType, property));

                ++numberOfPropertiesUsed;
            }

            foreach (U item in collection)
            {
                DataRow row = dataTable.NewRow();
                for (int i = 0; i < numberOfPropertiesUsed; i++)
                {
                    row[i] = getters[i].GetValue(item) ?? DBNull.Value;
                }

                dataTable.Rows.Add(row);
            }

            return(dataTable);
        }