private void Set(IDbEntity entity, object value)
        {
            IDbEntity    matchedEntity = DbEntityDataBinder.Eval(EntityPath, entity).Entity;
            PropertyInfo property      = matchedEntity.GetType().GetProperty(PropertyName);

            property.SetValue(matchedEntity, value, null);
        }
Beispiel #2
0
 public virtual void Recycle()
 {
     // clean out state
     DbEntity = null;
     Copy     = null;
     //entityState = DbEntityState.;null
 }
Beispiel #3
0
 public List <DbColumn> GetAllColumns(IDbEntity entity, IDbConnection conn = null)
 {
     using (var con = conn ?? GetConnection())
     {
         return(con.Query <DbColumn>(SqlStatements.GetAllColumns(_dbType), new { DbName = con.Database, Schema = entity.TableSchema, entity.TableName }).ToList());
     }
 }
Beispiel #4
0
 public static void SubmitUpdate2Queue(IDbEntity entity)
 {
     lock (UPDATE_QUEUE)
     {
         UPDATE_QUEUE[entity.GetId()] = entity;
     }
 }
Beispiel #5
0
        public void Insert(NpgsqlConnection dbCon, IDbEntity entity)
        {
            var order   = entity as Order;
            var command = dbCon.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText =
                $"INSERT INTO public.orders (id, \"userId\", \"restaurantId\", \"tableId\", \"creationDateTime\", \"timeToGet\", \"isCompleted\") " +
                $"VALUES" +
                $" ('{order.Id}',{order.UserId}, '{order.RestaurantId}', '{order.TableId}', {order.CreationDateTime}, '{order.TimeToGet}', {order.IsCompleted} )";
            command.ExecuteNonQuery();
            foreach (var dishesId in order.DishesIds)
            {
                using (var con = PostgresConn.GetConn())
                {
                    command             = con.CreateCommand();
                    command.CommandType = CommandType.Text;
                    command.CommandText =
                        $"INSERT INTO public.orderswithdishes (\"orderId\", \"dishId\") " +
                        $"VALUES" +
                        $" ('{order.Id}', '{dishesId}' )";
                    command.ExecuteNonQuery();
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Wire up the references of an entity
        /// </summary>
        /// <param name="entity"></param>
        private void InjectMultiReferences(IDbEntity entity)
        {
            Type type = entity.GetType();

            EntityInfo infos = GetEntityInfo(type);


            bool changed = false;

            // single refs
            foreach (MultipleReferenceProperty referenceProperty in infos.MultipleReferenceInjectors)
            {
                IList list = (IList)referenceProperty.PropertyAccessor.GetValue(entity);

                if (LoadDbMultiReference(entity, list))
                {
                    changed = true;
                }
            }

            // trigger if event is entity is changed
            if (changed)
            {
                OnEntityChanged?.Invoke(entity);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Loads the refrence for the entity
        /// return true if the entity reference changed
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dbReference"></param>
        /// <returns></returns>
        private bool LoadDbMultiReference(IDbEntity entity, IList dbMultiRefs)
        {
            // if null
            // do nothing
            if (dbMultiRefs == null)
            {
                return(false);
            }

            bool changed = false;

            for (int i = dbMultiRefs.Count - 1; i >= 0; i--)
            {
                IDbReference reference = (IDbReference)dbMultiRefs[i];

                IDbEntity otherRef = FindEntity(reference.EntityType, reference.ReferenceId.Value);

                // if other ref is null
                // that means that the link between the entities is gone
                // so delete from the list
                if (otherRef == null)
                {
                    dbMultiRefs.RemoveAt(i);
                    changed = true;
                }
            }

            return(changed);
        }
 public ForeignEntityCollectionManager(int userId, IDbEntity collectionOwner, Func <ICollection <TEntity> > collection, Action <IDbEntity, TEntity> setForeignKeys)
 {
     _userId         = userId;
     CollectionOwner = collectionOwner;
     _collection     = collection;
     _setForeignKeys = setForeignKeys;
 }
Beispiel #9
0
        /// <summary>
        /// Wire up the references of an entity
        /// </summary>
        /// <param name="entity"></param>
        private void InjectSingleReferences(IDbEntity entity)
        {
            Type entityType = entity.GetType();

            EntityInfo infos = GetEntityInfo(entityType);

            bool changed = false;

            // single refs
            foreach (SingleReferenceProperty referenceProperty in infos.SingleReferenceInjectors)
            {
                IDbReference dbReference = (IDbReference)referenceProperty.PropertyAccessor.GetValue(entity);

                if (LoadSingleDbReference(entityType, entity, dbReference))
                {
                    changed = true;
                }
            }

            // trigger if event is entity is changed
            if (changed)
            {
                OnEntityChanged?.Invoke(entity);
            }
        }
Beispiel #10
0
        private static BinderResult GetEntityGeneric <T>(IDbEntity entity, IEnumerable entities, string path, string collectionPath, string indexers)
            where T : class, IDbEntity
        {
            BinderResult result = null;

            IEnumerable <T> typedEntities = entities as IEnumerable <T>;

            string[] collectionEntityIndexers = indexers.Split(',');
            List <Tuple <string, object> > collectionEntityKeys = new List <Tuple <string, object> >();
            Type type = typeof(T);

            foreach (string indexer in collectionEntityIndexers)
            {
                string[] keyAndValue = indexer.Split('=');
                collectionEntityKeys.Add(new Tuple <string, object>(keyAndValue[0], Convert.ChangeType(keyAndValue[1], type.GetProperty(keyAndValue[0]).GetGetMethod().ReturnType, null)));
            }

            IDbEntity collectionEntity = typedEntities.AsQueryable().WherePrimaryKeysEqual(collectionEntityKeys.ToArray()).SingleOrDefault() as IDbEntity;
            string    actualPath       = path;

            if (collectionEntity != null)
            {
                actualPath = DbEntityUtilities.GenerateCollectionItemPath(collectionPath, collectionEntity.PrimaryKeys, collectionEntity.Guid);
            }
            result = new BinderResult(collectionEntity, path, actualPath);

            return(result);
        }
        private IEnumerable <IDbEntity> RemoveCollectionHandlers(IDbEntity entity, IEnumerable <IDbEntity> entities, string path, string propertyPath, PropertyInfo property)
        {
            // Unsubscribe collection changed listeners
            if (entities.GetType().IsINotifyCollectionChanged())
            {
                NotifyCollectionChangedEventHandler entityCollectionChanged;
                if (_entityCollectionChangedHandlers.TryGetValue(propertyPath, out entityCollectionChanged))
                {
                    (entities as INotifyCollectionChanged).CollectionChanged -= entityCollectionChanged;
                    _entityCollectionChangedHandlers.Remove(propertyPath);
                }
            }

            if (entities.GetType().IsIObservableRangeCollection())
            {
                IObservableRangeCollection c = entities as IObservableRangeCollection;

                EventHandler <DataEventArgs <IEnumerable> > entityCollectionAdded;
                if (_entityCollectionAddedHandlers.TryGetValue(propertyPath, out entityCollectionAdded))
                {
                    c.Added -= entityCollectionAdded;
                    _entityCollectionAddedHandlers.Remove(propertyPath);
                }

                EventHandler <DataEventArgs <IEnumerable> > entityCollectionRemoved;
                if (_entityCollectionRemovedHandlers.TryGetValue(propertyPath, out entityCollectionRemoved))
                {
                    c.Removed -= entityCollectionRemoved;
                    _entityCollectionRemovedHandlers.Remove(propertyPath);
                }
            }
            return(entities);
        }
        private ICollection <PropertyChange> ChangesForNonDeletedEntities(ISet <string> changePathsPrefixes, long utcTimestamp = long.MaxValue)
        {
            // Get all changes for entities that are not deleted
            List <PropertyChange> dbEntityChanges = new List <PropertyChange>(
                _changes
                .Where(c => c.UtcTimestamp <= utcTimestamp)
                .Where(c => !c.IsOrphan(_entity))
                .Where(c =>
            {
                bool returnChange = false;
                if (!string.IsNullOrEmpty(c.EntityPath))
                {
                    bool startsWithPathPrefix = changePathsPrefixes.Any(p => c.EntityPath.StartsWith(p));
                    IDbEntity entity          = DbEntityDataBinder.Eval(c.EntityPath, _entity).Entity;
                    returnChange = startsWithPathPrefix && (!(entity as IDbEntityBasic).IsDeleted || entity.State == EntityState.Persisted);
                }
                return(returnChange);
            }));

            // Get all flat property changes
            dbEntityChanges.AddRange(
                _changes
                .Where(c => string.IsNullOrEmpty(c.EntityPath)));

            return(dbEntityChanges);
        }
 public void Dispose()
 {
     if (!_isDisposing)
     {
         _isDisposing = true;
         _entity      = null;
         _projection  = null;
         _changes.Clear();
         _lastChange = null;
         _validEntitiesProperties.Clear <Type, string>();
         _entityUpdateHandlers.Clear();
         _entityCollectionChangedHandlers.Clear();
         _entityCollectionAddedHandlers.Clear();
         _entityCollectionRemovedHandlers.Clear();
         _entitiesPaths.Clear <string, string>();
         _observableCollectionType = null;
         _emptyObjectArray         = null;
         _validationRulesFilters.Clear();
         _isTracked = null;
         _removeHandlersBeforeRecursionAction           = null;
         _removeHandlersCollectionPropertyAction        = null;
         _createHandlersAfterRecursionAction            = null;
         _createHandlersBeforeCollectionRecursionAction = null;
         _createHandlersAfterCollectionRecursionAction  = null;
         _isDisposing = false;
     }
 }
Beispiel #14
0
 public DbChange(DbChangeType changeType, string affectedTable, IEnumerable <string> affectedColumns, IDbEntity entity)
 {
     ChangeType      = changeType;
     AffectedTable   = affectedTable;
     AffectedColumns = affectedColumns;
     Entity          = entity;
 }
Beispiel #15
0
        private static BinderResult GetEntity(IDbEntity entity, string path)
        {
            Match  match                  = CollectionPathMatch.Match(path);
            string collectionPath         = match.Groups[1].Value;
            string collectionItemIndexers = match.Groups[2].Value;
            string collectionPathSuffix   = match.Groups[3].Value;

            IEnumerable  entities             = entity.Eval(collectionPath) as IEnumerable;
            Type         entityType           = entities.GetType().GetGenericArguments()[0];
            MethodInfo   method               = typeof(DbEntityDataBinder).GetMethod("GetEntityGeneric", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo   generic              = method.MakeGenericMethod(entityType);
            BinderResult collectionItemResult = generic.Invoke(null, new object[] { entity, entities, path, collectionPath, collectionItemIndexers }) as BinderResult;

            if (collectionItemResult.Entity != null && !string.IsNullOrEmpty(collectionPathSuffix) && collectionPathSuffix.Contains("["))
            {
                BinderResult childResult = GetEntity(collectionItemResult.Entity, collectionPathSuffix.Substring(1));
                collectionItemResult.Entity      = childResult.Entity;
                collectionItemResult.ActualPath += childResult.ActualPath;
            }
            else if (collectionItemResult.Entity != null && !string.IsNullOrEmpty(collectionPathSuffix))
            {
                collectionItemResult = new BinderResult(collectionItemResult.Entity.Eval(collectionPathSuffix.Substring(1)) as IDbEntity, path, collectionItemResult.ActualPath + collectionPathSuffix.Substring(1));
            }
            return(collectionItemResult);
        }
Beispiel #16
0
        public AccountOBJ GetAccount(AccountOBJ entity, bool AutoCreate = false)
        {
            IDbEntity that = Get(entity);

            if (that != null)
            {
                return((AccountOBJ)that);
            }

            CHeck();
            Users usr = session.QueryOver <Users>().Where(x => x.UserName == entity.Username).List().FirstOrDefault();

            if (usr != null)
            {
                AccountOBJ account = GetAccountFromDB(usr.UserName);
                ENTITY.Add(account.GetId(), account);
                return(account);
            }
            else
            {
                if (AutoCreate)
                {
                    AccountOBJ user = new AccountOBJ((Users)entity.GetEntity());
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        user.Id = (uint)session.Save(user.GetEntity());
                        transaction.Commit();
                    }
                    return(GetAccount(user));
                }
            }
            return(null);
        }
Beispiel #17
0
 public static object GetPropertyValue(this IDbEntity item, string propertyName)
 {
     if (!CachedProperties.ContainsKey(item.GetType()))
     {
         CachedProperties.Add(item.GetType(), DeepCloner.GetFastDeepClonerProperties(item.GetType()).GroupBy(x => x.Name).Select(x => x.First()).ToDictionary(x => x.Name, x => x));
     }
     return(CachedProperties[item.GetType()][propertyName].GetValue(item));
 }
 public static void UpdatePrimaryKeys(IDictionary <string, Tuple <string, object>[]> pathsAndKeys, IDbEntity entity)
 {
     foreach (KeyValuePair <string, Tuple <string, object>[]> pathAndKeys in pathsAndKeys)
     {
         IDbEntity entityToUpdate = DbEntityDataBinder.Eval(pathAndKeys.Key, entity).Entity;
         UpdatePrimaryKeys(pathAndKeys.Value, entityToUpdate);
     }
 }
Beispiel #19
0
        /// <summary>
        ///     Put a new, <seealso cref="DbEntityState#TRANSIENT" /> object into the cache.
        /// </summary>
        /// <param name="e"> the object to put into the cache </param>
        public virtual void PutTransient(IDbEntity e)
        {
            var cachedDbEntity = new CachedDbEntity();

            cachedDbEntity.Entity      = e;
            cachedDbEntity.EntityState = DbEntityState.Transient;
            PutInternal(cachedDbEntity);
        }
        public void Insert(NpgsqlConnection dbCon, IDbEntity entity)
        {
            var table   = entity as Table;
            var command = dbCon.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText =
                @$ "INSERT INTO public.tables(name, " "tableId" ", " "isFree" ", " "restaurantId" ")
            VALUES ('{table.Name}', '{table.TableId}', {table.IsFree}, '{table.RestaurantId}');";
 private PropertyChange Undo(IDbEntity e, PropertyChange lastChange)
 {
     if (!lastChange.IsOrphan(e) ||
         (lastChange.IsDbEntityEnumerable && lastChange.After == null && lastChange.Before != null))
     {
         lastChange.Revert(e);
     }
     return(MoveLastChange(lastChange));
 }
Beispiel #22
0
 public static IFastDeepClonerProperty GetPrimaryKey(IDbEntity item)
 {
     if (CachedPrimaryKeys.ContainsKey(item.GetType()))
     {
         return(CachedPrimaryKeys[item.GetType()]);
     }
     CachedPrimaryKeys.Add(item.GetType(), DeepCloner.GetFastDeepClonerProperties(item.GetType()).FirstOrDefault(x => x.ContainAttribute <PrimaryKey>()));
     return(CachedPrimaryKeys[item.GetType()]);
 }
Beispiel #23
0
        /// <summary>
        ///     Allows checking whether the provided entity is present in the cache
        ///     and is <seealso cref="DbEntityState#TRANSIENT" />.
        /// </summary>
        /// <param name="dbEntity"> the entity to check </param>
        /// <returns>
        ///     true if the provided entity is present in the cache and is
        ///     <seealso cref="DbEntityState#TRANSIENT" />.
        /// </returns>
        public virtual bool IsTransient(IDbEntity dbEntity)
        {
            var cachedDbEntity = GetCachedEntity(dbEntity);

            if (cachedDbEntity == null)
            {
                return(false);
            }
            return(cachedDbEntity.EntityState == DbEntityState.Transient);
        }
Beispiel #24
0
        private void SerializeEntity()
        {
            IDbEntity entity = GetParameter(Type, EntityParameterKey) as IDbEntity;

            if (entity != null)
            {
                AddParameter(EntityJsonParameterKey, SerializeEntity(entity));
                Parameters.Remove(Type);
            }
        }
Beispiel #25
0
        private static string SerializeEntity(IDbEntity entity)
        {
            string json = DbEntityJsonConvert.SerializePrimaryKeys(entity);

            if (entity.HasChanges)
            {
                json = DbEntityJsonConvert.SerializeEntity(entity, entity.DbEntityChanges());
            }
            return(json);
        }
 public static void DepthFirst(IDbEntity entity,
                               Type projectionType,
                               Action <IDbEntity, string> beforeRecursionAction,
                               Action <IDbEntity, string, string, PropertyInfo> beforePropertyRecursionAction,
                               Func <IDbEntity, IEnumerable <IDbEntity>, string, string, PropertyInfo, IEnumerable <IDbEntity> > beforeCollectionRecursionAction,
                               Action <IDbEntity, IEnumerable <IDbEntity>, string, string, PropertyInfo> afterCollectionRecursionAction,
                               Action <IDbEntity, string> afterRecursionAction)
 {
     DepthFirst(entity, projectionType, ".", beforeRecursionAction, beforePropertyRecursionAction, beforeCollectionRecursionAction, afterCollectionRecursionAction, afterRecursionAction);
 }
Beispiel #27
0
 public DbEntityAssociativeCollectionManager(int userId, IDbEntity associativeCollectionOwner, Func <ICollection <TAssociative> > associativeEntities, Action <IDbEntity, TEntity, TAssociative> setForeignEntities, Action <IDbEntity, TEntity, TAssociative> setForeignKeys, Func <IDbEntity, TAssociative, bool> matchAssociativeEntityOwner, Func <TEntity, TAssociative, bool> matchAssociativeEntity)
 {
     _userId = userId;
     AssociativeCollectionOwner   = associativeCollectionOwner;
     _associativeEntities         = associativeEntities;
     _setForeignEntities          = setForeignEntities;
     _setForeignKeys              = setForeignKeys;
     _matchAssociativeEntityOwner = matchAssociativeEntityOwner;
     _matchAssociativeEntity      = matchAssociativeEntity;
 }
        private void RevertCollectionChange(IDbEntity entity)
        {
            IEnumerable <IDbEntity> entities = GetCollection(entity);
            MethodInfo generic = typeof(PropertyChange)
                                 .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                                 .Single(x => x.Name == "RevertCollectionChange" && x.GetParameters().Length == 1 && x.GetGenericArguments().Count() == 1)
                                 .MakeGenericMethod(entities.GetType().GetGenericArguments()[0]);

            generic.Invoke(this, new object[] { entities });
        }
 public void Revert(IDbEntity entity)
 {
     if (!IsDbEntityEnumerable)
     {
         Set(entity, Before);
     }
     else
     {
         RevertCollectionChange(entity);
     }
 }
 public void Apply(IDbEntity entity)
 {
     if (!IsDbEntityEnumerable)
     {
         Set(entity, After);
     }
     else
     {
         ApplyCollectionChange(entity);
     }
 }
		public override void Save(LibraryContext context, IDbEntity<LibraryContext> current, bool withCommit = true)
		{
			var currentPage = (LibraryPage)current;
			Folders.Save(currentPage.Folders, context);
			Folders.Sort();
			ColumnTitles.Save(currentPage.ColumnTitles, context);
			base.Save(context, current, withCommit);
		}
 public void Create(IDbEntity review)
 {
     _repository.Add((RestaurantReview)review);
 }
		public override void Save(LibraryContext context, IDbEntity<LibraryContext> current, bool withCommit = true)
		{
			var currentFolderLink = (LibraryFolderLink)current;
			Links.Save(currentFolderLink.Links, context);
			base.Save(context, current, withCommit);
		}
 public void ValidateEntity(IDbEntity entity)
 {
     RestaurantReview restaurant = entity as RestaurantReview;
     _repository.Update(restaurant, restaurant.Id);
 }