private void ThrowIfTargetNotLoadable(ILoadable target)
 {
     if (target == null)
     {
         throw new InterceptionTypeNotLoadableException();
     }
 }
        public InstructionBlockChain CallMethodWithReturn(MethodReference method,
                                                          ILoadable instance,
                                                          IPersistable returnValue,
                                                          params ILoadable[] arguments)
        {
            var type = FixTypeReference(method.DeclaringType);

            method = FixMethodReference(type, method);

            InstructionBlock block;

            if (method.Resolve().IsStatic)
            {
                block = _creator.CallStaticMethod(method, returnValue, arguments);
            }
            else
            {
                block = _creator.CallInstanceMethod(method, instance, returnValue, arguments);
            }

            var chain = new InstructionBlockChain();

            chain.Add(block);
            return(chain);
        }
Пример #3
0
 protected void InitProjection(SqlString projectionString, SqlString whereString,
                               SqlString orderByString, string groupByString, SqlString havingString, LockMode lockMode)
 {
     WalkEntityTree(persister, Alias);
     Persisters = new ILoadable[0];
     InitStatementString(projectionString, whereString, orderByString, groupByString, havingString, lockMode);
 }
Пример #4
0
        }                                                   // For the Ok btn that in the error panel
        public LogInViewModel(ILoadable loadable)
        {
            this.loadable = loadable;

            LoginCommand = new DelegateCommand(x => UserName.Length > 0, x =>
            {
                BussinesLogic bl = new BussinesLogic();
                p             = bl.GetPersonByEmail(UserName);
                IsLogInActive = false;
                Notify("MutexIndex", "ErrorTitle");

                if (p != null && Password.Equals(p.Password))
                {
                    BackgroundWorker worker = new BackgroundWorker();
                    worker.DoWork          += (s, e) =>
                    {
                        while (progress < 1)
                        {
                            Thread.Sleep(50);
                            progress += 0.01;
                            Notify("Progress");
                        }
                    };
                    worker.RunWorkerCompleted += (s, e) => loadable.Loaded(p.PersonType);
                    worker.RunWorkerAsync();
                }
            });
            ErrorOkCommand = new DelegateCommand(x => IsLogInActive = true);

            CancelCommand = new DelegateCommand(x =>
            {
                loadable.Cancel();
            });
        }
Пример #5
0
        public void OnModsLoad()
        {
            IEnumerable <Assembly> asses = ModLoader.Mods
                                           .SafeSelect(mod => mod.GetType().Assembly);

            foreach (Assembly ass in asses)
            {
                foreach (Type classType in ass.GetTypes())
                {
                    try {
                        Type iloadableType = classType.GetInterface("ILoadable");
                        if (iloadableType == null)
                        {
                            continue;
                        }

                        ILoadable loadable = this.LoadLoadableSingleton(classType);
                        if (loadable == null)
                        {
                            continue;
                        }

                        this.Loadables.Add(loadable);
                    } catch { }
                }
            }

            foreach (ILoadable loadable in this.Loadables)
            {
                loadable.OnModsLoad();
            }
        }
Пример #6
0
		protected void InitProjection(SqlString projectionString, SqlString whereString,
			string orderByString, string groupByString, LockMode lockMode)
		{
			WalkEntityTree(persister, Alias);
			Persisters = new ILoadable[0];
			InitStatementString(projectionString, whereString, orderByString, groupByString, lockMode);
		}
 private void ThrowIfTargetNotLoadable(ILoadable target)
 {
     if(target == null)
     {
         throw new InterceptionTypeNotLoadableException();
     }
 }
		/// <summary>
		/// Calculate and cache select-clause suffixes.
		/// </summary>
		public DefaultEntityAliases(IDictionary<string, string[]> userProvidedAliases, ILoadable persister, string suffix)
		{
			this.suffix = suffix;
			this.userProvidedAliases = userProvidedAliases;

			string[] keyColumnsCandidates = GetUserProvidedAliases(persister.IdentifierPropertyName, null);
			if (keyColumnsCandidates == null)
			{
				suffixedKeyColumns = GetUserProvidedAliases(EntityPersister.EntityID, GetIdentifierAliases(persister, suffix));
			}
			else
			{
				suffixedKeyColumns = keyColumnsCandidates;
			}
			Intern(suffixedKeyColumns);

			suffixedPropertyColumns = GetSuffixedPropertyAliases(persister);
			suffixedDiscriminatorColumn =
				GetUserProvidedAlias(AbstractEntityPersister.EntityClass, GetDiscriminatorAlias(persister, suffix));
			if (persister.IsVersioned)
			{
				suffixedVersionColumn = suffixedPropertyColumns[persister.VersionProperty];
			}
			else
			{
				suffixedVersionColumn = null;
			}
			rowIdAlias = Loadable.RowIdAlias + suffix; // TODO: not visible to the user!
		}
Пример #9
0
 public static void AddLoadable(ILoadable loadable)
 {
     lock (loadables) if (!loadables.Contains(loadable))
         {
             loadables.Add(loadable);
         }
 }
Пример #10
0
            /// <summary>
            /// Method that save the repository type of the object passed as argument inside the RavenDB embedded document.
            /// </summary>
            /// <param name="data">Object to store</param>
            /// <returns>Always RepositoryResponse.RepositorySuccess</returns>
            public override RepositoryResponse Save(ILoadable data)
            {
                /*try
                 * {*/
                lock (_store)
                {
                    /*using (TransactionScope tx = new TransactionScope())
                     * {*/
                    using (IDocumentSession _session = _store.OpenSession())
                    {
                        dynamic entity = data.GetAsDatabaseType();
                        _session.Store(entity);
                        try
                        {
                            _session.SaveChanges();
                        }
                        catch (COMException comE)
                        {
                            log.Warn("Cannot save cause to interop error", comE);
                        }
                        //      tx.Complete();
                        log.Debug("Data saved with id " + entity.Id);
                    }
                    //}
                }

                /*}
                 * catch (TransactionAbortedException tae)
                 * {
                 *  log.Error("Transaction aborted", tae);
                 *  return RepositoryResponse.RepositoryTransactionAbort;
                 * }*/
                return(RepositoryResponse.RepositorySuccess);
            }
Пример #11
0
        /// <summary>
        /// Retrieve property values from one row of a result set
        /// </summary>
        //6.0 TODO: Merge into ILoadable
        public static Task <object[]> HydrateAsync(
            this ILoadable loadable, DbDataReader rs, object id, object obj,
            string[][] suffixedPropertyColumns, ISet <string> fetchedLazyProperties, bool allProperties, ISessionImplementor session, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled <object[]>(cancellationToken));
            }
            try
            {
                if (loadable is AbstractEntityPersister abstractEntityPersister)
                {
                    return(abstractEntityPersister.HydrateAsync(
                               rs, id, obj, suffixedPropertyColumns, fetchedLazyProperties, allProperties, session, cancellationToken));
                }

                var rootLoadable = loadable.RootEntityName == loadable.EntityName
                                        ? loadable
                                        : (ILoadable)loadable.Factory.GetEntityPersister(loadable.RootEntityName);

#pragma warning disable 618
                // Fallback to the old behavior
                return(loadable.HydrateAsync(rs, id, obj, rootLoadable, suffixedPropertyColumns, allProperties, session, cancellationToken));

#pragma warning restore 618
            }
            catch (Exception ex)
            {
                return(Task.FromException <object[]>(ex));
            }
        }
        public LogInViewModel(ILoadable loadable)
        {
            this.loadable = loadable;

            LoginCommand = new DelegateCommand(x => UserName.Length > 0, x =>
            {
                IsLogInActive = false;
                Notify("MutexIndex", "ErrorTitle");
                if (UserName == "Setec")
                {
                    BackgroundWorker worker = new BackgroundWorker();
                    worker.DoWork          += (s, e) =>
                    {
                        while (progress < 1)
                        {
                            Thread.Sleep(50);
                            progress += 0.01;
                            Notify("Progress");
                        }
                    };
                    worker.RunWorkerCompleted += (s, e) => loadable.Loaded();
                    worker.RunWorkerAsync();
                }
            });
            ErrorOkCommand = new DelegateCommand(x => IsLogInActive = true);
        }
Пример #13
0
        public static bool Draw(ILoadable loadable, IUndoable undoable, ICopyable copyable)
        {
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("File", EditorStyles.toolbarButton, GUILayout.Width(35)))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("New: Ctrl+Atl+N "), false, OnNew, loadable);
                menu.AddItem(new GUIContent("Load: Ctrl+Atl+L"), false, OnLoad, loadable);
                menu.AddItem(new GUIContent("Save: Ctrl+Atl+S"), false, OnSave, loadable);
                menu.ShowAsContext();
                return(true);
            }

            if (GUILayout.Button("Edit", EditorStyles.toolbarButton, GUILayout.Width(35)))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Undo: Ctrl+Atl+Z"), false, OnUndo, undoable);
                menu.AddItem(new GUIContent("Redo: Ctrl+Atl+Y"), false, OnRedo, undoable);
                menu.AddItem(new GUIContent("Copy: Ctrl+Atl+C"), false, Copy, copyable);
                menu.AddItem(new GUIContent("Past: Ctrl+Atl+V"), false, Paste, copyable);
                menu.ShowAsContext();
                return(true);
            }

            if (GUILayout.Button("View", EditorStyles.toolbarButton, GUILayout.Width(35)))
            {
                GenericMenu menu = new GenericMenu();
                menu.ShowAsContext();
                return(true);
            }

            GUILayout.Label("", EditorStyles.toolbarButton);
            EditorGUILayout.EndHorizontal();
            return(false);
        }
Пример #14
0
        public static void AddContent(Mod mod, ILoadable instance)
        {
            instance.Load(mod);

            content.Add(instance);
            //ContentInstance.Register(instance); //Normally, we would have this line, but 1.3 already calls it, so having it everywhere would cause clashes.
        }
Пример #15
0
            /// <summary>
            /// Gets element of the given type and identified by the string passed as arguments.
            /// </summary>
            /// <typeparam name="DBType">Type of the element stored in the database. This is used to identify the collection</typeparam>
            /// <param name="id">Identifier of the element to retrieve</param>
            /// <param name="elem">Reference where the object will be loaded</param>
            /// <returns>RepositoryResponse.RepositoryLoad if the element has been successfully loaded,
            /// RepositoryResponse.RepositoryMissingKey if the element is not contained in the repository,
            ///  RepositoryResponse.RepositoryGenericError otherwise.</returns>
            public override RepositoryResponse GetByKey <DBType>(string id, ILoadable elem)
            {
                DBType entity;

                using (IDocumentSession _session = _store.OpenSession())
                {
                    entity = _session.Load <DBType>(id);
                }
                if (entity != null)
                {
                    if (elem.LoadFromDatabaseType(entity))
                    {
                        log.Debug("Data with key " + id + " loaded");
                        return(RepositoryResponse.RepositoryLoad);
                    }
                    else
                    {
                        return(RepositoryResponse.RepositoryGenericError);
                    }
                }
                else
                {
                    return(RepositoryResponse.RepositoryMissingKey);
                }
            }
Пример #16
0
 private void FillEntityPersisterProperties(int i, OuterJoinableAssociation oj, ILoadable persister)
 {
     persisters[i]           = persister;
     aliases[i]              = oj.RHSAlias;
     EagerPropertyFetches[i] = oj.SelectMode == SelectMode.FetchLazyProperties;
     ChildFetchEntities[i]   = oj.SelectMode == SelectMode.ChildFetch;
 }
 public SimpleEntityLoader(ILoadable persister, SqlString sql, LockMode lockMode)
 {
     this.persister = new ILoadable[] { persister };
     this.idType    = persister.IdentifierType;
     this.sql       = sql;
     this.lockMode  = new LockMode[] { lockMode };
     PostInstantiate();
 }
Пример #18
0
 //destroy the handle
 public void destroy()
 {
     if (resource != null)
     {
         resource.unload();
         resource = null;
     }
 }
Пример #19
0
        public void LoadSetLoaded()
        {
            ILoadable loadable = Sut;

            loadable.Load();

            Assert.IsTrue(loadable.IsLoaded);
        }
Пример #20
0
 //load layout
 public void Loadlayout(ILoadable employeeService)
 {
     if (!(Employees is null))
     {
         Employees.Clear();
     }
     Employees = employeeService.LoadAdvanced();
 }
		public SimpleEntityLoader( ILoadable persister, SqlString sql, LockMode lockMode )
		{
			this.persister = new ILoadable[ ] {persister};
			this.idType = persister.IdentifierType;
			this.sql = sql;
			this.lockMode = new LockMode[ ] {lockMode};
			PostInstantiate();
		}
 private static List <Instruction> CreateInstanceMethodCallInstructions(
     MethodReference methodReference,
     ILoadable callerInstance,
     IPersistable returnValue,
     params ILoadable[] arguments)
 {
     return(CreateMethodCallInstructions(methodReference, callerInstance, returnValue, arguments));
 }
        /// <summary>
        ///     Add a new loadable object to the savemanager for when the game is being loaded.
        /// </summary>
        /// <param name="saveable">Loadable to add.</param>

        public static void RegisterLoadable(ILoadable loadable)
        {
            if (_loadables.Contains(loadable))
            {
                return;
            }

            _loadables.Add(loadable);
        }
        /// <summary>
        ///     Removes a new loadable object to the savemanager for when the game is being loaded.
        /// </summary>
        /// <param name="saveable">Loadable to remove.</param>
        public static void UnregisterLoadable(ILoadable loadable)
        {
            if (!_loadables.Contains(loadable))
            {
                return;
            }

            _loadables.Remove(loadable);
        }
Пример #25
0
        protected void InitClassPersisters(IList associations)
        {
            int joins = CountClassPersisters(associations);

            collectionOwner = -1;             // if no collection found
            classPersisters = new ILoadable[joins + 1];
            Owners          = new int[joins + 1];
            aliases         = new string[joins + 1];
            lockModeArray   = CreateLockModeArray(joins + 1, LockMode.None);
            int i = 0;

            foreach (OuterJoinableAssociation oj in associations)
            {
                object subpersister = oj.Joinable;
                if (subpersister is ILoadable)
                {
                    classPersisters[i] = ( ILoadable )subpersister;
                    Owners[i]          = ToOwner(oj, joins, oj.IsOneToOne);
                    aliases[i]         = oj.Subalias;
                    if (oj.JoinType == JoinType.InnerJoin)
                    {
                        AddAllToPropertySpaces(classPersisters[i].PropertySpaces);
                    }
                    i++;
                }
                else
                {
                    IQueryableCollection collPersister = ( IQueryableCollection )subpersister;
                    // TODO: ?? suppress initialization of collections with a where condition
                    if (oj.JoinType == JoinType.LeftOuterJoin)
                    {
                        collectionPersister = collPersister;
                        collectionOwner     = ToOwner(oj, joins, true);
                    }
                    else
                    {
                        AddToPropertySpaces(collPersister.CollectionSpace);
                    }

                    if (collPersister.IsOneToMany)
                    {
                        classPersisters[i] = ( ILoadable )collPersister.ElementPersister;
                        aliases[i]         = oj.Subalias;
                        i++;
                    }
                }
            }
            classPersisters[joins] = persister;
            Owners[joins]          = -1;
            aliases[joins]         = alias;

            if (ArrayHelper.IsAllNegative(Owners))
            {
                Owners = null;
            }
        }
Пример #26
0
 public void AddContent(ILoadable instance)
 {
     if (!loading)
     {
         throw new Exception(Language.GetTextValue("tModLoader.LoadErrorNotLoading"));
     }
     instance.Load(this);
     content.Add(instance);
     ContentInstance.Register(instance);
 }
		private void RenderStatement( ILoadable[ ] persisters )
		{
			int loadables = persisters.Length;

			Persisters = persisters;
			Suffixes = GenerateSuffixes( loadables );
			lockModeArray = CreateLockModeArray( loadables, LockMode.None );

			SqlString = SubstituteParams( SubstituteBrackets() );
		}
Пример #28
0
		public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters,
		                      ISet<EntityKey> resultingEntityKeys)
		{
			this.resultingEntityKeys = resultingEntityKeys;
			this.queryParameters = queryParameters;
			this.loadable = loadable;
			this.alias = alias;

			queryString = queryParameters.ProcessedSql.GetSubselectString();
		}
Пример #29
0
        public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters,
                              ISet <EntityKey> resultingEntityKeys)
        {
            this.resultingEntityKeys = resultingEntityKeys;
            this.queryParameters     = queryParameters;
            this.loadable            = loadable;
            this.alias = alias;

            queryString = queryParameters.ProcessedSql.GetSubselectString();
        }
        /// <summary>
        /// Register given handler to given event as a weak reference.
        /// </summary>
        /// <param name="sender">Object to register.</param>
        /// <param name="handler">Handler to register.</param>
        public static void RegisterLoadable(ILoadable sender, EventHandler handler)
        {
            var listener = new WeakEventListener <ILoadable, object, EventArgs>(sender)
            {
                OnEventAction  = (instance, source, eventArgs) => { handler.Invoke(source, eventArgs); },
                OnDetachAction = (instance, weakEventListener) => instance.Loaded -= weakEventListener.OnEvent
            };

            sender.Loaded += listener.OnEvent;
        }
		protected void InitClassPersisters( IList associations )
		{
			int joins = CountClassPersisters( associations );

			collectionOwner = -1; // if no collection found
			classPersisters = new ILoadable[ joins + 1 ];
			Owners = new int[ joins + 1 ];
			aliases = new string[ joins + 1 ];
			lockModeArray = CreateLockModeArray( joins + 1, LockMode.None );
			int i = 0;
			foreach( OuterJoinableAssociation oj in associations )
			{
				object subpersister = oj.Joinable;
				if( subpersister is ILoadable )
				{
					classPersisters[ i ] = ( ILoadable ) subpersister;
					Owners[ i ] = ToOwner( oj, joins, oj.IsOneToOne );
					aliases[ i ] = oj.Subalias;
					if( oj.JoinType == JoinType.InnerJoin )
					{
						AddAllToPropertySpaces( classPersisters[ i ].PropertySpaces );
					}
					i++;
				}
				else
				{
					IQueryableCollection collPersister = ( IQueryableCollection ) subpersister;
					// TODO: ?? suppress initialization of collections with a where condition
					if( oj.JoinType == JoinType.LeftOuterJoin )
					{
						collectionPersister = collPersister;
						collectionOwner = ToOwner( oj, joins, true );
					}
					else
					{
						AddToPropertySpaces( collPersister.CollectionSpace );
					}

					if( collPersister.IsOneToMany )
					{
						classPersisters[ i ] = ( ILoadable ) collPersister.ElementPersister;
						aliases[ i ] = oj.Subalias;
						i++;
					}
				}
			}
			classPersisters[ joins ] = persister;
			Owners[ joins ] = -1;
			aliases[ joins ] = alias;

			if( ArrayHelper.IsAllNegative( Owners ) )
			{
				Owners = null;
			}
		}
Пример #32
0
        public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters,
                              ISet <EntityKey> resultingEntityKeys, IDictionary <string, int[]> namedParameterLocMap)
        {
            this.resultingEntityKeys  = resultingEntityKeys;
            this.queryParameters      = queryParameters;
            this.namedParameterLocMap = namedParameterLocMap;
            this.loadable             = loadable;
            this.alias = alias;

            queryString = queryParameters.FilteredSQL.GetSubselectString();
        }
        public InstructionBlock CallInstanceMethod(
            MethodReference methodReference,
            ILoadable callerInstance,
            IPersistable returnValue,
            params ILoadable[] arguments)
        {
            var instructions = CreateInstanceMethodCallInstructions(methodReference,
                                                                    callerInstance, returnValue, arguments);

            return(new InstructionBlock("CallInstanceMethod: " + methodReference.Name, instructions));
        }
Пример #34
0
		public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters,
		                      ISet<EntityKey> resultingEntityKeys, IDictionary<string, int[]> namedParameterLocMap)
		{
			this.resultingEntityKeys = resultingEntityKeys;
			this.queryParameters = queryParameters;
			this.namedParameterLocMap = namedParameterLocMap;
			this.loadable = loadable;
			this.alias = alias;

			queryString = queryParameters.FilteredSQL.GetSubselectString();
		}
Пример #35
0
        public string[][] GetSuffixedPropertyAliases(ILoadable persister)
        {
            int size = persister.PropertyNames.Length;

            string[][] suffixedPropertyAliases = new string[size][];
            for (int j = 0; j < size; j++)
            {
                suffixedPropertyAliases[j] = GetUserProvidedAliases(persister.PropertyNames[j], GetPropertyAliases(persister, j));
                Intern(suffixedPropertyAliases[j]);
            }
            return(suffixedPropertyAliases);
        }
        /// <summary>
        /// Returns default aliases for all the properties
        /// </summary>
        private string[][] GetAllPropertyAliases(ILoadable persister)
        {
            var propertyNames           = persister.PropertyNames;
            var suffixedPropertyAliases = new string[propertyNames.Length][];

            for (var i = 0; i < propertyNames.Length; i++)
            {
                suffixedPropertyAliases[i] = GetPropertyAliases(persister, i);
            }

            return(suffixedPropertyAliases);
        }
        public void Intercept(IInvocation invocation)
        {
            ILoadable target = invocation.InvocationTarget as ILoadable;

            ThrowIfTargetNotLoadable(target);

            if (!target.IsLoaded)
            {
                target.Load();
            }

            invocation.Proceed();
        }
        private string DetermineDiscriminatorAlias(ILoadable persister)
        {
            if (_userProvidedAliases != null)
            {
                var columns = GetUserProvidedAliases(AbstractEntityPersister.EntityClass);
                if (columns != null)
                {
                    return(columns[0]);
                }
            }

            return(GetDiscriminatorAlias(persister, _suffix));
        }
Пример #39
0
		protected void InitProjection(CriteriaQueryTranslator translator, 
			IDictionary<string, IFilter> enabledFilters, LockMode lockMode)
		{
			// the order of the calls here is important, as the join clauses can contain parameter bindings
			SqlString projectionString = translator.GetSelect(enabledFilters);
			WalkEntityTree(persister, Alias);
			SqlString whereString = translator.GetWhereCondition(enabledFilters);
			SqlString orderByString = translator.GetOrderBy();
			SqlString groupByString = translator.GetGroupBy();
			SqlString havingString = translator.GetHavingCondition(enabledFilters);
			
			Persisters = new ILoadable[0];
			InitStatementString(projectionString, whereString, orderByString, groupByString.ToString(), 
                havingString, lockMode);
		}
		private void InitClassPersisters( IOuterJoinLoadable persister, IList associations )
		{
			int joins = associations.Count;
			lockModeArray = CreateLockModeArray( joins + 1, LockMode.None );

			classPersisters = new ILoadable[joins + 1];
			Owners = new int[ joins + 1 ];
			for( int i = 0; i < joins; i++ )
			{
				OuterJoinableAssociation oj = ( OuterJoinableAssociation ) associations[ i ];
				Persisters[ i ] = (ILoadable) oj.Joinable;
				Owners[ i ] = ToOwner( oj, joins, oj.IsOneToOne );
			}
			classPersisters[ joins ] = persister;
			Owners[ joins ] = -1;

			if ( ArrayHelper.IsAllNegative( Owners ) )
			{
				Owners = null;
			}
		}
		private void InitClassPersisters( IList associations )
		{
			int joins = associations.Count;
			lockModeArray = CreateLockModeArray( joins, LockMode.None );

			classPersisters = new ILoadable[joins];
			Owners = new int[joins];

			int i = 0;
			foreach( OuterJoinableAssociation oj in associations )
			{
				classPersisters[ i ] = ( ILoadable ) oj.Joinable;
				Owners[ i ] = ToOwner( oj, joins, oj.IsOneToOne );
				i++;
			}

			if( ArrayHelper.IsAllNegative( Owners ) )
			{
				Owners = null;
			}
		}
Пример #42
0
		public ColumnEntityAliases(IDictionary<string, string[]> returnProperties, ILoadable persister)
			: base(returnProperties, persister, null) {}
		private SqlString GenerateSequentialSelect(ILoadable persister)
		{
			//note that this method could easily be moved up to BasicEntityPersister,
			//if we ever needed to reuse it from other subclasses

			//figure out which tables need to be fetched
			AbstractEntityPersister subclassPersister = (AbstractEntityPersister)persister;
			HashedSet<int> tableNumbers = new HashedSet<int>();
			string[] props = subclassPersister.PropertyNames;
			string[] classes = subclassPersister.PropertySubclassNames;
			for (int i = 0; i < props.Length; i++)
			{
				int propTableNumber = GetSubclassPropertyTableNumber(props[i], classes[i]);
				if (IsSubclassTableSequentialSelect(propTableNumber) && !IsSubclassTableLazy(propTableNumber))
				{
					tableNumbers.Add(propTableNumber);
				}
			}
			if ((tableNumbers.Count == 0))
				return null;

			//figure out which columns are needed
			List<int> columnNumbers = new List<int>();
			int[] columnTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassColumnClosure.Length; i++)
			{
				if (tableNumbers.Contains(columnTableNumbers[i]))
					columnNumbers.Add(i);
			}

			//figure out which formulas are needed
			List<int> formulaNumbers = new List<int>();
			int[] formulaTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassFormulaTemplateClosure.Length; i++)
			{
				if (tableNumbers.Contains(formulaTableNumbers[i]))
					formulaNumbers.Add(i);
			}

			//render the SQL
			return RenderSelect(ArrayHelper.ToIntArray(tableNumbers), columnNumbers.ToArray(), formulaNumbers.ToArray());
		}
		public string[][] GetSuffixedPropertyAliases(ILoadable persister)
		{
			int size = persister.PropertyNames.Length;
			string[][] suffixedPropertyAliases = new string[size][];
			for (int j = 0; j < size; j++)
			{
				suffixedPropertyAliases[j] = GetUserProvidedAliases(persister.PropertyNames[j], GetPropertyAliases(persister, j));
				Intern(suffixedPropertyAliases[j]);
			}
			return suffixedPropertyAliases;
		}
		public DefaultEntityAliases(ILoadable persister, string suffix)
			: this(new CollectionHelper.EmptyMapClass<string, string[]>(), persister, suffix) {}
		protected virtual string[] GetPropertyAliases(ILoadable persister, int j)
		{
			return persister.GetPropertyAliases(suffix, j);
		}
Пример #47
0
		/// <summary>
		/// Determine the concrete class of an instance for the <c>IDataReader</c>
		/// </summary>
		private string GetInstanceClass(IDataReader rs, int i, ILoadable persister, object id, ISessionImplementor session)
		{
			if (persister.HasSubclasses)
			{
				// code to handle subclasses of topClass
				object discriminatorValue =
					persister.DiscriminatorType.NullSafeGet(rs, EntityAliases[i].SuffixedDiscriminatorAlias, session, null);

				string result = persister.GetSubclassForDiscriminatorValue(discriminatorValue);

				if (result == null)
				{
					// woops we got an instance of another class hierarchy branch.
					throw new WrongClassException(string.Format("Discriminator was: '{0}'", discriminatorValue), id,
					                              persister.EntityName);
				}

				return result;
			}
			else
			{
				return persister.EntityName;
			}
		}
		protected override string[] GetPropertyAliases(ILoadable persister, int j)
		{
			return persister.GetPropertyColumnNames(j);
		}
		protected override string GetDiscriminatorAlias(ILoadable persister, string suffix)
		{
			return persister.DiscriminatorColumnName;
		}
		protected override string[] GetIdentifierAliases(ILoadable persister, string suffix)
		{
			return persister.IdentifierColumnNames;
		}
		public ColumnEntityAliases(IDictionary returnProperties, ILoadable persister, string suffix)
			: base(returnProperties, persister, suffix)
		{
		}
Пример #52
0
 public static void AddLoadable(ILoadable loadable)
 {
     lock (loadables) if (!loadables.Contains(loadable)) loadables.Add(loadable);
 }
Пример #53
0
        public LoadWaiter(ILoadable[] loadables, Loader.LoadedCallbackMethod loadedCallback)
        {
            this.loadables = loadables;
            LoadedCallback = loadedCallback;

            Loader.AddLoadable(this);
        }
		/// <summary>
		/// Unmarshall the fields of a persistent instance from a result set,
		/// without resolving associations or collections
		/// </summary>
		public object[] Hydrate(IDataReader rs, object id, object obj, ILoadable rootLoadable,
			string[][] suffixedPropertyColumns, bool allProperties, ISessionImplementor session)
		{
			if (log.IsDebugEnabled)
			{
				log.Debug("Hydrating entity: " + MessageHelper.InfoString(this, id, Factory));
			}

			AbstractEntityPersister rootPersister = (AbstractEntityPersister)rootLoadable;

			bool hasDeferred = rootPersister.HasSequentialSelect;
			IDbCommand sequentialSelect = null;
			IDataReader sequentialResultSet = null;
			bool sequentialSelectEmpty = false;
			using (new SessionIdLoggingContext(session.SessionId)) 
			try
			{
				if (hasDeferred)
				{
					SqlString sql = rootPersister.GetSequentialSelect(EntityName);
					if (sql != null)
					{
						//TODO: I am not so sure about the exception handling in this bit!
						sequentialSelect = session.Batcher.PrepareCommand(CommandType.Text, sql, IdentifierType.SqlTypes(factory));
						rootPersister.IdentifierType.NullSafeSet(sequentialSelect, id, 0, session);
						sequentialResultSet = session.Batcher.ExecuteReader(sequentialSelect);
						if (!sequentialResultSet.Read())
						{
							// TODO: Deal with the "optional" attribute in the <join> mapping;
							// this code assumes that optional defaults to "true" because it
							// doesn't actually seem to work in the fetch="join" code
							//
							// Note that actual proper handling of optional-ality here is actually
							// more involved than this patch assumes.  Remember that we might have
							// multiple <join/> mappings associated with a single entity.  Really
							// a couple of things need to happen to properly handle optional here:
							//  1) First and foremost, when handling multiple <join/>s, we really
							//      should be using the entity root table as the driving table;
							//      another option here would be to choose some non-optional joined
							//      table to use as the driving table.  In all likelihood, just using
							//      the root table is much simplier
							//  2) Need to add the FK columns corresponding to each joined table
							//      to the generated select list; these would then be used when
							//      iterating the result set to determine whether all non-optional
							//      data is present
							// My initial thoughts on the best way to deal with this would be
							// to introduce a new SequentialSelect abstraction that actually gets
							// generated in the persisters (ok, SingleTable...) and utilized here.
							// It would encapsulated all this required optional-ality checking...
							sequentialSelectEmpty = true;
						}
					}
				}

				string[] propNames = PropertyNames;
				IType[] types = PropertyTypes;
				object[] values = new object[types.Length];
				bool[] laziness = PropertyLaziness;
				string[] propSubclassNames = SubclassPropertySubclassNameClosure;

				for (int i = 0; i < types.Length; i++)
				{
					if (!propertySelectable[i])
					{
						values[i] = BackrefPropertyAccessor.Unknown;
					}
					else if (allProperties || !laziness[i])
					{
						//decide which ResultSet to get the property value from:
						bool propertyIsDeferred = hasDeferred
																			&& rootPersister.IsSubclassPropertyDeferred(propNames[i], propSubclassNames[i]);
						if (propertyIsDeferred && sequentialSelectEmpty)
						{
							values[i] = null;
						}
						else
						{
							IDataReader propertyResultSet = propertyIsDeferred ? sequentialResultSet : rs;
							string[] cols = propertyIsDeferred ? propertyColumnAliases[i] : suffixedPropertyColumns[i];
							values[i] = types[i].Hydrate(propertyResultSet, cols, session, obj);
						}
					}
					else
					{
						values[i] = LazyPropertyInitializer.UnfetchedProperty;
					}
				}

				if (sequentialResultSet != null)
				{
					sequentialResultSet.Close();
				}

				return values;
			}
			finally
			{
				if (sequentialSelect != null)
				{
					session.Batcher.CloseCommand(sequentialSelect, sequentialResultSet);
				}
			}
		}
		protected virtual string[] GetIdentifierAliases(ILoadable persister, string suffix)
		{
			return persister.GetIdentifierAliases(suffix);
		}
Пример #56
0
		/// <summary>
		/// The entity instance is not in the session cache
		/// </summary>
		private object InstanceNotYetLoaded(IDataReader dr, int i, ILoadable persister, EntityKey key, LockMode lockMode,
		                                    string rowIdAlias, EntityKey optionalObjectKey, object optionalObject,
		                                    IList hydratedObjects, ISessionImplementor session)
		{
			object obj;

			string instanceClass = GetInstanceClass(dr, i, persister, key.Identifier, session);

			if (optionalObjectKey != null && key.Equals(optionalObjectKey))
			{
				// its the given optional object
				obj = optionalObject;
			}
			else
			{
				obj = session.Instantiate(instanceClass, key.Identifier);
			}

			// need to hydrate it

			// grab its state from the DataReader and keep it in the Session
			// (but don't yet initialize the object itself)
			// note that we acquired LockMode.READ even if it was not requested
			LockMode acquiredLockMode = lockMode == LockMode.None ? LockMode.Read : lockMode;
			LoadFromResultSet(dr, i, obj, instanceClass, key, rowIdAlias, acquiredLockMode, persister, session);

			// materialize associations (and initialize the object) later
			hydratedObjects.Add(obj);

			return obj;
		}
Пример #57
0
		/// <summary>
		/// Resolve any ids for currently loaded objects, duplications within the <c>IDataReader</c>,
		/// etc. Instanciate empty objects to be initialized from the <c>IDataReader</c>. Return an
		/// array of objects (a row of results) and an array of booleans (by side-effect) that determine
		/// wheter the corresponding object should be initialized
		/// </summary>
		private object[] GetRow(IDataReader rs, ILoadable[] persisters, EntityKey[] keys, object optionalObject,
		                        EntityKey optionalObjectKey, LockMode[] lockModes, IList hydratedObjects,
		                        ISessionImplementor session)
		{
			int cols = persisters.Length;
			IEntityAliases[] descriptors = EntityAliases;

			if (log.IsDebugEnabled)
			{
				log.Debug("result row: " + StringHelper.ToString(keys));
			}

			object[] rowResults = new object[cols];

			for (int i = 0; i < cols; i++)
			{
				object obj = null;
				EntityKey key = keys[i];

				if (keys[i] == null)
				{
					// do nothing
					/* TODO NH-1001 : if (persisters[i]...EntityType) is an OneToMany or a ManyToOne and
					 * the keys.length > 1 and the relation IsIgnoreNotFound probably we are in presence of
					 * an load with "outer join" the relation can be considerer loaded even if the key is null (mean not found)
					*/
				}
				else
				{
					//If the object is already loaded, return the loaded one
					obj = session.GetEntityUsingInterceptor(key);
					if (obj != null)
					{
						//its already loaded so dont need to hydrate it
						InstanceAlreadyLoaded(rs, i, persisters[i], key, obj, lockModes[i], session);
					}
					else
					{
						obj =
							InstanceNotYetLoaded(rs, i, persisters[i], key, lockModes[i], descriptors[i].RowIdAlias, optionalObjectKey,
							                     optionalObject, hydratedObjects, session);
					}
				}

				rowResults[i] = obj;
			}
			return rowResults;
		}
		protected void InitProjection(SqlString projectionString, SqlString whereString, SqlString orderByString, SqlString groupByString, SqlString havingString, IDictionary<string, IFilter> enabledFilters, LockMode lockMode)
		{
			WalkEntityTree(persister, Alias);
			Persisters = new ILoadable[0];
			InitStatementString(projectionString, whereString, orderByString, groupByString.ToString(), havingString, lockMode);
		}
Пример #59
0
		/// <summary>
		/// Hydrate the state of an object from the SQL <c>IDataReader</c>, into
		/// an array of "hydrated" values (do not resolve associations yet),
		/// and pass the hydrated state to the session.
		/// </summary>
		private void LoadFromResultSet(IDataReader rs, int i, object obj, string instanceClass, EntityKey key,
		                               string rowIdAlias, LockMode lockMode, ILoadable rootPersister,
		                               ISessionImplementor session)
		{
			object id = key.Identifier;

			// Get the persister for the _subclass_
			ILoadable persister = (ILoadable) Factory.GetEntityPersister(instanceClass);

			if (log.IsDebugEnabled)
			{
				log.Debug("Initializing object from DataReader: " + MessageHelper.InfoString(persister, id));
			}

			bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i);

			// add temp entry so that the next step is circular-reference
			// safe - only needed because some types don't take proper
			// advantage of two-phase-load (esp. components)
			TwoPhaseLoad.AddUninitializedEntity(key, obj, persister, lockMode, !eagerPropertyFetch, session);

			// This is not very nice (and quite slow):
			string[][] cols = persister == rootPersister
			                  	? EntityAliases[i].SuffixedPropertyAliases
			                  	: EntityAliases[i].GetSuffixedPropertyAliases(persister);

			object[] values = persister.Hydrate(rs, id, obj, rootPersister, cols, eagerPropertyFetch, session);

			object rowId = persister.HasRowId ? rs[rowIdAlias] : null;

			IAssociationType[] ownerAssociationTypes = OwnerAssociationTypes;
			if (ownerAssociationTypes != null && ownerAssociationTypes[i] != null)
			{
				string ukName = ownerAssociationTypes[i].RHSUniqueKeyPropertyName;
				if (ukName != null)
				{
					int index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName);
					IType type = persister.PropertyTypes[index];

					// polymorphism not really handled completely correctly,
					// perhaps...well, actually its ok, assuming that the
					// entity name used in the lookup is the same as the
					// the one used here, which it will be

					EntityUniqueKey euk =
						new EntityUniqueKey(rootPersister.EntityName, ukName, type.SemiResolve(values[index], session, obj), type,
						                    session.EntityMode, session.Factory);
					session.PersistenceContext.AddEntity(euk, obj);
				}
			}

			TwoPhaseLoad.PostHydrate(persister, id, values, rowId, obj, lockMode, !eagerPropertyFetch, session);
		}
		protected virtual string GetDiscriminatorAlias(ILoadable persister, string suffix)
		{
			return persister.GetDiscriminatorAlias(suffix);
		}