/// <summary> /// Updates row in table. /// </summary> /// <param name="dbObject">Table name based on type name of object.</param> /// <returns></returns> public bool UpdateData(IDbObject dbObject, string condition = null) { GenericPropertyFinder <IDbObject> property = new GenericPropertyFinder <IDbObject>(); IEnumerable <List <string> > obj = property.PrintTModelPropertyAndValue(dbObject); string table = dbObject.GetType().ToString().Substring(dbObject.GetType().ToString().LastIndexOf('.') + 1); string query = new DbQueryBuilder(obj, table, condition).BuildQuery(QueryType.Update); if (condition != null) { if (query.EndsWith(';')) { query = query[0..^ 1];
public long Insert(IDbObject o, DbConnection connection, IDictionary <IDbObject, long> objectGraph) { var type = o.GetType(); var dbFunctionHelper = GetDbFunctionHelper(type); return(dbFunctionHelper.Insert(o, connection, objectGraph)); }
public string Insert(IDbObject o, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate) { string key = o.Id + "_" + o.GetType().Name; cache.Insert(key, o, time, isRelative, removeDelegate); return(ownIp + "_" + key); }
/// <summary> /// Добавляет сущность в базу данных на основе параметров входного IDTOModel. /// </summary> /// /// <param name="inputDbObject"> Объект IDbObject, параметры которого /// будут основой для добавляемого объекта. /// Тип класса влияет на тип сохраняемой сущности. </param> /// <remarks> /// Тип входного inputDTO влияет на тип сохраняемой сущности. </remarks> /// /// <returns> Task Log, Result которого true, если операция добавления была успешно выполнена. /// Иначе, будет возвращён Log с описанием ошибки и значением Result - false. /// Сущность не будет сохранена. /// </returns> public async Task <Log> AddEntityToDb(IDbObject inputDbObject) { try { if (inputDbObject.GetType() == typeof(DbNews)) { var newNews = inputDbObject as DbNews; _context.News.Add(newNews); await _context.SaveChangesAsync(); } else if (inputDbObject.GetType() == typeof(DbUser)) { var newUser = inputDbObject as DbUser; _context.Users.Add(newUser); await _context.SaveChangesAsync(); } else { throw new TypeAccessException("Invalid type for IDbObject argument."); } } catch (DbUpdateConcurrencyException ex) { return(WriteLog(NameOfManager, "AddEntityToDb", ex)); } catch (DbUpdateException ex) { return(WriteLog(NameOfManager, "AddEntityToDb", ex)); } catch (TypeAccessException ex) { return(WriteLog(NameOfManager, "AddEntityToDb", ex)); } catch (Exception ex) { return(WriteLog(NameOfManager, "AddEntityToDb", ex)); } return(WriteLog(NameOfManager, "AddEntityToDb")); }
public IEnumerable <Account> GetInstanceAccounts() { List <Account> result = new List <Account>(); IDbObject instance = GetInstance(); if (instance is Account) { result.Add((Account)instance); } else if (instance is AccountFeedItem) { result.Add(((AccountFeedItem)instance).AccountFeed.Account); } else if (instance is AccountGroup) { foreach (AccountGroupAccount account in ((AccountGroup)instance).AccountGroupAccounts) { if (account.IsAdministrator) { result.Add(account.Account); } } } else if (instance is IDbObject) { PropertyInfo pi = instance.GetType().BaseType.GetProperty("Account"); if (pi == null) { throw new Exception(string.Format( "Unsupported type: {0} doesn't have an an Account property", instance.GetType().FullName)); } result.Add((Account)pi.GetValue(instance, null)); } else { throw new Exception(string.Format("Unsupported type: {0}", instance.GetType().FullName)); } return(result); }
public int Update(IDbObject o, DbConnection connection, IDictionary <IDbObject, long> objectGraph) { objectGraph.Add(o, o.Id); var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType()); var result = 0; if (o.IsDirty) { o.IsDirty = false; var mappingTable = classMetadata.MappingTable; var properties = classMetadata.Properties; var command = connection.CreateCommand(); var queryBuilder = new StringBuilder("UPDATE " + mappingTable + " SET "); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("`" + mappingField + "`=@" + mappingField + ", "); } var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString); queryBuilder.Append(" WHERE Id = " + o.Id); command.CommandText = queryBuilder.ToString(); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; var propertyInfo = mappingInfo.PropertyInfo; var propertyType = propertyInfo.PropertyType; object value = propertyInfo.GetValue(o, null); if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal)) { command.Parameters.Add(new MySqlParameter("@" + mappingField, value)); } else { byte[] blob = null; if (value != null) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, value); blob = stream.ToArray(); } } command.Parameters.Add(new MySqlParameter("@" + mappingField, blob)); } } result = command.ExecuteNonQuery(); } UpdateRelations(o, classMetadata, connection, objectGraph); return(result); }
public int Update(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph) { objectGraph.Add(o, o.Id); var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType()); var result = 0; if (o.IsDirty) { o.IsDirty = false; var mappingTable = classMetadata.MappingTable; var properties = classMetadata.Properties; var command = connection.CreateCommand(); var queryBuilder = new StringBuilder("UPDATE " + mappingTable + " SET "); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("`" + mappingField + "`=@" + mappingField + ", "); } var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString); queryBuilder.Append(" WHERE Id = " + o.Id); command.CommandText = queryBuilder.ToString(); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; var propertyInfo = mappingInfo.PropertyInfo; var propertyType = propertyInfo.PropertyType; object value = propertyInfo.GetValue(o, null); if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal)) { command.Parameters.Add(new MySqlParameter("@" + mappingField, value)); } else { byte[] blob = null; if (value != null) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, value); blob = stream.ToArray(); } } command.Parameters.Add(new MySqlParameter("@" + mappingField, blob)); } } result = command.ExecuteNonQuery(); } UpdateRelations(o, classMetadata, connection, objectGraph); return result; }
public void Insert(object key, IDbObject value, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate) { string valueKey = key.ToString() + "_" + value.GetType().Name; string id = cacheLocal.Get(valueKey); if (id != null) { string[] str = id.Split(new char[] { '_' }, 1); string host = str[0]; ServiceCacheProxy cacheProxy = cacheProxies[host]; if (cacheProxy != null) { cacheProxy.BeginInsert(FinishInsert, new object[] { valueKey, time, isRelative, removeDelegate }, value, time, isRelative, null); } } //TODO insert }
public void Insert(object key, IDbObject value, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate) { string valueKey = key.ToString() + "_" + value.GetType().Name; string id = cacheLocal.Get(valueKey); if (id != null) { string[] str = id.Split(new char[] { '_' }, 1); string host = str[0]; ServiceCacheProxy cacheProxy = cacheProxies[host]; if (cacheProxy != null) { cacheProxy.BeginInsert(FinishInsert, new object[] { valueKey, time, isRelative, removeDelegate },value, time, isRelative, null); } } //TODO insert }
public TemeljnicaPripremaForm(IDbObject obj, List <PostavkeKnjizenja> postavkeKnjizenja, List <KontoParovi> parovi = null) { Parovi = parovi; _postavkeKnjizenja = postavkeKnjizenja; _obj = obj; string model = obj.GetType().Name; InitializeComponent(); _labelList = new List <Label>() { labelDugovna, labelPotrazna }; _dt = new DataTable() { Columns = { "Redni broj", "Opis stavke", "Opis knjiženja", "Konto", "Datum dokumenta", "Dugovna", "Potražna", "Mijenja predznak" } }; SelectType(model); }
public void GetDbInstanceTest() { TransitFeature t_instance = new TransitFeature(); t_instance.DataObjectName = "Place"; t_instance.DataRowId = _place.Instance.Id; ManagedFeature m_instance = new ManagedFeature(Session); t_instance.Id = m_instance.CreateOrUpdate(t_instance, AdminSecurityContext); Console.WriteLine("Created feature: {0}", t_instance.Id); IDbObject dbobject = m_instance.GetInstance(); Console.WriteLine("Instance: {0} -> {1}", dbobject.GetType().FullName, dbobject.Id); Assert.AreEqual(dbobject.Id, _place.Instance.Id); Console.WriteLine("Instance: {0}", m_instance.GetInstance <Place>().Id); IList <Account> accounts = new List <Account>(m_instance.GetInstanceAccounts()); Console.WriteLine("Accounts: {0}", accounts.Count); m_instance.Delete(AdminSecurityContext); }
private void ProcessChildren(IDbObject obj) { using (new Scope <SavedTypeKey>(new SavedTypeKey(obj.GetType(), Handler.GetKeyValue(obj)))) { foreach (MemberHandler member in Info.RelationMembers) { if (member.Is.RelationField) { var ho = (ILazyLoading)member.GetValue(obj); if (ho.IsLoaded) { Util.TryEnumerate(ho.Read(), o => SetBelongsToForeignKey(obj, o, Handler.GetKeyValue(obj))); } } } foreach (MemberHandler member in Info.RelationMembers) { var ho = (ILazyLoading)member.GetValue(obj); if (ho.IsLoaded) { if (member.Is.HasOne) { ProcessHasOne(ho); } else if (member.Is.HasMany) { ProcessHasMany(ho); } else if (member.Is.HasAndBelongsToMany) { ProcessHasAndBelongsToMany(obj, member, ho); } } } } }
public static void Save(IDbObject obj) { GetOperator(obj.GetType()).Save(obj); }
public long Insert(IDbObject o, DbConnection connection, IDictionary <IDbObject, long> objectGraph) { if (o.Id > 0) { return(o.Id); } objectGraph.Add(o, 0); var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType()); var result = 0; var mappingTable = classMetadata.MappingTable; var properties = classMetadata.Properties; var command = connection.CreateCommand(); var queryBuilder = new StringBuilder("INSERT INTO " + mappingTable + " ( "); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("`" + mappingField + "`, "); } var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString + ") VALUES ("); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("@" + mappingField + ", "); } tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString + "); SELECT LAST_INSERT_ID()"); command.CommandText = queryBuilder.ToString(); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; var propertyInfo = mappingInfo.PropertyInfo; var propertyType = propertyInfo.PropertyType; object value = propertyInfo.GetValue(o, null); if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal)) { command.Parameters.Add(new MySqlParameter("@" + mappingField, value)); } else { byte[] blob = null; if (value != null) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, value); blob = stream.ToArray(); } } command.Parameters.Add(new MySqlParameter("@" + mappingField, blob)); } } o.Id = (long)command.ExecuteScalar(); UpdateRelations(o, classMetadata, connection, objectGraph); return(o.Id); }
public string Insert(IDbObject o, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate) { string key = o.Id + "_" + o.GetType().Name; cache.Insert(key, o, time, isRelative, removeDelegate); return ownIp + "_" + key; }
private static void SetBelongsToForeignKey(IDbObject obj, object subobj, object foreignKey) { MemberHandler belongsTo = ModelContext.GetInstance(subobj.GetType()).Info.GetBelongsTo(obj.GetType()); if (belongsTo != null) { var to = belongsTo.GetValue(subobj) as IBelongsTo; if (to != null) { to.ForeignKey = foreignKey; } } }
private void ProcessChildren(IDbObject obj) { using (new Scope<SavedTypeKey>(new SavedTypeKey(obj.GetType(), Handler.GetKeyValue(obj)))) { foreach (MemberHandler member in Info.RelationMembers) { if(member.Is.RelationField) { var ho = (ILazyLoading)member.GetValue(obj); if (ho.IsLoaded) { Util.TryEnumerate(ho.Read(), o => SetBelongsToForeignKey(obj, o, Handler.GetKeyValue(obj))); } } } foreach (MemberHandler member in Info.RelationMembers) { var ho = (ILazyLoading)member.GetValue(obj); if (ho.IsLoaded) { if (member.Is.HasOne) { ProcessHasOne(ho); } else if (member.Is.HasMany) { ProcessHasMany(ho); } else if (member.Is.HasAndBelongsToMany) { ProcessHasAndBelongsToMany(obj, member, ho); } } } } }
public int Update(IDbObject dbObject, IsolationLevel?isolationLevel) { using (var connection = connectionManager.GetUpdateConnection()) { if (isolationLevel != null) { var transaction = connection.BeginTransaction(); try { var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(dbObject.GetType()); var command = connection.CreateCommand(); command.CommandText = "SELECT UpdateTime FROM " + classMetadata.MappingTable + " WHERE Id = " + dbObject.Id; long updateTime = -1; using (var reader = command.ExecuteReader(CommandBehavior.SingleRow)) { updateTime = reader.GetInt64(reader.GetOrdinal("UpdateTime")); if (updateTime > dbObject.UpdateTime) { return(0); } } if (updateTime == -1) { throw new ApplicationException("Cannot get update time of object: " + dbObject + " with id: " + dbObject.Id); } var result = dbFunctionHelper.Update(dbObject, connection, new Dictionary <IDbObject, long>()); transaction.Commit(); return(result); } catch (Exception e) { transaction.Rollback(); throw new ApplicationException(e.ToString()); } } return(dbFunctionHelper.Update(dbObject, connection, new Dictionary <IDbObject, long>())); } }
public static int Delete(IDbObject obj) { return(GetOperator(obj.GetType()).Delete(obj)); }
public static void Insert(IDbObject obj) { GetOperator(obj.GetType()).Insert(obj); }
public static void Update(IDbObject obj) { GetOperator(obj.GetType()).Update(obj); }
public long Insert(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph) { var type = o.GetType(); var dbFunctionHelper = GetDbFunctionHelper(type); return dbFunctionHelper.Insert(o, connection, objectGraph); }
public long Insert(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph) { if (o.Id > 0) { return o.Id; } objectGraph.Add(o, 0); var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType()); var result = 0; var mappingTable = classMetadata.MappingTable; var properties = classMetadata.Properties; var command = connection.CreateCommand(); var queryBuilder = new StringBuilder("INSERT INTO " + mappingTable + " ( "); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("`" + mappingField + "`, "); } var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString + ") VALUES ("); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; queryBuilder.Append("@" + mappingField + ", "); } tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2); queryBuilder.Length = 0; queryBuilder.Append(tmpString + "); SELECT LAST_INSERT_ID()"); command.CommandText = queryBuilder.ToString(); foreach (var mappingInfo in properties.Values) { var mappingField = mappingInfo.MappingField; var propertyInfo = mappingInfo.PropertyInfo; var propertyType = propertyInfo.PropertyType; object value = propertyInfo.GetValue(o, null); if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal)) { command.Parameters.Add(new MySqlParameter("@" + mappingField, value)); } else { byte[] blob = null; if (value != null) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, value); blob = stream.ToArray(); } } command.Parameters.Add(new MySqlParameter("@" + mappingField, blob)); } } o.Id = (long) command.ExecuteScalar(); UpdateRelations(o, classMetadata, connection, objectGraph); return o.Id; }