Example #1
0
        internal static void UpdateAmountInUserLog(CollectionEntry dailyCollectionAmt)
        {
            string        connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            SqlConnection con     = new SqlConnection(connStr);

            try
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("USER_DAILY_AMOUNT_ENTRY", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@USER_ID", dailyCollectionAmt.ID);
                    cmd.Parameters.AddWithValue("@CURRENT_AMOUNT", dailyCollectionAmt.UpdatedAmt);
                    cmd.ExecuteNonQuery();
                }
                con.Close();
                MessageBox.Show("Data Saved Successfully.");
            }
            catch (DbException dbException)
            {
                MessageBox.Show("Error!! DB Exception UpdateAmountInUserLog");
                ExceptionHandler.HandleException(dbException);
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error!! General Exception UpdateAmountInUserLog");
                ExceptionHandler.HandleException(exception);
            }
            finally
            {
                con.Close();
            }
        }
Example #2
0
        // GET: CollectionEntry/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            try
            {
                CollectionEntry      collectionEntry = _collectionManager.RetreiveCollectionEntryByID(id);
                CollectionEntryModel model           = new CollectionEntryModel
                {
                    CollectionID  = collectionEntry.CollectionID,
                    CreatureID    = collectionEntry.CreatureID,
                    Name          = collectionEntry.Name,
                    Level         = collectionEntry.Level,
                    Health        = collectionEntry.Health,
                    Stamina       = collectionEntry.Stamina,
                    Oxygen        = collectionEntry.Oxygen,
                    Food          = collectionEntry.Food,
                    Weight        = collectionEntry.Weight,
                    BaseDamage    = collectionEntry.BaseDamage,
                    MovementSpeed = collectionEntry.MovementSpeed,
                    Torpor        = collectionEntry.Torpor,
                    Imprint       = collectionEntry.Imprint,
                    Active        = collectionEntry.Active
                };
                ViewBag.Creatures = _collectionManager.RetrieveCreatures();
                return(View(model));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Index", "Error", new { message = ex.Message, stackTrace = ex.StackTrace }));
            }
        }
        protected static ICollectionPersister GetLoadedCollectionPersister(IPersistentCollection collection,
                                                                           IEventSource source)
        {
            CollectionEntry ce = source.PersistenceContext.GetCollectionEntry(collection);

            return(ce == null ? null : ce.LoadedPersister);
        }
Example #4
0
        internal static void AccountCollectionEntry(CollectionEntry dailyCollectionAmt)
        {
            string        connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            SqlConnection con     = new SqlConnection(connStr);

            try
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("ACCOUNT_COLLECTION_ENTRY", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ENTRY_DATE", dailyCollectionAmt.EntryDate);
                    cmd.Parameters.AddWithValue("@COLLECTION_AMOUNT", dailyCollectionAmt.CurrentAmt);
                    cmd.ExecuteNonQuery();
                }
                con.Close();
                MessageBox.Show("Data Saved Successfully.");
            }
            catch (DbException dbException)
            {
                MessageBox.Show("Error!! DB Exception AccountCollectionEntry");
                ExceptionHandler.HandleException(dbException);
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error!! General Exception AccountCollectionEntry");
                ExceptionHandler.HandleException(exception);
            }
            finally
            {
                con.Close();
            }
        }
Example #5
0
 /// <summary> Called by the <tt>Count</tt> property</summary>
 protected virtual bool ReadSize()
 {
     if (!initialized)
     {
         if (cachedSize != -1 && !HasQueuedOperations)
         {
             return(true);
         }
         else
         {
             ThrowLazyInitializationExceptionIfNotConnected();
             CollectionEntry      entry     = session.PersistenceContext.GetCollectionEntry(this);
             ICollectionPersister persister = entry.LoadedPersister;
             if (persister.IsExtraLazy)
             {
                 if (HasQueuedOperations)
                 {
                     session.Flush();
                 }
                 cachedSize = persister.GetSize(entry.LoadedKey, session);
                 return(true);
             }
         }
     }
     Read();
     return(false);
 }
Example #6
0
        ��������private void FlushCollections(IEventSource session)
        ��������
        {
            ������������log.Debug("Processing unreferenced collections");
            �
            ������������ICollection list = IdentityMap.Entries(session.PersistenceContext.CollectionEntries);

            ������������foreach(DictionaryEntry me in list)
            ������������ {
                ����������������CollectionEntry ce = (CollectionEntry)me.Value;

                ����������������if(!ce.IsReached && !ce.IsIgnore)
                ���������������� {
                    ��������������������Collections.ProcessUnreachableCollection((IPersistentCollection)me.Key, session);
                    ����������������
                }
                ������������
            }
            �
            ������������// Schedule updates to collections:
            �
            ������������log.Debug("Scheduling collection removes/(re)creates/updates");

            �
                ������������list = IdentityMap.Entries(session.PersistenceContext.CollectionEntries);
            ������������ActionQueue actionQueue = session.ActionQueue;

            ������������foreach(DictionaryEntry me in list)
            ������������ {
                ����������������IPersistentCollection coll = (IPersistentCollection)me.Key;
                ����������������CollectionEntry       ce   = (CollectionEntry)me.Value;

                �
                ����������������if(ce.IsDorecreate)
                ����������������
                {
                    ��������������������session.Interceptor.OnCollectionRecreate(coll, ce.CurrentKey);
                    ��������������������actionQueue.AddAction(new CollectionRecreateAction(coll, ce.CurrentPersister, ce.CurrentKey, session));
                    ����������������
                }

                ����������������if(ce.IsDoremove)
                ���������������� {
                    ��������������������session.Interceptor.OnCollectionRemove(coll, ce.LoadedKey);
                    ��������������������actionQueue.AddAction(
                        ������������������������new CollectionRemoveAction(coll, ce.LoadedPersister, ce.LoadedKey, ce.IsSnapshotEmpty(coll), session));
                    ����������������
                }
                ����������������if(ce.IsDoupdate)
                ���������������� {
                    ��������������������session.Interceptor.OnCollectionUpdate(coll, ce.LoadedKey);
                    ��������������������actionQueue.AddAction(
                        ������������������������new CollectionUpdateAction(coll, ce.LoadedPersister, ce.LoadedKey, ce.IsSnapshotEmpty(coll), session));
                    ����������������
                }
                ������������
            }
            ������������actionQueue.SortCollectionActions();
            ��������
        }
Example #7
0
    // Use this for initialization
    void Start()
    {
        redButtons = new List <GameObject> ();
        for (int i = 0; i < Red.transform.childCount; i++)
        {
            redButtons.Add(Red.transform.GetChild(i).gameObject);
        }
        greenButtons = new List <GameObject> ();
        for (int i = 0; i < Green.transform.childCount; i++)
        {
            greenButtons.Add(Green.transform.GetChild(i).gameObject);
        }
        List <CollectionEntry> collection = new List <CollectionEntry> ();
        Status status;

        for (int i = 1; i < 5; i++)
        {
            if (i % 2 == 0)
            {
                status = Status.red;
            }
            else
            {
                status = Status.green;
            }
            CollectionEntry entry = new CollectionEntry("id" + i.ToString(), "text" + i.ToString(), status);
            collection.Add(entry);
        }
        Click = testHandler;
        setData(collection);
    }
Example #8
0
 /// <summary>
 /// Associate the collection with the given session.
 /// </summary>
 /// <param name="session"></param>
 /// <returns>false if the collection was already associated with the session</returns>
 public virtual bool SetCurrentSession(ISessionImplementor session)
 {
     if (session == this.session &&          // NH: added to fix NH-704
         session.PersistenceContext.ContainsCollection(this))
     {
         return(false);
     }
     else
     {
         if (IsConnectedToSession)
         {
             CollectionEntry ce = session.PersistenceContext.GetCollectionEntry(this);
             if (ce == null)
             {
                 throw new HibernateException("Illegal attempt to associate a collection with two open sessions");
             }
             else
             {
                 throw new HibernateException("Illegal attempt to associate a collection with two open sessions: "
                                              + MessageHelper.InfoString(ce.LoadedPersister, ce.LoadedKey, session.Factory));
             }
         }
         else
         {
             this.session = session;
             return(true);
         }
     }
 }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            CollectionEntry entry = (CollectionEntry)PropertyUtility.GetTargetObjectOfProperty(property);

            SerializedProperty    idProperty = property.FindPropertyRelative("field");
            CollectionInformation info       = EnumerableCollection.GetReflectionInformation(entry.IndexType);

            string[] names = info.fieldNames;

            int currentIndex = -1;

            for (int i = 0; i < names.Length; i++)
            {
                if (names[i] == idProperty.stringValue)
                {
                    currentIndex = i;
                    break;
                }
            }
            if (currentIndex == -1)
            {
                currentIndex           = 0;
                idProperty.stringValue = names[EditorGUI.Popup(position, label.text, currentIndex, names)];
                Debug.Log("Assignig default value");
            }

            EditorGUI.BeginChangeCheck();

            idProperty.stringValue = names[EditorGUI.Popup(position, label.text, currentIndex, names)];

            if (EditorGUI.EndChangeCheck())
            {
                entry.entryIndex = -1;
            }
        }
Example #10
0
        public static bool IsCollectionLoaded <TEntity, TCollection>(
            this HookingDbContext ctx,
            TEntity entity,
            Expression <Func <TEntity, IEnumerable <TCollection> > > navigationProperty,
            out CollectionEntry <TEntity, TCollection> collectionEntry)
            where TEntity : BaseEntity
            where TCollection : BaseEntity
        {
            Guard.NotNull(entity, nameof(entity));
            Guard.NotNull(navigationProperty, nameof(navigationProperty));

            collectionEntry = null;
            if (entity.Id == 0)
            {
                return(false);
            }

            var entry = ctx.Entry(entity);

            collectionEntry = entry.Collection(navigationProperty);

            // Avoid System.InvalidOperationException: Member 'IsLoaded' cannot be called for property...
            if (entry.State == EfState.Detached || entry.State == EfState.Added)
            {
                return(collectionEntry.CurrentValue != null);
            }

            return(collectionEntry.IsLoaded);
        }
Example #11
0
    // called on IsInventoriable items...
    public void Insert(Mixin m)
    {
        // if name of IsInventoriable component is unique, insert in unique slot
        // otherwise, stack
        bool found = false;

        foreach (CollectionEntry e in data)
        {
            // if this the right collection
            if (m.name == e.name)
            {
                // insert it
                e.Add(m);
                found = true;
                break;
            }
        }

        // unique item, insert at end of list
        if (!found)
        {
            data.Add(new CollectionEntry());

            // insert at end of data
            int             index = data.Count - 1;
            CollectionEntry e     = data[index];
            e.init();
            e.Add(m);              //add inventory item at end
        }
    }
        public ActionResult DeleteConfirmed(string hashControlValue)
        {
            CollectionEntry collectionEntry = db.CollectionEntry.Where(c => c.HashControlValue == hashControlValue).FirstOrDefault();//.Find(id);

            db.CollectionEntry.Remove(collectionEntry);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public static List <CollectionEntry> RetrieveCollectionEntriesByCollectionId(int id)
        {
            var entries = new List <CollectionEntry>();

            var conn = DBConnection.GetDBConnection();

            var cmdText = @"sp_select_collection_entries_by_active";
            var cmd     = new SqlCommand(cmdText, conn);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@CollectionID", id);
            cmd.Parameters.AddWithValue("@Active", true);
            try
            {
                conn.Open();
                var reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var entry = new CollectionEntry()
                        {
                            CollectionEntryID = reader.GetInt32(0),
                            CollectionID      = reader.GetInt32(1),
                            CreatureID        = reader.GetString(2),
                            Name          = reader.GetString(3),
                            Level         = reader.GetInt32(4),
                            Health        = reader.GetInt32(5),
                            Stamina       = reader.GetInt32(6),
                            Oxygen        = reader.GetInt32(7),
                            Food          = reader.GetInt32(8),
                            Weight        = reader.GetInt32(9),
                            BaseDamage    = reader.GetInt32(10),
                            MovementSpeed = reader.GetInt32(11),
                            Torpor        = reader.GetInt32(12),
                            Imprint       = reader.GetInt32(13),
                            Active        = reader.GetBoolean(14)
                        };

                        entries.Add(entry);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }


            return(entries);
        }
Example #14
0
        public void OnPreRemoveCollection(PreCollectionRemoveEvent evt)
        {
            CollectionEntry collectionEntry = GetCollectionEntry(evt);

            if (collectionEntry != null && !collectionEntry.LoadedPersister.IsInverse)
            {
                OnCollectionAction(evt, null, collectionEntry.Snapshot, collectionEntry);
            }
        }
Example #15
0
 public TweetEventArgs(CollectionEntry collectionEntry, long userId, List <string> parameter,
                       bool streaming = false)
 {
     Type            = TypeEnum.CollectionEntry;
     CollectionEntry = collectionEntry;
     UserId          = userId;
     Parameter       = parameter;
     Streaming       = streaming;
 }
Example #16
0
        public void OnPostRecreateCollection(PostCollectionRecreateEvent evt)
        {
            CollectionEntry collectionEntry = GetCollectionEntry(evt);

            if (!collectionEntry.LoadedPersister.IsInverse)
            {
                OnCollectionAction(evt, evt.Collection, null, collectionEntry);
            }
        }
Example #17
0
        private async Task EndLoadingCollectionAsync(LoadingCollectionEntry lce, ICollectionPersister persister,
                                                     Action <CachePutData> cacheBatchingHandler, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (log.IsDebugEnabled())
            {
                log.Debug("ending loading collection [{0}]", lce);
            }

            var persistenceContext = LoadContext.PersistenceContext;
            var session            = persistenceContext.Session;

            bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled;
            var  stopWath     = new Stopwatch();

            if (statsEnabled)
            {
                stopWath.Start();
            }

            bool hasNoQueuedAdds = lce.Collection.EndRead(persister);             // warning: can cause a recursive calls! (proxy initialization)

            if (persister.CollectionType.HasHolder())
            {
                persistenceContext.AddCollectionHolder(lce.Collection);
            }

            CollectionEntry ce = persistenceContext.GetCollectionEntry(lce.Collection);

            if (ce == null)
            {
                ce = persistenceContext.AddInitializedCollection(persister, lce.Collection, lce.Key);
            }
            else
            {
                ce.PostInitialize(lce.Collection, persistenceContext);
            }

            bool addToCache = hasNoQueuedAdds && persister.HasCache &&
                              session.CacheMode.HasFlag(CacheMode.Put) && !ce.IsDoremove;   // and this is not a forced initialization during flush

            if (addToCache)
            {
                await(AddCollectionToCacheAsync(lce, persister, cacheBatchingHandler, cancellationToken)).ConfigureAwait(false);
            }

            if (log.IsDebugEnabled())
            {
                log.Debug("collection fully initialized: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session));
            }

            if (statsEnabled)
            {
                stopWath.Stop();
                session.Factory.StatisticsImplementor.LoadCollection(persister.Role, stopWath.Elapsed);
            }
        }
Example #18
0
        public void OnPreUpdateCollection(PreCollectionUpdateEvent evt)
        {
            CollectionEntry collectionEntry = GetCollectionEntry(evt);

            if (!collectionEntry.LoadedPersister.IsInverse)
            {
                OnCollectionAction(evt, evt.Collection, collectionEntry.Snapshot, collectionEntry);
            }
        }
        public static int UpdateCollectionEntry(CollectionEntry updateEntry, CollectionEntry collectionEntry)
        {
            int result = 0;

            var conn    = DBConnection.GetDBConnection();
            var cmdText = @"sp_update_collection_entry";
            var cmd     = new SqlCommand(cmdText, conn);

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@CollectionEntryID", collectionEntry.CollectionEntryID);
            cmd.Parameters.AddWithValue("@OldCreatureID", collectionEntry.CreatureID);
            cmd.Parameters.AddWithValue("@NewCreatureID", updateEntry.CreatureID);
            cmd.Parameters.AddWithValue("@OldName", collectionEntry.Name);
            cmd.Parameters.AddWithValue("@NewName", updateEntry.Name);
            cmd.Parameters.AddWithValue("@OldLevel", collectionEntry.Level);
            cmd.Parameters.AddWithValue("@NewLevel", updateEntry.Level);
            cmd.Parameters.AddWithValue("@OldHealth", collectionEntry.Health);
            cmd.Parameters.AddWithValue("@NewHealth", updateEntry.Health);
            cmd.Parameters.AddWithValue("@OldStamina", collectionEntry.Stamina);
            cmd.Parameters.AddWithValue("@NewStamina", updateEntry.Stamina);
            cmd.Parameters.AddWithValue("@OldOxygen", collectionEntry.Oxygen);
            cmd.Parameters.AddWithValue("@NewOxygen", updateEntry.Oxygen);
            cmd.Parameters.AddWithValue("@OldFood", collectionEntry.Food);
            cmd.Parameters.AddWithValue("@NewFood", updateEntry.Food);
            cmd.Parameters.AddWithValue("@OldWeight", collectionEntry.Weight);
            cmd.Parameters.AddWithValue("@NewWeight", updateEntry.Weight);
            cmd.Parameters.AddWithValue("@OldBaseDamage", collectionEntry.BaseDamage);
            cmd.Parameters.AddWithValue("@NewBaseDamage", updateEntry.BaseDamage);
            cmd.Parameters.AddWithValue("@OldMovementSpeed", collectionEntry.MovementSpeed);
            cmd.Parameters.AddWithValue("@NewMovementSpeed", updateEntry.MovementSpeed);
            cmd.Parameters.AddWithValue("@OldTorpor", collectionEntry.Torpor);
            cmd.Parameters.AddWithValue("@NewTorpor", updateEntry.Torpor);
            cmd.Parameters.AddWithValue("@OldImprint", collectionEntry.Imprint);
            cmd.Parameters.AddWithValue("@NewImprint", updateEntry.Imprint);


            try
            {
                conn.Open();

                result = cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                conn.Close();
            }

            return(result);
        }
Example #20
0
        public virtual async Task LoadCollectionAsync <TProperty>(TEntity entity, Expression <Func <TEntity, IEnumerable <TProperty> > > childs, CancellationToken cancellationToken) where TProperty : class
        {
            Attach(entity);

            CollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(childs);

            if (collection.IsLoaded == false)
            {
                await collection.LoadAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Example #21
0
        private void EndLoadingCollection(LoadingCollectionEntry lce, ICollectionPersister persister)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("ending loading collection [" + lce + "]");
            }
            ISessionImplementor session = LoadContext.PersistenceContext.Session;
            EntityMode          em      = session.EntityMode;

            bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled;
            var  stopWath     = new Stopwatch();

            if (statsEnabled)
            {
                stopWath.Start();
            }

            bool hasNoQueuedAdds = lce.Collection.EndRead(persister);             // warning: can cause a recursive calls! (proxy initialization)

            if (persister.CollectionType.HasHolder(em))
            {
                LoadContext.PersistenceContext.AddCollectionHolder(lce.Collection);
            }

            CollectionEntry ce = LoadContext.PersistenceContext.GetCollectionEntry(lce.Collection);

            if (ce == null)
            {
                ce = LoadContext.PersistenceContext.AddInitializedCollection(persister, lce.Collection, lce.Key);
            }
            else
            {
                ce.PostInitialize(lce.Collection);
            }

            bool addToCache = hasNoQueuedAdds && persister.HasCache &&
                              ((session.CacheMode & CacheMode.Put) == CacheMode.Put) && !ce.IsDoremove;   // and this is not a forced initialization during flush

            if (addToCache)
            {
                AddCollectionToCache(lce, persister);
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("collection fully initialized: " + MessageHelper.InfoString(persister, lce.Key, session.Factory));
            }

            if (statsEnabled)
            {
                stopWath.Stop();
                session.Factory.StatisticsImplementor.LoadCollection(persister.Role, stopWath.Elapsed);
            }
        }
        public PersistentCollectionChangeWorkUnit(ISessionImplementor sessionImplementor, String entityName,
                                                  AuditConfiguration auditCfg, IPersistentCollection collection,
                                                  CollectionEntry collectionEntry, Object snapshot, Object id,
                                                  String referencingPropertyName)
            : base(sessionImplementor, entityName, auditCfg,
                   new PersistentCollectionChangeWorkUnitId(id, collectionEntry.Role))
        {
            this.ReferencingPropertyName = referencingPropertyName;

            collectionChanges = auditCfg.EntCfg[EntityName].PropertyMapper
                                .MapCollectionChanges(referencingPropertyName, collection, snapshot, id);
        }
Example #23
0
        public virtual void LoadCollection <TProperty>(TEntity entity, Expression <Func <TEntity, IEnumerable <TProperty> > > childs)
            where TProperty : class
        {
            Attach(entity);

            CollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(childs);

            if (collection.IsLoaded == false)
            {
                collection.Load();
            }
        }
Example #24
0
        /// <summary> Try to initialize a collection from the cache</summary>
        private async Task <bool> InitializeCollectionFromCacheAsync(
            object collectionKey, ICollectionPersister persister, IPersistentCollection collection,
            ISessionImplementor source, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (!(source.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(source))
            {
                log.Debug("disregarding cached version (if any) of collection due to enabled filters ");
                return(false);
            }

            bool useCache = persister.HasCache && source.CacheMode.HasFlag(CacheMode.Get);

            if (!useCache)
            {
                return(false);
            }

            var batchSize = persister.GetBatchSize();

            if (batchSize > 1 && persister.Cache.PreferMultipleGet())
            {
                var collectionEntries = new CollectionEntry[batchSize];
                // The first item in the array is the item that we want to load
                var collectionBatch = await(source.PersistenceContext.BatchFetchQueue
                                            .GetCollectionBatchAsync(persister, collectionKey, batchSize, false, collectionEntries, cancellationToken)).ConfigureAwait(false);
                // Ignore null values as the retrieved batch may contains them when there are not enough
                // uninitialized collection in the queue
                var keys = new List <CacheKey>(batchSize);
                for (var i = 0; i < collectionBatch.Length; i++)
                {
                    var key = collectionBatch[i];
                    if (key == null)
                    {
                        break;
                    }
                    keys.Add(source.GenerateCacheKey(key, persister.KeyType, persister.Role));
                }
                var cachedObjects = await(persister.Cache.GetManyAsync(keys.ToArray(), source.Timestamp, cancellationToken)).ConfigureAwait(false);
                for (var i = 1; i < cachedObjects.Length; i++)
                {
                    var coll = source.PersistenceContext.BatchFetchQueue.GetBatchLoadableCollection(persister, collectionEntries[i]);
                    await(AssembleAsync(keys[i], cachedObjects[i], persister, source, coll, collectionBatch[i], false, cancellationToken)).ConfigureAwait(false);
                }
                return(await(AssembleAsync(keys[0], cachedObjects[0], persister, source, collection, collectionKey, true, cancellationToken)).ConfigureAwait(false));
            }

            var cacheKey     = source.GenerateCacheKey(collectionKey, persister.KeyType, persister.Role);
            var cachedObject = await(persister.Cache.GetAsync(cacheKey, source.Timestamp, cancellationToken)).ConfigureAwait(false);

            return(await(AssembleAsync(cacheKey, cachedObject, persister, source, collection, collectionKey, true, cancellationToken)).ConfigureAwait(false));
        }
 public static void Reload(this CollectionEntry source)
 {
     if (source.CurrentValue != null)
     {
         foreach (var item in source.CurrentValue)
         {
             source.EntityEntry.Context.Entry(item).State = EntityState.Detached;
         }
         source.CurrentValue = null;
     }
     source.IsLoaded = false;
     source.Load();
 }
Example #26
0
 internal CollectionEntry(
     CollectionEntry <T> .GetMembersDelegate getMembers,
     CollectionEntry <T> .GetMemberDelegate getMember,
     bool shouldReplicateWhenReturning,
     bool shouldCloneWhenReturning,
     string collectionNameForTracing)
 {
     this.getMembers = getMembers;
     this.getMember  = getMember;
     this.shouldReplicateWhenReturning = shouldReplicateWhenReturning;
     this.shouldCloneWhenReturning     = shouldCloneWhenReturning;
     this.collectionNameForTracing     = collectionNameForTracing;
 }
        // GET: CollectionEntries/Details/5
        public ActionResult Details(string hashControlValue)
        {
            if (hashControlValue == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CollectionEntry collectionEntry = db.CollectionEntry.Where(c => c.HashControlValue == hashControlValue).FirstOrDefault();//.Find(id);

            if (collectionEntry == null)
            {
                return(HttpNotFound());
            }
            return(View(collectionEntry));
        }
Example #28
0
        �������� /// <summary>
        �������� /// 1. Recreate the collection key -> collection map
        �������� /// 2. rebuild the collection entries
        �������� /// 3. call Interceptor.postFlush()
        �������� /// </summary>
        ��������protected virtual void PostFlush(ISessionImplementor session)
        ��������
        {
            ������������if(log.IsDebugEnabled)
            ������������ {
                ����������������log.Debug("post flush");
                ������������
            }
            �
            ������������IPersistenceContext persistenceContext = session.PersistenceContext;

            ������������persistenceContext.CollectionsByKey.Clear();
            ������������persistenceContext.BatchFetchQueue.ClearSubselects();
            ������������ //the database has changed now, so the subselect results need to be invalidated
            �
            ������������ // NH Different implementation: In NET an iterator is immutable;
            ������������ // we need something to hold the persistent collection to remove, and it must be less intrusive as possible
            ������������IDictionary cEntries = persistenceContext.CollectionEntries;
            ������������List <IPersistentCollection> keysToRemove = new List <IPersistentCollection>(cEntries.Count);

            ������������foreach(DictionaryEntry me in cEntries)
            ������������ {
                ����������������CollectionEntry       collectionEntry      = (CollectionEntry)me.Value;
                ����������������IPersistentCollection persistentCollection = (IPersistentCollection)me.Key;

                ����������������collectionEntry.PostFlush(persistentCollection);
                ����������������if(collectionEntry.LoadedPersister == null)
                ���������������� {
                    ��������������������keysToRemove.Add(persistentCollection);
                    ����������������
                }
                ����������������else
                ���������������� {
                    ��������������������//otherwise recreate the mapping between the collection and its key
                    ��������������������CollectionKey collectionKey =
                        ������������������������new CollectionKey(collectionEntry.LoadedPersister, collectionEntry.LoadedKey, session.EntityMode);

                    ��������������������persistenceContext.CollectionsByKey[collectionKey] = persistentCollection;
                    ����������������
                }
                ������������
            }
            ������������foreach(IPersistentCollection key in keysToRemove)
            ������������ {
                ����������������persistenceContext.CollectionEntries.Remove(key);
                ������������
            }
            ������������session.Interceptor.PostFlush((ICollection)persistenceContext.EntitiesByKey.Values);
            ��������
        }
Example #29
0
        //1. record the collection role that this collection is referenced by
        //2. decide if the collection needs deleting/creating/updating (but don't actually schedule the action yet)
        private static void PrepareCollectionForUpdate(IPersistentCollection coll, CollectionEntry entry)
        {
            if (entry.IsProcessed)
                throw new AssertionFailure("collection was processed twice by flush()");

            entry.IsProcessed = true;

            ICollectionPersister loadedPersister = entry.LoadedPersister;
            ICollectionPersister currentPersister = entry.CurrentPersister;
            if (loadedPersister != null || currentPersister != null)
            {
                // it is or was referenced _somewhere_
                bool ownerChanged = loadedPersister != currentPersister ||
                    !currentPersister.KeyType.IsEqual(entry.LoadedKey, entry.CurrentKey, EntityMode.Poco);

                if (ownerChanged)
                {
                    // do a check
                    bool orphanDeleteAndRoleChanged = loadedPersister != null &&
                        currentPersister != null && loadedPersister.HasOrphanDelete;

                    if (orphanDeleteAndRoleChanged)
                    {
                        throw new HibernateException("Don't change the reference to a collection with cascade=\"all-delete-orphan\": " + loadedPersister.Role);
                    }

                    // do the work
                    if (currentPersister != null)
                    {
                        entry.IsDorecreate = true; // we will need to create new entries
                    }

                    if (loadedPersister != null)
                    {
                        entry.IsDoremove = true; // we will need to remove ye olde entries
                        if (entry.IsDorecreate)
                        {
                            log.Debug("Forcing collection initialization");
                            coll.ForceInitialization(); // force initialize!
                        }
                    }
                }
                else if (coll.IsDirty)
                {
                    // else if it's elements changed
                    entry.IsDoupdate = true;
                }
            }
        }
        /// <summary> Try to initialize a collection from the cache</summary>
        private bool InitializeCollectionFromCache(object id, ICollectionPersister persister, IPersistentCollection collection, ISessionImplementor source)
        {
            if (!(source.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(source))
            {
                log.Debug("disregarding cached version (if any) of collection due to enabled filters ");
                return(false);
            }

            bool useCache = persister.HasCache && source.CacheMode.HasFlag(CacheMode.Get);

            if (!useCache)
            {
                return(false);
            }

            var batchSize = persister.GetBatchSize();

            if (batchSize > 1 && persister.Cache.IsBatchingGetSupported())
            {
                var collectionEntries = new CollectionEntry[batchSize];
                // The first item in the array is the item that we want to load
                var collectionBatch = source.PersistenceContext.BatchFetchQueue
                                      .GetCollectionBatch(persister, id, batchSize, false, collectionEntries);
                // Ignore null values as the retrieved batch may contains them when there are not enough
                // uninitialized collection in the queue
                var keys = new List <CacheKey>(batchSize);
                for (var i = 0; i < collectionBatch.Length; i++)
                {
                    var key = collectionBatch[i];
                    if (key == null)
                    {
                        break;
                    }
                    keys.Add(source.GenerateCacheKey(key, persister.KeyType, persister.Role));
                }
                var cachedObjects = persister.Cache.GetMany(keys.ToArray(), source.Timestamp);
                for (var i = 1; i < cachedObjects.Length; i++)
                {
                    var coll = source.PersistenceContext.BatchFetchQueue.GetBatchLoadableCollection(persister, collectionEntries[i]);
                    Assemble(keys[i], cachedObjects[i], persister, source, coll, collectionBatch[i], false);
                }
                return(Assemble(keys[0], cachedObjects[0], persister, source, collection, id, true));
            }

            var cacheKey     = source.GenerateCacheKey(id, persister.KeyType, persister.Role);
            var cachedObject = persister.Cache.Get(cacheKey, source.Timestamp);

            return(Assemble(cacheKey, cachedObject, persister, source, collection, id, true));
        }
        private void EvictCollection(IPersistentCollection collection)
        {
            CollectionEntry ce = (CollectionEntry)Session.PersistenceContext.CollectionEntries[collection];

            Session.PersistenceContext.CollectionEntries.Remove(collection);
            if (log.IsDebugEnabled())
            {
                log.Debug("evicting collection: {0}", MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, Session));
            }
            if (ce.LoadedPersister != null && ce.LoadedKey != null)
            {
                //TODO: is this 100% correct?
                Session.PersistenceContext.CollectionsByKey.Remove(new CollectionKey(ce.LoadedPersister, ce.LoadedKey));
            }
        }
 protected void AddItem(object value, int tag)
 {
     CollectionEntry[] entryArray = this._items;
     for (int i = 0; i < entryArray.Length; i++)
     {
         if (!entryArray[i].HasTarget)
         {
             entryArray[i].Target = value;
             entryArray[i].Tag = tag;
             return;
         }
     }
     int num3 = (5 == entryArray.Length) ? 15 : (entryArray.Length + 15);
     CollectionEntry[] entryArray2 = new CollectionEntry[num3];
     for (int j = 0; j < entryArray.Length; j++)
     {
         entryArray2[j] = entryArray[j];
     }
     entryArray2[entryArray.Length].Target = value;
     entryArray2[entryArray.Length].Tag = tag;
     this._items = entryArray2;
 }
		/// <summary> Add an collection to the cache, with a given collection entry. </summary>
		/// <param name="coll">The collection for which we are adding an entry.</param>
		/// <param name="entry">The entry representing the collection. </param>
		/// <param name="key">The key of the collection's entry. </param>
		private void AddCollection(IPersistentCollection coll, CollectionEntry entry, object key)
		{
			collectionEntries[coll] = entry;
			CollectionKey collectionKey = new CollectionKey(entry.LoadedPersister, key, session.EntityMode);
			IPersistentCollection tempObject;
			collectionsByKey.TryGetValue(collectionKey, out tempObject);
			collectionsByKey[collectionKey] = coll;
			IPersistentCollection old = tempObject;
			if (old != null)
			{
				if (old == coll)
				{
					throw new AssertionFailure("bug adding collection twice");
				}
				// or should it actually throw an exception?
				old.UnsetSession(session);
				collectionEntries.Remove(old);
				// watch out for a case where old is still referenced
				// somewhere in the object graph! (which is a user error)
			}
		}
		/// <summary> add a detached uninitialized collection</summary>
		public void AddUninitializedDetachedCollection(ICollectionPersister persister, IPersistentCollection collection)
		{
			CollectionEntry ce = new CollectionEntry(persister, collection.Key);
			AddCollection(collection, ce, collection.Key);
		}
		/// <summary> add a collection we just loaded up (still needs initializing)</summary>
		public void AddUninitializedCollection(ICollectionPersister persister, IPersistentCollection collection, object id)
		{
			CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
			AddCollection(collection, ce, id);
		}
		/// <summary> Get the ID for the entity that owned this persistent collection when it was loaded </summary>
		/// <param name="ce">The collection entry </param>
		/// <returns> the owner ID if available from the collection's loaded key; otherwise, returns null </returns>
		private object GetLoadedCollectionOwnerIdOrNull(CollectionEntry ce)
		{
			if (ce == null || ce.LoadedKey == null || ce.LoadedPersister == null)
			{
				return null;
			}
			// TODO: an alternative is to check if the owner has changed; if it hasn't then
			// get the ID from collection.getOwner()
			return ce.LoadedPersister.CollectionType.GetIdOfOwnerOrNull(ce.LoadedKey, session);
		}
 /// <summary> add a collection we just loaded up (still needs initializing)</summary>
 public void AddUninitializedCollection(ICollectionPersister persister, IPersistentCollection collection, object id)
 {
     CollectionEntry ce = new CollectionEntry(persister, id, flushing);
     collection.CollectionSnapshot = ce; // NH Different behavior
     AddCollection(collection, ce, id);
 }
		/// <summary> add a collection we just pulled out of the cache (does not need initializing)</summary>
		public CollectionEntry AddInitializedCollection(ICollectionPersister persister, IPersistentCollection collection,
																										object id)
		{
			CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
			ce.PostInitialize(collection);
			AddCollection(collection, ce, id);
			return ce;
		}
		private void AddUninitializedDetachedCollection( PersistentCollection collection, ICollectionPersister persister, object id )
		{
			CollectionEntry ce = new CollectionEntry( persister, id );
			collection.CollectionSnapshot = ce;
			AddCollection( collection, ce, id );
		}
 /// <summary> Add a collection to the cache, creating a new collection entry for it </summary>
 /// <param name="collection">The collection for which we are adding an entry. </param>
 private CollectionEntry AddCollection(IPersistentCollection collection)
 {
     CollectionEntry ce = new CollectionEntry(collection);
     collectionEntries[collection] = ce;
     collection.CollectionSnapshot = ce;
     return ce;
 }
 /// <summary> add a collection we just pulled out of the cache (does not need initializing)</summary>
 public CollectionEntry AddInitializedCollection(ICollectionPersister persister, IPersistentCollection collection,
     object id)
 {
     CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
     ce.PostInitialize(collection);
     collection.CollectionSnapshot = ce; // NH Different behavior
     AddCollection(collection, ce, id);
     return ce;
 }
		private void AddCollection( PersistentCollection collection, CollectionEntry entry, object key )
		{
			collectionEntries[ collection ] = entry;

			CollectionKey ck = new CollectionKey( entry.loadedPersister, key );
			PersistentCollection old = ( PersistentCollection ) collectionsByKey[ ck ];
			collectionsByKey[ ck ] = collection;

			if( old != null )
			{
				if( old == collection )
				{
					throw new AssertionFailure( "collection added twice" );
				}
				// or should it actually throw an exception?
				old.UnsetSession( this );
				collectionEntries.Remove( old );
				// watch out for a case where old is still referenced
				// somewhere in the object graph! (which is a user error)
			}
		}
 /// <summary> 
 /// add an (initialized) collection that was created by another session and passed
 /// into update() (ie. one with a snapshot and existing state on the database)
 /// </summary>
 public void AddInitializedDetachedCollection(IPersistentCollection collection,
     ICollectionSnapshot snapshot)
 {
     if (snapshot.WasDereferenced)
     {
         //treat it just like a new collection
         AddCollection(collection);
     }
     else
     {
         CollectionEntry ce = new CollectionEntry(snapshot, session.Factory);
         collection.CollectionSnapshot = ce; // NH Different behavior
         AddCollection(collection, ce, ce.Key);
     }
 }
		/// <summary> Add a collection to the cache, creating a new collection entry for it </summary>
		/// <param name="collection">The collection for which we are adding an entry. </param>
		/// <param name="persister">The collection persister </param>
		private void AddCollection(IPersistentCollection collection, ICollectionPersister persister)
		{
			CollectionEntry ce = new CollectionEntry(persister, collection);
			collectionEntries[collection] = ce;
		}
		/// <summary> 
		/// add an (initialized) collection that was created by another session and passed
		/// into update() (ie. one with a snapshot and existing state on the database)
		/// </summary>
		public void AddInitializedDetachedCollection(ICollectionPersister collectionPersister, IPersistentCollection collection)
		{
			if (collection.IsUnreferenced)
			{
				//treat it just like a new collection
				AddCollection(collection, collectionPersister);
			}
			else
			{
				CollectionEntry ce = new CollectionEntry(collection, session.Factory);
				AddCollection(collection, ce, collection.Key);
			}
		}
		/// <summary>
		/// 1. record the collection role that this collection is referenced by
		/// 2. decide if the collection needs deleting/creating/updating (but
		///    don't actually schedule the action yet)
		/// </summary>
		/// <param name="coll"></param>
		/// <param name="entry"></param>
		private void PrepareCollectionForUpdate( PersistentCollection coll, CollectionEntry entry )
		{
			if( entry.processed )
			{
				throw new AssertionFailure( "collection was processed twice by flush()" );
			}

			entry.processed = true;

			// it is or was referenced _somewhere_
			if( entry.loadedPersister != null || entry.currentPersister != null )
			{
				if(
					entry.loadedPersister != entry.currentPersister || //if either its role changed,
						!entry.currentPersister.KeyType.Equals( entry.loadedKey, entry.currentKey ) // or its key changed
					)
				{
					// do a check
					if(
						entry.loadedPersister != null &&
							entry.currentPersister != null &&
							entry.loadedPersister.HasOrphanDelete )
					{
						throw new HibernateException( "Don't dereference a collection with cascade=\"all-delete-orphan\": " + coll.CollectionSnapshot.Role );
					}

					// do the work
					if( entry.currentPersister != null )
					{
						entry.dorecreate = true; //we will need to create new entries
					}

					if( entry.loadedPersister != null )
					{
						entry.doremove = true; // we will need to remove the old entres
						if( entry.dorecreate )
						{
							log.Debug( "forcing collection initialization" );
							coll.ForceInitialization();
						}
					}
				}
				else if( entry.Dirty )
				{
					// else if it's elements changed
					entry.doupdate = true;
				}
			}
		}
		private object GetCollectionOwner( CollectionEntry ce )
		{
			return GetCollectionOwner( ce.loadedKey, ce.loadedPersister );
		}
		/// <summary>
		/// add a collection we just pulled out of the cache (does not need initializing)
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="persister"></param>
		/// <param name="id"></param>
		public CollectionEntry AddInitializedCollection( PersistentCollection collection, ICollectionPersister persister, object id )
		{
			CollectionEntry ce = new CollectionEntry( persister, id, flushing );
			ce.PostInitialize( collection );
			collection.CollectionSnapshot = ce;
			AddCollection( collection, ce, id );

			return ce;
		}
		/// <summary>
		/// Add an (initialized) collection that was created by another session and passed
		/// into update() (i.e. one with a snapshot and existing state on the database)
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="cs"></param>
		private void AddInitializedDetachedCollection( PersistentCollection collection, ICollectionSnapshot cs )
		{
			if( cs.WasDereferenced )
			{
				AddCollection( collection );
			}
			else
			{
				CollectionEntry ce = new CollectionEntry( cs, factory );
				collection.CollectionSnapshot = ce;
				AddCollection( collection, ce, cs.Key );
			}
		}
 /// <summary> add a detached uninitialized collection</summary>
 public void AddUninitializedDetachedCollection(IPersistentCollection collection, ICollectionSnapshot snapshot)
 {
     CollectionEntry ce = new CollectionEntry(snapshot, Session.Factory);
     collection.CollectionSnapshot = ce; // NH Different behavior
     AddCollection(collection, ce, ce.Key);
 }