public DocumentSerializationWithIlPropertyFactoryTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); var configuration = new SerializationConfiguration(new SerializationContractResolver()); SUT = new DefaultSerializer(configuration, new DocumentSerializationMetaProvider(), entityReflector); }
protected SerializationConfiguration CreateSerializationConfiguration(EntityReflector entityReflector) { return(new SerializationConfiguration(new EntitySerializationContractResolver(entityReflector)) { WriterFactory = (t, w) => new EntityJsonWriter(t, w) }); }
public GetChangesHttpRequestFactoryTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); var configuration = new SerializationConfiguration(new SerializationContractResolver()); var serializer = new DefaultSerializer(configuration, new DocumentSerializationMetaProvider(), entityReflector); SUT = new GetChangesHttpRequestFactory(serializer); }
/// <summary> /// Update base <see cref="EntityType"/> to database /// </summary> /// <param name="sql"></param> /// <param name="p"></param> /// <param name="commandType"></param> /// <returns></returns> public virtual int Update(string sql, EntityType entity) { int returnValue = 0; Db db = new Db(); DbParameter[] param = new DbParameter[EntityFieldInfoCache <EntityType> .GetEntityFieldInfos().Count]; int i = 0; // build insert query and parameter foreach (EntityFieldInfo fieldInfo in EntityFieldInfoCache <EntityType> .GetEntityFieldInfos()) { if (fieldInfo.FieldAccessMode == FieldAccessMode.ReadWrite) { try { // retrive entity value object value = EntityReflector <EntityType> .GetValueFromField(entity, fieldInfo); // add data parameter if (value != null) { if (fieldInfo.FieldType == FieldType.DateTime && Convert.ToDateTime(value).ToString("dd/MM/yyyy") == "01/01/0001") { continue; } param[i] = new DbParameter("@" + fieldInfo.FieldName, value); i++; } } catch (Exception ex) { throw new Exception(String.Format("Error occured while getting '{0}' property from data row.", fieldInfo.FieldName), ex); } } else { param[i] = new DbParameter("@" + fieldInfo.FieldName, entity.Id); i++; } } DbParameter[] param2 = new DbParameter[i]; for (int j = 0; j < i; j++) { param2[j] = new DbParameter(param[j].ParameterName, param[j].Value); } try { returnValue = db.Update(sql, param2, CommandType.StoredProcedure); } catch (Exception ex) { log.Fatal("Update entity has an exception: ", ex); } return(returnValue); }
/// <summary> /// Delete base <see cref="EntityType"/> specified by entity id /// </summary> /// <param name="id">Entity id</param> /// <returns></returns> public virtual int Delete(int id) { EntityType entity = EntityReflector <EntityType> .CreateInstance(); StringBuilder sb = new StringBuilder(); sb.Append("DELETE FROM ").Append(entity.TableName).Append(" WHERE id=@id"); Db db = new Db(); int ret = db.Delete(sb.ToString(), new DbParameter("@id", id), CommandType.Text); return(ret); }
/// <summary> /// Update base <see cref="EntityType"/> to database /// </summary> /// <param name="entity">Entity</param> /// <returns>A object of <see cref="EntityType"/> when success, <b>null</b> when error</returns> public virtual EntityType Update(EntityType entity) { Db db = new Db(); StringBuilder sb = new StringBuilder(); sb.Append("UPDATE ").Append(entity.TableName).Append(" SET "); DbParameter[] param = new DbParameter[EntityFieldInfoCache <EntityType> .GetEntityFieldInfos().Count]; // build update query and parameter int i = 0; foreach (EntityFieldInfo fieldInfo in EntityFieldInfoCache <EntityType> .GetEntityFieldInfos()) { if (fieldInfo.FieldAccessMode == FieldAccessMode.ReadWrite) { try { object value = EntityReflector <EntityType> .GetValueFromField(entity, fieldInfo); if (value != null) { if (fieldInfo.FieldType == FieldType.DateTime && DateTime.Compare(Convert.ToDateTime(value), new DateTime(1, 1, 1)) == 0) { continue; } param[i] = new DbParameter("@" + fieldInfo.FieldName, value); sb.Append(fieldInfo.FieldName).Append("=@").Append(fieldInfo.FieldName).Append(", "); i++; } } catch (Exception ex) { log.Fatal("Error occured while getting '{0}' property from data row: ", ex); throw new Exception(String.Format("Error occured while getting '{0}' property from data row.", fieldInfo.FieldName), ex); } } else { param[i] = new DbParameter("@" + fieldInfo.FieldName, entity.Id); i++; } } DbParameter[] param2 = new DbParameter[i]; for (int j = 0; j < i; j++) { param2[j] = new DbParameter(param[j].ParameterName, param[j].Value); log.Info(param[j].ParameterName + ":" + param[j].Value); } sb.Remove(sb.Length - 2, 2); sb.Append(" WHERE id=@id"); return((db.Update(sb.ToString(), param2, CommandType.Text) > 0) ? entity : null); }
private void SetEntityForeignKey(object parentEntity, object childEntity) { var parentProps = parentEntity.GetType().GetProperties(); var parentKey = EntityReflector.GetKeyColumn(parentProps); var childProps = childEntity.GetType().GetProperties(); var childForeignKey = EntityReflector.GetForeignKeyColumn(childProps); if ((parentKey != null) && (childForeignKey != null)) { childForeignKey.SetValue(childEntity, parentKey.GetValue(parentEntity, null), null); } }
public void GetByPrimaryKeyTest() { var entityType = typeof(SampleEntity); var entityProps = entityType.GetProperties(); var testFilter = EntityReflector.GetFilterByPrimaryKey(entityType, entityProps, 12345); var result = EntitySqlParser.ParseEntity(testFilter, DatabaseEngine.SQLite, PersistenceAction.Get, testFilter); result = result.Trim(); Assert.NotNull(result); Assert.StartsWith("SELECT", result); Assert.EndsWith(string.Format("WHERE {0}.{1} = 12345", "sample_entity", "doc_number"), result); }
public void SearchTest() { var filterType = typeof(SampleEntity); var filterProps = filterType.GetProperties(); var testFilter = EntityReflector.GetFilterByFilterableColumns(typeof(SampleEntity), filterProps, "roberto"); var result = EntitySqlParser.ParseEntity(testFilter, DatabaseEngine.SQLite, PersistenceAction.List, testFilter); result = result.Trim(); Assert.NotNull(result); Assert.StartsWith("SELECT", result); Assert.Contains("FROM", result); Assert.EndsWith(string.Format("WHERE {0}.{1} LIKE '%roberto%'", "sample_entity", "name"), result); }
public async Task <ICollection <T> > SearchAsync(object criteria, bool loadComposition = false, int recordsLimit = 0, string orderAttributes = null, bool orderDescending = false) { var result = new List <T>(); var filter = EntityReflector.GetFilterByFilterableColumns(entityType, entityProps, criteria); var queryResult = await ListObjectsAsync(filter, PersistenceAction.List, loadComposition, recordsLimit, orderAttributes : orderAttributes, orderDescending : orderDescending); if (queryResult != null) { foreach (var item in queryResult) { result.Add(item as T); } } return(result); }
/// <summary> /// Find list EntityType /// </summary> /// <param name="sql">string query</param> /// <param name="commandType">command type</param> /// <returns></returns> public virtual IList <EntityType> FindList(string sql, CommandType commandType) { Db db = new Db(); DataTable dt = db.GetDataTable(sql, commandType); List <EntityType> list = new List <EntityType>(); if (dt != null) { foreach (DataRow row in dt.Rows) { EntityType entity = EntityReflector <EntityType> .CreateInstance(); entity = mapper.MapItem(row); list.Add(entity); } } return(list); }
/// <summary> /// Find EntityType /// </summary> /// <param name="sql">string query</param> /// <param name="p">parameter</param> /// <param name="commandType">command type</param> /// <returns></returns> public virtual EntityType FindEntity(string sql, DbParameter[] p, CommandType commandType) { Db db = new Db(); EntityType entity = EntityReflector <EntityType> .CreateInstance(); try { DataRow row = db.GetDataRow(sql, p, commandType); if (row != null) { entity = mapper.MapItem(row); } } catch (Exception ex) { log.Fatal("Find entity has an exception: ", ex); return(null); } return(entity); }
private void CreateReplicas(object entity, PropertyInfo[] entityProps, int lastInsertedId, bool persistComposition) { var entityColumnKey = EntityReflector.GetKeyColumn(entityProps); if (entityColumnKey != null) { entityColumnKey.SetValue(entity, lastInsertedId, null); } ParallelParam parallelParam = new ParallelParam() { Param1 = entity, Param2 = PersistenceAction.Create, Param3 = persistComposition }; var replicationParallelDelegate = new ParameterizedThreadStart(PersistReplicasAsync); Parallelizer.StartNewProcess(replicationParallelDelegate, parallelParam); }
/// <summary> /// Find object <see cref="EntityType"/> specified by id /// </summary> /// <param name="id">Entity Id</param> /// <returns>A object of <see cref="EntityType"/> when success, <b>null</b> when error or not found </returns> public virtual EntityType FindByKey(int id) { EntityType entity = EntityReflector <EntityType> .CreateInstance(); try { StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM ").Append(entity.TableName).Append(" WHERE id=@id"); Db db = new Db(); DataRow row = db.GetDataRow(sb.ToString(), new DbParameter("@id", id), CommandType.Text); if (row != null) { entity = mapper.MapItem(row); } } catch (Exception ex) { log.Fatal("Find entity has an exception: ", ex); return(null); } return(entity); }
public virtual IList <EntityType> FindAll() { EntityType entity1 = EntityReflector <EntityType> .CreateInstance(); StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM ").Append(entity1.TableName); Db db = new Db(); DataTable dt = db.GetDataTable(sb.ToString(), CommandType.Text); List <EntityType> list = new List <EntityType>(); if (dt != null) { foreach (DataRow row in dt.Rows) { EntityType entity = EntityReflector <EntityType> .CreateInstance(); entity = mapper.MapItem(row); list.Add(entity); } } return(list); }
/// <summary> /// Lazy load method /// </summary> public void LazyLoad() { if (!initialized) { EntityType entity1 = EntityReflector <EntityType> .CreateInstance(); StringBuilder sb = new StringBuilder(); sb.Append("SELECT * FROM ").Append(entity1.TableName).Append(" WHERE ").Append(ForeignKey).Append("=@").Append(ForeignKey); DbParameter param = new DbParameter("@" + this.ForeignKey, Parrent.Id); Db db = new Db(); DataTable dt = db.GetDataTable(sb.ToString(), param, CommandType.Text); if (dt != null) { foreach (DataRow row in dt.Rows) { EntityType entity = EntityReflector <EntityType> .CreateInstance(); entity = mapper.MapItem(row); list.Add(entity); } } } initialized = true; }
/// <summary> /// Insert base <see cref="EntityType"/> to database /// </summary> /// <param name="entity">Entity</param> /// <returns>A object of <see cref="EntityType"/> when success, <b>null</b> when error</returns> public virtual int Insert(EntityType entity) { Db db = new Db(); // string buider query insert StringBuilder sb = new StringBuilder(); // string builder values to insert StringBuilder sbValues = new StringBuilder(); // append entity table name sb.Append("INSERT INTO ").Append(entity.TableName).Append(" ("); sbValues.Append(" VALUES ("); DbParameter[] param = new DbParameter[EntityFieldInfoCache <EntityType> .GetEntityFieldInfos().Count]; int i = 0; // build insert query and parameter foreach (EntityFieldInfo fieldInfo in EntityFieldInfoCache <EntityType> .GetEntityFieldInfos()) { if (fieldInfo.FieldAccessMode == FieldAccessMode.ReadWrite) { try { // retrive entity value object value = EntityReflector <EntityType> .GetValueFromField(entity, fieldInfo); // add data parameter if (value != null) { if (fieldInfo.FieldType == FieldType.DateTime && Convert.ToDateTime(value).ToString("dd/MM/yyyy") == "01/01/0001") { continue; } if (fieldInfo.FieldType == FieldType.String && value.ToString() == string.Empty) { continue; } param[i] = new DbParameter("@" + fieldInfo.FieldName, value); // append to query sb.Append(fieldInfo.FieldName).Append(", "); sbValues.Append("@").Append(fieldInfo.FieldName).Append(", "); i++; } } catch (Exception ex) { throw new Exception(String.Format("Error occured while getting '{0}' property from data row.", fieldInfo.FieldName), ex); } } //else //{ // param[i] = new DbParameter("@" + fieldInfo.FieldName, entity.Id); // i++; //} } DbParameter[] param2 = new DbParameter[i]; for (int j = 0; j < i; j++) { param2[j] = new DbParameter(param[j].ParameterName, param[j].Value); } // fix string builder value sb.Remove(sb.Length - 2, 2); sbValues.Remove(sbValues.Length - 2, 2); sb.Append(")").Append(sbValues).Append(")"); // execute insert query return(db.Insert(sb.ToString(), true, param2, CommandType.Text)); }
private void FillComposition(object loadedEntity, PropertyInfo[] entityProps) { RelatedEntity relationConfig = null; var propertiesList = entityProps.Where(prp => prp.GetCustomAttributes(true) .Any(atb => atb.GetType().Name.Equals("RelatedEntity"))); foreach (var prop in propertiesList) { object attributeInstance = null; IEnumerable <object> attributeAnnotations = prop.GetCustomAttributes(true) .Where(atb => atb.GetType().Name.Equals("RelatedEntity")); foreach (object annotation in attributeAnnotations) { relationConfig = (RelatedEntity)annotation; PropertyInfo foreignKeyColumn = null; object foreignKeyValue = null; var keyColumn = EntityReflector.GetKeyColumn(entityProps); switch (relationConfig.Cardinality) { case RelationCardinality.OneToOne: attributeInstance = Activator.CreateInstance(prop.PropertyType); foreignKeyColumn = loadedEntity.GetType().GetProperty(relationConfig.ForeignKeyAttribute); foreignKeyValue = foreignKeyColumn.GetValue(loadedEntity, null); if ((foreignKeyValue != null) && int.Parse(foreignKeyValue.ToString()) > 0) { var attributeProps = attributeInstance.GetType().GetProperties(); var keyColumnAttribute = EntityReflector.GetKeyColumn(attributeProps); keyColumnAttribute.SetValue(attributeInstance, foreignKeyColumn.GetValue(loadedEntity, null), null); attributeInstance = GetObject(attributeInstance); } break; case RelationCardinality.OneToMany: attributeInstance = Activator.CreateInstance(prop.PropertyType.GetGenericArguments()[0], true); foreignKeyColumn = attributeInstance.GetType().GetProperty(relationConfig.ForeignKeyAttribute); foreignKeyColumn.SetValue(attributeInstance, int.Parse(keyColumn.GetValue(loadedEntity, null).ToString()), null); attributeInstance = ListObjects(attributeInstance as object, PersistenceAction.List); break; case RelationCardinality.ManyToMany: attributeInstance = Activator.CreateInstance(relationConfig.IntermediaryEntity, true); if (attributeInstance != null) { SetEntityForeignKey(loadedEntity, attributeInstance); var manyToRelations = ListObjects(attributeInstance, PersistenceAction.List, true); Type childManyType = prop.PropertyType.GetGenericArguments()[0]; Type dynamicManyType = typeof(List <>).MakeGenericType(new Type[] { childManyType }); IList childManyEntities = (IList)Activator.CreateInstance(dynamicManyType, true); foreach (var rel in manyToRelations) { var childManyKeyValue = rel.GetType().GetProperty(relationConfig.IntermediaryKeyAttribute).GetValue(rel, null); var childFilter = Activator.CreateInstance(childManyType); var childFilterProps = childFilter.GetType().GetProperties(); EntityReflector.GetKeyColumn(childFilterProps).SetValue(childFilter, childManyKeyValue, null); var childInstance = GetObject(childFilter); childManyEntities.Add(childInstance); } attributeInstance = childManyEntities; } break; } } if (attributeInstance != null) { if (!prop.PropertyType.Name.Contains("List")) { prop.SetValue(loadedEntity, attributeInstance, null); } else { prop.SetValue(loadedEntity, (IList)attributeInstance, null); } } } }
private List <string> ParseComposition(object entity, PersistenceAction action, object filterEntity) { List <string> result = new List <string>(); object childEntityInstance = null; var entityType = entity.GetType(); IEnumerable <PropertyInfo> childEntities = entityType.GetProperties().Where(prp => prp.GetCustomAttributes(true) .Any(atb => atb.GetType().Name.Equals("RelatedEntity"))); foreach (PropertyInfo child in childEntities) { var relationAttrib = child.GetCustomAttributes(true) .FirstOrDefault(atb => atb.GetType().Name.Equals("RelatedEntity")) as RelatedEntity; childEntityInstance = child.GetValue(entity, null); object childEntityFilter = null; var entityParent = (action != PersistenceAction.Edit) ? entity : filterEntity; if (childEntityInstance != null) { var childEntityType = childEntityInstance.GetType(); if (!childEntityType.Name.Contains("List")) { var childProps = childEntityType.GetProperties(); action = EntitySqlParser.SetPersistenceAction(childEntityInstance, EntityReflector.GetKeyColumn(childProps)); childEntityFilter = Activator.CreateInstance(childEntityInstance.GetType()); if (action == PersistenceAction.Edit) { EntityReflector.MigrateEntityPrimaryKey(childEntityInstance, childProps, childEntityFilter); } SetEntityForeignKey(entityParent, child); result.Add(EntitySqlParser.ParseEntity(childEntityInstance, engine, action)); } else { var childListInstance = (IList)childEntityInstance; List <object> childFiltersList = new List <object>(); if (childListInstance.Count > 0) { foreach (var listItem in childListInstance) { if (relationAttrib.Cardinality == RelationCardinality.OneToMany) { var listItemType = listItem.GetType(); childEntityFilter = Activator.CreateInstance(listItemType); var listItemProps = listItemType.GetProperties(); action = EntitySqlParser.SetPersistenceAction(listItem, EntityReflector.GetKeyColumn(listItemProps)); if (action == PersistenceAction.Edit) { EntityReflector.MigrateEntityPrimaryKey(listItem, listItemProps, childEntityFilter); childFiltersList.Add(childEntityFilter); } SetEntityForeignKey(entityParent, listItem); result.Add(EntitySqlParser.ParseEntity(listItem, engine, action)); } else { var manyToEntity = EntitySqlParser.ParseManyToRelation(listItem, relationAttrib); SetEntityForeignKey(entityParent, manyToEntity); var existRelation = this.GetObject(manyToEntity); if (existRelation != null) { manyToEntity = existRelation; } var manyToEntityProps = manyToEntity.GetType().GetProperties(); action = EntitySqlParser.SetPersistenceAction(manyToEntity, EntityReflector.GetKeyColumn(manyToEntityProps)); object existFilter = null; if (action == PersistenceAction.Edit) { existFilter = Activator.CreateInstance(manyToEntity.GetType()); EntityReflector.MigrateEntityPrimaryKey(manyToEntity, manyToEntityProps, existFilter); childFiltersList.Add(existFilter); } result.Add(EntitySqlParser.ParseEntity(manyToEntity, engine, action)); } } } else { var childInstance = Activator.CreateInstance(childListInstance.GetType().GetGenericArguments()[0]); var childEntity = new object(); if (relationAttrib.Cardinality == RelationCardinality.ManyToMany) { childEntity = EntitySqlParser.ParseManyToRelation(childInstance, relationAttrib); } else { childEntity = childInstance; } SetEntityForeignKey(entityParent, childEntity); childFiltersList.Add(childEntity); } } } } if (result.Any(rst => rst.Contains(SQLStatements.SQL_ReservedWord_INSERT))) { result.Reverse(); } return(result); }
public async Task CreateBulkRangeAsync(ICollection <T> entities) { var entitiesTable = EntityReflector.GetDataTable <T>(entities); await ExecuteBulkCommandAsync(entitiesTable); }
public DefaultResponseMaterializerWithEntityContractResolverUsingIlTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); SUT = new DefaultResponseMaterializer(new SerializationConfiguration(new EntitySerializationContractResolver(entityReflector))); }
protected static SerializationConfiguration CreateSerializationConfiguration(EntityReflector entityReflector) { return(new SerializationConfiguration(new EntityContractResolver(entityReflector))); }
public EntitySerializationWithIlPropertyFactoryTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); SUT = new EntitySerializer(CreateSerializationConfiguration(entityReflector), CreateDocumentSerializationMetaProvider()); }
public T Get(object key, bool loadComposition = false) { var filter = EntityReflector.GetFilterByPrimaryKey(entityType, entityProps, key) as T; return(Get(filter, loadComposition)); }
public EntitySerializationWithIlPropertyFactoryTests() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); SUT = new DefaultSerializer(CreateSerializationConfiguration(entityReflector)); }
public async Task <T> GetAsync(object key, bool loadComposition = false) { var filter = EntityReflector.GetFilterByPrimaryKey(entityType, entityProps, key) as T; return(await GetAsync(filter, loadComposition)); }
private static SerializationConfiguration CreateSerializationConfiguration() { var entityReflector = new EntityReflector(new IlDynamicPropertyFactory()); return(new SerializationConfiguration(new EntityContractResolver(entityReflector))); }
public void CreateBulkRange(ICollection <T> entities) { var entitiesTable = EntityReflector.GetDataTable <T>(entities); ExecuteBulkCommand(entitiesTable); }