Exemple #1
0
 public GameList(LoadEvent le)
 {
     InitializeComponent();
     Program.GamesRepository.GameInstalled += new EventHandler(GamesRepository_GameInstalled);
     if (le == LoadEvent.InstallGame)
         Install_Game();
 }
Exemple #2
0
 public GameList(LoadEvent le)
 {
     InitializeComponent();
     Program.GamesRepository.GameInstalled += GamesRepositoryGameInstalled;
     if (le == LoadEvent.InstallGame)
         InstallGame();
 }
Exemple #3
0
        private Status _status; // status of plug-in, does allow to load or not;

        #endregion Fields

        #region Constructors

        public Plugin()
        {
            _name = "";
            _filePath = "";
            _status = PluginForm.Status.Disable;
            _loadEvent = LoadEvent.onClick;
        }
		/// <summary>
		/// Attempts to locate the entity in the session-level cache.
		/// </summary>
		/// <param name="event">The load event </param>
		/// <param name="keyToLoad">The EntityKey representing the entity to be loaded. </param>
		/// <param name="options">The load options. </param>
		/// <returns> The entity from the session-level cache, or null. </returns>
		/// <remarks>
		/// If allowed to return nulls, then if the entity happens to be found in
		/// the session cache, we check the entity type for proper handling
		/// of entity hierarchies.
		/// If checkDeleted was set to true, then if the entity is found in the
		/// session-level cache, it's current status within the session cache
		/// is checked to see if it has previously been scheduled for deletion.
		/// </remarks>
		protected virtual object LoadFromSessionCache(LoadEvent @event, EntityKey keyToLoad, LoadType options)
		{
			ISessionImplementor session = @event.Session;
			object old = session.GetEntityUsingInterceptor(keyToLoad);

			if (old != null)
			{
				// this object was already loaded
				EntityEntry oldEntry = session.PersistenceContext.GetEntry(old);
				if (options.IsCheckDeleted)
				{
					Status status = oldEntry.Status;
					if (status == Status.Deleted || status == Status.Gone)
					{
						return RemovedEntityMarker;
					}
				}
				if (options.IsAllowNulls)
				{
					IEntityPersister persister = GetEntityPersister(@event.Session.Factory, @event.EntityClassName);
					if (!persister.IsInstance(old, @event.Session.EntityMode))
					{
						return InconsistentRTNClassMarker;
					}
				}
				UpgradeLock(old, oldEntry, @event.LockMode, session);
			}
			return old;
		}
		/// <summary>
		/// Coordinates the efforts to load a given entity.  First, an attempt is
		/// made to load the entity from the session-level cache.  If not found there,
		/// an attempt is made to locate it in second-level cache.  Lastly, an
		/// attempt is made to load it directly from the datasource.
		/// </summary>
		/// <param name="event">The load event </param>
		/// <param name="persister">The persister for the entity being requested for load </param>
		/// <param name="keyToLoad">The EntityKey representing the entity to be loaded. </param>
		/// <param name="options">The load options. </param>
		/// <returns> The loaded entity, or null. </returns>
		protected virtual object DoLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
		{
			if (log.IsDebugEnabled)
			{
				log.Debug("attempting to resolve: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
			}

			object entity = LoadFromSessionCache(@event, keyToLoad, options);
			if (entity == RemovedEntityMarker)
			{
				log.Debug("load request found matching entity in context, but it is scheduled for removal; returning null");
				return null;
			}
			if (entity == InconsistentRTNClassMarker)
			{
				log.Debug("load request found matching entity in context, but the matched entity was of an inconsistent return type; returning null");
				return null;
			}
			if (entity != null)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("resolved object in session cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
				}
				return entity;
			}

			entity = LoadFromSecondLevelCache(@event, persister, options);
			if (entity != null)
			{
				if (log.IsDebugEnabled)
				{
					log.Debug("resolved object in second-level cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
				}
				return entity;
			}

			if (log.IsDebugEnabled)
			{
				log.Debug("object not resolved in any cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
			}

			return LoadFromDatasource(@event, persister, keyToLoad, options);
		}
		/// <summary>
		/// If the class to be loaded has been configured with a cache, then lock
		/// given id in that cache and then perform the load.
		/// </summary>
		/// <returns> The loaded entity </returns>
		protected virtual object LockAndLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, ISessionImplementor source)
		{
			ISoftLock sLock = null;
			CacheKey ck;
			if (persister.HasCache)
			{
				ck = new CacheKey(@event.EntityId, persister.IdentifierType, persister.RootEntityName, source.EntityMode, source.Factory);
				sLock = persister.Cache.Lock(ck, null);
			}
			else
			{
				ck = null;
			}

			object entity;
			try
			{
				entity = Load(@event, persister, keyToLoad, options);
			}
			finally
			{
				if (persister.HasCache)
				{
					persister.Cache.Release(ck, sLock);
				}
			}

			object proxy = @event.Session.PersistenceContext.ProxyFor(persister, keyToLoad, entity);

			return proxy;
		}
		/// <summary>
		/// Given that there is a pre-existing proxy.
		/// Initialize it if necessary; narrow if necessary.
		/// </summary>
		private object ReturnNarrowedProxy(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, IPersistenceContext persistenceContext, object proxy)
		{
			log.Debug("entity proxy found in session cache");
			var castedProxy = (INHibernateProxy) proxy;
			ILazyInitializer li = castedProxy.HibernateLazyInitializer;
			if (li.Unwrap)
			{
				return li.GetImplementation();
			}
			object impl = null;
			if (!options.IsAllowProxyCreation)
			{
				impl = Load(@event, persister, keyToLoad, options);
				// NH Different behavior : NH-1252
				if (impl == null && !options.IsAllowNulls)
				{
					@event.Session.Factory.EntityNotFoundDelegate.HandleEntityNotFound(persister.EntityName, keyToLoad.Identifier);
				}
			}
			if (impl == null && !options.IsAllowProxyCreation && options.ExactPersister)
			{
				// NH Different behavior : NH-1252
				return null;
			}
			return persistenceContext.NarrowProxy(castedProxy, persister, keyToLoad, impl);
		}
Exemple #8
0
        private object AssembleCacheEntry(CacheEntry entry, object id, IEntityPersister persister, LoadEvent @event)
        {
            object       optionalObject        = @event.InstanceToLoad;
            IEventSource session               = @event.Session;
            ISessionFactoryImplementor factory = session.Factory;

            if (log.IsDebugEnabled)
            {
                log.Debug("assembling entity from second-level cache: " + MessageHelper.InfoString(persister, id, factory));
            }

            IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass);
            object           result            = optionalObject ?? session.Instantiate(subclassPersister, id);

            // make it circular-reference safe
            TwoPhaseLoad.AddUninitializedCachedEntity(new EntityKey(id, subclassPersister, session.EntityMode), result, subclassPersister, LockMode.None, entry.AreLazyPropertiesUnfetched, entry.Version, session);

            IType[]  types  = subclassPersister.PropertyTypes;
            object[] values = entry.Assemble(result, id, subclassPersister, session.Interceptor, session);             // intializes result by side-effect
            TypeFactory.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session);

            object version = Versioning.GetVersion(values, subclassPersister);

            if (log.IsDebugEnabled)
            {
                log.Debug("Cached Version: " + version);
            }

            IPersistenceContext persistenceContext = session.PersistenceContext;

            persistenceContext.AddEntry(result, Status.Loaded, values, null, id, version, LockMode.None, true, subclassPersister, false, entry.AreLazyPropertiesUnfetched);
            subclassPersister.AfterInitialize(result, entry.AreLazyPropertiesUnfetched, session);
            persistenceContext.InitializeNonLazyCollections();
            // upgrade the lock if necessary:
            //lock(result, lockMode);

            //PostLoad is needed for EJB3
            //TODO: reuse the PostLoadEvent...
            PostLoadEvent postLoadEvent = new PostLoadEvent(session);

            postLoadEvent.Entity    = result;
            postLoadEvent.Id        = id;
            postLoadEvent.Persister = persister;

            IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners;
            for (int i = 0; i < listeners.Length; i++)
            {
                listeners[i].OnPostLoad(postLoadEvent);
            }
            return(result);
        }
Exemple #9
0
        private async Task <object> AssembleCacheEntryAsync(CacheEntry entry, object id, IEntityPersister persister, LoadEvent @event, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            object       optionalObject        = @event.InstanceToLoad;
            IEventSource session               = @event.Session;
            ISessionFactoryImplementor factory = session.Factory;

            if (log.IsDebugEnabled())
            {
                log.Debug("assembling entity from second-level cache: {0}", MessageHelper.InfoString(persister, id, factory));
            }

            IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass);
            object           result            = optionalObject ?? session.Instantiate(subclassPersister, id);

            // make it circular-reference safe
            EntityKey entityKey = session.GenerateEntityKey(id, subclassPersister);

            TwoPhaseLoad.AddUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.None, entry.AreLazyPropertiesUnfetched, entry.Version, session);

            IType[]  types  = subclassPersister.PropertyTypes;
            object[] values = await(entry.AssembleAsync(result, id, subclassPersister, session.Interceptor, session, cancellationToken)).ConfigureAwait(false);              // intializes result by side-effect
            TypeHelper.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session);

            object version = Versioning.GetVersion(values, subclassPersister);

            if (log.IsDebugEnabled())
            {
                log.Debug("Cached Version: {0}", version);
            }

            IPersistenceContext persistenceContext = session.PersistenceContext;
            bool isReadOnly = session.DefaultReadOnly;

            if (persister.IsMutable)
            {
                object proxy = persistenceContext.GetProxy(entityKey);
                if (proxy != null)
                {
                    // this is already a proxy for this impl
                    // only set the status to read-only if the proxy is read-only
                    isReadOnly = ((INHibernateProxy)proxy).HibernateLazyInitializer.ReadOnly;
                }
            }
            else
            {
                isReadOnly = true;
            }

            persistenceContext.AddEntry(
                result,
                isReadOnly ? Status.ReadOnly : Status.Loaded,
                values,
                null,
                id,
                version,
                LockMode.None,
                true,
                subclassPersister,
                false,
                entry.AreLazyPropertiesUnfetched);

            subclassPersister.AfterInitialize(result, entry.AreLazyPropertiesUnfetched, session);
            await(persistenceContext.InitializeNonLazyCollectionsAsync(cancellationToken)).ConfigureAwait(false);
            // upgrade the lock if necessary:
            //lock(result, lockMode);

            //PostLoad is needed for EJB3
            //TODO: reuse the PostLoadEvent...
            PostLoadEvent postLoadEvent = new PostLoadEvent(session);

            postLoadEvent.Entity    = result;
            postLoadEvent.Id        = id;
            postLoadEvent.Persister = persister;

            IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners;
            for (int i = 0; i < listeners.Length; i++)
            {
                listeners[i].OnPostLoad(postLoadEvent);
            }
            return(result);
        }
 public void ReverseLoad(LoadEvent loadEvent)
 {
 }
 public void HandleLoad(LoadEvent loadEvent)
 {
 }
 private void ProcessLoadEvent(LoadEvent loadEvent)
 {
     //Turn Room On/Off based on event
 }
Exemple #13
0
 protected override object DoLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
 {
     return(base.DoLoad(@event, persister, keyToLoad, options));
 }
 /// <summary>
 /// The handler that creates a new loaded view
 /// </summary>
 /// <param name="message">Not used</param>
 public void Handle(LoadEvent message)
 {
     ActivateItem(new LoadViewModel(_events));
 }
		private object AssembleCacheEntry(CacheEntry entry, object id, IEntityPersister persister, LoadEvent @event)
		{
			object optionalObject = @event.InstanceToLoad;
			IEventSource session = @event.Session;
			ISessionFactoryImplementor factory = session.Factory;

			if (log.IsDebugEnabled)
			{
				log.Debug("assembling entity from second-level cache: " + MessageHelper.InfoString(persister, id, factory));
			}

			IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass);
			object result = optionalObject ?? session.Instantiate(subclassPersister, id);

			// make it circular-reference safe
			EntityKey entityKey = new EntityKey(id, subclassPersister, session.EntityMode);
			TwoPhaseLoad.AddUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.None, entry.AreLazyPropertiesUnfetched, entry.Version, session);

			IType[] types = subclassPersister.PropertyTypes;
			object[] values = entry.Assemble(result, id, subclassPersister, session.Interceptor, session); // intializes result by side-effect
			TypeHelper.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session);

			object version = Versioning.GetVersion(values, subclassPersister);
			if (log.IsDebugEnabled)
			{
				log.Debug("Cached Version: " + version);
			}

			IPersistenceContext persistenceContext = session.PersistenceContext;
			bool isReadOnly = session.DefaultReadOnly;

			if (persister.IsMutable)
			{
				object proxy = persistenceContext.GetProxy(entityKey);
				if (proxy != null)
				{
					// this is already a proxy for this impl
					// only set the status to read-only if the proxy is read-only
					isReadOnly = ((INHibernateProxy)proxy).HibernateLazyInitializer.ReadOnly;
				}
			}
			else
				isReadOnly = true;
			
			persistenceContext.AddEntry(
				result,
				isReadOnly ? Status.ReadOnly : Status.Loaded,
				values,
				null,
				id,
				version,
				LockMode.None,
				true,
				subclassPersister,
				false,
				entry.AreLazyPropertiesUnfetched);
			
			subclassPersister.AfterInitialize(result, entry.AreLazyPropertiesUnfetched, session);
			persistenceContext.InitializeNonLazyCollections();
			// upgrade the lock if necessary:
			//lock(result, lockMode);

			//PostLoad is needed for EJB3
			//TODO: reuse the PostLoadEvent...
			PostLoadEvent postLoadEvent = new PostLoadEvent(session);
			postLoadEvent.Entity = result;
			postLoadEvent.Id = id;
			postLoadEvent.Persister = persister;

			IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners;
			for (int i = 0; i < listeners.Length; i++)
			{
				listeners[i].OnPostLoad(postLoadEvent);
			}
			return result;
		}
Exemple #16
0
 public void OnLoad(LoadEvent @event, LoadType loadType)
 {
     log.Debug("OnLoad :" + @event);
 }
 protected virtual void OnLoadEvent(LoadEventArgs e)
 {
     LoadEvent?.Invoke(this, e);
 }
Exemple #18
0
        public virtual void OnLoad(LoadEvent @event, LoadType loadType)
        {
            ISessionImplementor source = @event.Session;

            IEntityPersister persister;

            if (@event.InstanceToLoad != null)
            {
                persister = source.GetEntityPersister(null, @event.InstanceToLoad);                 //the load() which takes an entity does not pass an entityName
                @event.EntityClassName = @event.InstanceToLoad.GetType().FullName;
            }
            else
            {
                persister = source.Factory.GetEntityPersister(@event.EntityClassName);
            }

            if (persister == null)
            {
                throw new HibernateException("Unable to locate persister: " + @event.EntityClassName);
            }

            if (persister.IdentifierType.IsComponentType)
            {
                // skip this check for composite-ids relating to dom4j entity-mode;
                // alternatively, we could add a check to make sure the incoming id value is
                // an instance of Element...
            }
            else
            {
                System.Type idClass = persister.IdentifierType.ReturnedClass;
                if (idClass != null && !idClass.IsInstanceOfType(@event.EntityId))
                {
                    throw new TypeMismatchException("Provided id of the wrong type. Expected: " + idClass + ", got " + @event.EntityId.GetType());
                }
            }

            EntityKey keyToLoad = new EntityKey(@event.EntityId, persister, source.EntityMode);

            try
            {
                if (loadType.IsNakedEntityReturned)
                {
                    //do not return a proxy!
                    //(this option indicates we are initializing a proxy)
                    @event.Result = Load(@event, persister, keyToLoad, loadType);
                }
                else
                {
                    //return a proxy if appropriate
                    if (@event.LockMode == LockMode.None)
                    {
                        @event.Result = ProxyOrLoad(@event, persister, keyToLoad, loadType);
                    }
                    else
                    {
                        @event.Result = LockAndLoad(@event, persister, keyToLoad, loadType, source);
                    }
                }
            }
            catch (HibernateException e)
            {
                log.Info("Error performing load command", e);
                throw;
            }
        }
Exemple #19
0
 /// <summary>
 /// Do not call this constructor. Use SxLib.InitializeWinForms instead.
 /// </summary>
 /// <param name="_Current"></param>
 /// <param name="_SynapseDir"></param>
 protected internal SxLibWinForms(Form _Current, string _SynapseDir) : base(_SynapseDir)
 {
     Current              = _Current;
     LoadEventInternal   += delegate(SynLoadEvents LEvent, object Param) { Current.Invoke(new Action(() => { LoadEvent?.Invoke(LEvent, Param); })); };
     AttachEventInternal += delegate(SynAttachEvents AEvent, object Param) { Current.Invoke(new Action(() => { AttachEvent?.Invoke(AEvent, Param); })); };
     HubEventInternal    += delegate(List <SynHubEntry> Entries) { Current.Invoke(new Action(() => { ScriptHubEvent?.Invoke(Entries); })); };
 }
		/// <summary> 
		/// Performs the process of loading an entity from the configured underlying datasource. 
		/// </summary>
		/// <param name="event">The load event </param>
		/// <param name="persister">The persister for the entity being requested for load </param>
		/// <param name="keyToLoad">The EntityKey representing the entity to be loaded. </param>
		/// <param name="options">The load options. </param>
		/// <returns> The object loaded from the datasource, or null if not found. </returns>
		protected virtual object LoadFromDatasource(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
		{
			ISessionImplementor source = @event.Session;
			object entity = persister.Load(@event.EntityId, @event.InstanceToLoad, @event.LockMode, source);

			if (@event.IsAssociationFetch && source.Factory.Statistics.IsStatisticsEnabled)
			{
				source.Factory.StatisticsImplementor.FetchEntity(@event.EntityClassName);
			}

			return entity;
		}
Exemple #21
0
 public void LoadEventOperation()
 {
     LoadEvent?.Invoke(this, EventArgs.Empty);
 }
		/// <summary>
		/// Based on configured options, will either return a pre-existing proxy,
		/// generate a new proxy, or perform an actual load.
		/// </summary>
		/// <returns> The result of the proxy/load operation.</returns>
		protected virtual object ProxyOrLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
		{
			if (log.IsDebugEnabled)
			{
				log.Debug("loading entity: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
			}

			if (!persister.HasProxy)
			{
				// this class has no proxies (so do a shortcut)
				return Load(@event, persister, keyToLoad, options);
			}
			else
			{
				IPersistenceContext persistenceContext = @event.Session.PersistenceContext;

				// look for a proxy
				object proxy = persistenceContext.GetProxy(keyToLoad);
				if (proxy != null)
				{
					return ReturnNarrowedProxy(@event, persister, keyToLoad, options, persistenceContext, proxy);
				}
				else
				{
					if (options.IsAllowProxyCreation)
					{
						return CreateProxyIfNecessary(@event, persister, keyToLoad, options, persistenceContext);
					}
					else
					{
						// return a newly loaded object
						return Load(@event, persister, keyToLoad, options);
					}
				}
			}
		}
 public virtual void Refresh()
 {
     LoadEvent.Invoke();
 }
		/// <summary>
		/// Given that there is no pre-existing proxy.
		/// Check if the entity is already loaded. If it is, return the entity,
		/// otherwise create and return a proxy.
		/// </summary>
		private object CreateProxyIfNecessary(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, IPersistenceContext persistenceContext)
		{
			object existing = persistenceContext.GetEntity(keyToLoad);
			if (existing != null)
			{
				// return existing object or initialized proxy (unless deleted)
				log.Debug("entity found in session cache");
				if (options.IsCheckDeleted)
				{
					EntityEntry entry = persistenceContext.GetEntry(existing);
					Status status = entry.Status;
					if (status == Status.Deleted || status == Status.Gone)
					{
						return null;
					}
				}
				return existing;
			}
			else
			{
				log.Debug("creating new proxy for entity");
				// return new uninitialized proxy
				object proxy = persister.CreateProxy(@event.EntityId, @event.Session);
				persistenceContext.BatchFetchQueue.AddBatchLoadableEntityKey(keyToLoad);
				persistenceContext.AddProxy(keyToLoad, (INHibernateProxy)proxy);
				((INHibernateProxy)proxy)
					.HibernateLazyInitializer
					.ReadOnly = @event.Session.DefaultReadOnly || !persister.IsMutable;
				return proxy;
			}
		}
Exemple #25
0
 internal void InitScript(UUIView _script)
 {
     Script = _script;
     LoadEvent?.Invoke(Script);
     LoadEvent = null;
 }
		public virtual void OnLoad(LoadEvent @event, LoadType loadType)
		{
			ISessionImplementor source = @event.Session;

			IEntityPersister persister;
			if (@event.InstanceToLoad != null)
			{
				persister = source.GetEntityPersister(null, @event.InstanceToLoad); //the load() which takes an entity does not pass an entityName
				@event.EntityClassName = @event.InstanceToLoad.GetType().FullName;
			}
			else
			{
				persister = GetEntityPersister(source.Factory, @event.EntityClassName);
			}

			if (persister == null)
			{
				throw new HibernateException("Unable to locate persister: " + @event.EntityClassName);
			}

			if (persister.IdentifierType.IsComponentType)
			{
				// skip this check for composite-ids relating to dom4j entity-mode;
				// alternatively, we could add a check to make sure the incoming id value is
				// an instance of Element...
			}
			else
			{
				System.Type idClass = persister.IdentifierType.ReturnedClass;
				if (idClass != null && !idClass.IsInstanceOfType(@event.EntityId))
				{
					throw new TypeMismatchException("Provided id of the wrong type. Expected: " + idClass + ", got " + @event.EntityId.GetType());
				}
			}

			EntityKey keyToLoad = new EntityKey(@event.EntityId, persister, source.EntityMode);
			try
			{
				if (loadType.IsNakedEntityReturned)
				{
					//do not return a proxy!
					//(this option indicates we are initializing a proxy)
					@event.Result = Load(@event, persister, keyToLoad, loadType);
				}
				else
				{
					//return a proxy if appropriate
					if (@event.LockMode == LockMode.None)
					{
						@event.Result = ProxyOrLoad(@event, persister, keyToLoad, loadType);
					}
					else
					{
						@event.Result = LockAndLoad(@event, persister, keyToLoad, loadType, source);
					}
				}
			}
			catch (HibernateException e)
			{
				log.Info("Error performing load command", e);
				throw;
			}
		}
        /// <summary> Attempts to load the entity from the second-level cache. </summary>
        /// <param name="event">The load event </param>
        /// <param name="persister">The persister for the entity being requested for load </param>
        /// <param name="options">The load options. </param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns> The entity from the second-level cache, or null. </returns>
        protected virtual async Task <object> LoadFromSecondLevelCacheAsync(LoadEvent @event, IEntityPersister persister, LoadType options, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ISessionImplementor source = @event.Session;
            bool useCache = persister.HasCache && source.CacheMode.HasFlag(CacheMode.Get) &&
                            @event.LockMode.LessThan(LockMode.Read);

            if (!useCache)
            {
                return(null);
            }
            ISessionFactoryImplementor factory = source.Factory;
            var batchSize = persister.GetBatchSize();

            if (batchSize > 1 && persister.Cache.PreferMultipleGet())
            {
                // The first item in the array is the item that we want to load
                var entityBatch =
                    await(source.PersistenceContext.BatchFetchQueue.GetEntityBatchAsync(persister, @event.EntityId, batchSize, false, cancellationToken)).ConfigureAwait(false);
                // Ignore null values as the retrieved batch may contains them when there are not enough
                // uninitialized entities in the queue
                var keys = new List <CacheKey>(batchSize);
                for (var i = 0; i < entityBatch.Length; i++)
                {
                    var key = entityBatch[i];
                    if (key == null)
                    {
                        break;
                    }
                    keys.Add(source.GenerateCacheKey(key, persister.IdentifierType, persister.RootEntityName));
                }
                var cachedObjects = await(persister.Cache.GetManyAsync(keys.ToArray(), source.Timestamp, cancellationToken)).ConfigureAwait(false);
                for (var i = 1; i < cachedObjects.Length; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await(AssembleAsync(
                              keys[i],
                              cachedObjects[i],
                              new LoadEvent(entityBatch[i], @event.EntityClassName, @event.LockMode, @event.Session),
                              false)).ConfigureAwait(false);
                }
                cancellationToken.ThrowIfCancellationRequested();
                return(await(AssembleAsync(keys[0], cachedObjects[0], @event, true)).ConfigureAwait(false));
            }
            var cacheKey     = source.GenerateCacheKey(@event.EntityId, persister.IdentifierType, persister.RootEntityName);
            var cachedObject = await(persister.Cache.GetAsync(cacheKey, source.Timestamp, cancellationToken)).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();
            return(await(AssembleAsync(cacheKey, cachedObject, @event, true)).ConfigureAwait(false));

            Task <object> AssembleAsync(CacheKey ck, object ce, LoadEvent evt, bool alterStatistics)
            {
                if (factory.Statistics.IsStatisticsEnabled && alterStatistics)
                {
                    if (ce == null)
                    {
                        factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName);
                        log.Debug("Entity cache miss: {0}", ck);
                    }
                    else
                    {
                        factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName);
                        log.Debug("Entity cache hit: {0}", ck);
                    }
                }

                if (ce != null)
                {
                    CacheEntry entry = (CacheEntry)persister.CacheEntryStructure.Destructure(ce, factory);

                    // Entity was found in second-level cache...
                    // NH: Different behavior (take a look to options.ExactPersister (NH-295))
                    if (!options.ExactPersister || persister.EntityMetamodel.SubclassEntityNames.Contains(entry.Subclass))
                    {
                        return(AssembleCacheEntryAsync(entry, evt.EntityId, persister, evt, cancellationToken));
                    }
                }

                return(Task.FromResult <object>(null));
            }
        }
		/// <summary>
		/// Performs the process of loading an entity from the configured underlying datasource.
		/// </summary>
		/// <param name="event">The load event </param>
		/// <param name="persister">The persister for the entity being requested for load </param>
		/// <param name="keyToLoad">The EntityKey representing the entity to be loaded. </param>
		/// <param name="options">The load options. </param>
		/// <returns> The object loaded from the datasource, or null if not found. </returns>
		protected virtual object LoadFromDatasource(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
		{
			ISessionImplementor source = @event.Session;

			bool statsEnabled = source.Factory.Statistics.IsStatisticsEnabled;
			var stopWath = new Stopwatch();
			if (statsEnabled)
			{
				stopWath.Start();
			}

			object entity = persister.Load(@event.EntityId, @event.InstanceToLoad, @event.LockMode, source);

			if (@event.IsAssociationFetch && statsEnabled)
			{
				stopWath.Stop();
				source.Factory.StatisticsImplementor.FetchEntity(@event.EntityClassName, stopWath.Elapsed);
			}

			return entity;
		}
 public void OnLoad(LoadEvent @event, LoadType loadType)
 {
 }
		/// <summary> Attempts to load the entity from the second-level cache. </summary>
		/// <param name="event">The load event </param>
		/// <param name="persister">The persister for the entity being requested for load </param>
		/// <param name="options">The load options. </param>
		/// <returns> The entity from the second-level cache, or null. </returns>
		protected virtual object LoadFromSecondLevelCache(LoadEvent @event, IEntityPersister persister, LoadType options)
		{
			ISessionImplementor source = @event.Session;
			bool useCache = persister.HasCache && ((source.CacheMode & CacheMode.Get) == CacheMode.Get)
				&& @event.LockMode.LessThan(LockMode.Read);

			if (useCache)
			{
				ISessionFactoryImplementor factory = source.Factory;

				CacheKey ck = new CacheKey(@event.EntityId, persister.IdentifierType, persister.RootEntityName, source.EntityMode, factory);
				object ce = persister.Cache.Get(ck, source.Timestamp);

				if (factory.Statistics.IsStatisticsEnabled)
				{
					if (ce == null)
					{
						factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName);
						log.DebugFormat("Entity cache miss: {0}", ck);
					}
					else
					{
						factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName);
						log.DebugFormat("Entity cache hit: {0}", ck);
					}
				}

				if (ce != null)
				{
					CacheEntry entry = (CacheEntry) persister.CacheEntryStructure.Destructure(ce, factory);

					// Entity was found in second-level cache...
					// NH: Different behavior (take a look to options.ExactPersister (NH-295))
					if (!options.ExactPersister || persister.EntityMetamodel.SubclassEntityNames.Contains(entry.Subclass))
					{
						return AssembleCacheEntry(entry, @event.EntityId, persister, @event);
					}
				}
			}

			return null;
		}
Exemple #31
0
        public virtual async Task OnLoadAsync(LoadEvent @event, LoadType loadType, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ISessionImplementor source = @event.Session;

            IEntityPersister persister;

            if (@event.InstanceToLoad != null)
            {
                persister = source.GetEntityPersister(null, @event.InstanceToLoad);                 //the load() which takes an entity does not pass an entityName
                @event.EntityClassName = @event.InstanceToLoad.GetType().FullName;
            }
            else
            {
                persister = GetEntityPersister(source.Factory, @event.EntityClassName);
            }

            if (persister == null)
            {
                var message = new StringBuilder(512);
                message.AppendLine(string.Format("Unable to locate persister for the entity named '{0}'.", @event.EntityClassName));
                message.AppendLine("The persister define the persistence strategy for an entity.");
                message.AppendLine("Possible causes:");
                message.AppendLine(string.Format(" - The mapping for '{0}' was not added to the NHibernate configuration.", @event.EntityClassName));
                throw new HibernateException(message.ToString());
            }

            if (persister.IdentifierType.IsComponentType)
            {
                // skip this check for composite-ids relating to dom4j entity-mode;
                // alternatively, we could add a check to make sure the incoming id value is
                // an instance of Element...
            }
            else
            {
                System.Type idClass = persister.IdentifierType.ReturnedClass;
                if (idClass != null && !idClass.IsInstanceOfType(@event.EntityId))
                {
                    throw new TypeMismatchException("Provided id of the wrong type. Expected: " + idClass + ", got " + @event.EntityId.GetType());
                }
            }

            EntityKey keyToLoad = source.GenerateEntityKey(@event.EntityId, persister);

            try
            {
                if (loadType.IsNakedEntityReturned)
                {
                    //do not return a proxy!
                    //(this option indicates we are initializing a proxy)
                    @event.Result = await(LoadAsync(@event, persister, keyToLoad, loadType, cancellationToken)).ConfigureAwait(false);
                }
                else
                {
                    //return a proxy if appropriate
                    if (@event.LockMode == LockMode.None)
                    {
                        @event.Result = await(ProxyOrLoadAsync(@event, persister, keyToLoad, loadType, cancellationToken)).ConfigureAwait(false);
                    }
                    else
                    {
                        @event.Result = await(LockAndLoadAsync(@event, persister, keyToLoad, loadType, source, cancellationToken)).ConfigureAwait(false);
                    }
                }
            }
            catch (HibernateException e)
            {
                log.Info(e, "Error performing load command");
                throw;
            }
        }
		/// <summary> Perfoms the load of an entity. </summary>
		/// <returns> The loaded entity. </returns>
		protected virtual object Load(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
		{
			if (@event.InstanceToLoad != null)
			{
				if (@event.Session.PersistenceContext.GetEntry(@event.InstanceToLoad) != null)
				{
					throw new PersistentObjectException("attempted to load into an instance that was already associated with the session: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory));
				}
				persister.SetIdentifier(@event.InstanceToLoad, @event.EntityId, @event.Session.EntityMode);
			}

			object entity = DoLoad(@event, persister, keyToLoad, options);

			bool isOptionalInstance = @event.InstanceToLoad != null;

			if (!options.IsAllowNulls || isOptionalInstance)
			{
				if (entity == null)
				{
					@event.Session.Factory.EntityNotFoundDelegate.HandleEntityNotFound(@event.EntityClassName, @event.EntityId);
				}
			}

			if (isOptionalInstance && entity != @event.InstanceToLoad)
			{
				throw new NonUniqueObjectException(@event.EntityId, @event.EntityClassName);
			}

			return entity;
		}
Exemple #33
0
 /// <summary>
 /// Do not call this constructor. Use SxLib.InitializeWPF instead.
 /// </summary>
 /// <param name="_Current"></param>
 /// <param name="_SynapseDir"></param>
 protected internal SxLibWPF(Window _Current, string _SynapseDir) : base(_SynapseDir)
 {
     Current              = _Current;
     LoadEventInternal   += delegate(SynLoadEvents LEvent, object Param) { Current.Dispatcher.Invoke(() => { LoadEvent?.Invoke(LEvent, Param); }); };
     AttachEventInternal += delegate(SynAttachEvents AEvent, object Param) { Current.Dispatcher.Invoke(() => { AttachEvent?.Invoke(AEvent, Param); }); };
     HubEventInternal    += delegate(List <SynHubEntry> Entries) { Current.Dispatcher.Invoke(() => { ScriptHubEvent?.Invoke(Entries); }); };
 }