From af96a88e64ee06dadf1e5dd7f2d4b99ad12d50b5 Mon Sep 17 00:00:00 2001 From: Vilen Tambovtsev Date: Thu, 14 May 2015 13:48:52 +0300 Subject: [PATCH 1/6] initial migration to 4.0 --- .gitignore | 4 +- .../App.config | 28 +++- ...ord.Framework.Internal.Tests-vs2010.csproj | 31 ++-- .../packages.config | 7 + ...tle.ActiveRecord.Tests.Model-vs2010.csproj | 34 +++- .../app.config | 6 + .../packages.config | 6 + .../App-net-3.5.config | 148 +++++++++--------- src/Castle.ActiveRecord.Tests/App.config | 128 ++++++++------- .../Castle.ActiveRecord.Tests-vs2010.csproj | 57 ++++--- .../Event/EventListenerAttributeTest.cs | 4 +- .../Model/GenericModel/Company.cs | 4 +- .../Model/GenericModel/Person.cs | 9 +- .../Model/LazyModel/ProductLazy.cs | 5 +- src/Castle.ActiveRecord.Tests/Model/Order.cs | 5 +- .../Model/Product.cs | 6 +- .../Model/StrictModel/Estrato.cs | 9 +- .../Model/StrictModel/QuestionContainer.cs | 5 +- .../TableHierarchyTestCase.cs | 5 +- src/Castle.ActiveRecord.Tests/packages.config | 10 ++ .../Castle.ActiveRecord.Web.csproj | 37 +++-- src/Castle.ActiveRecord.Web/app.config | 15 ++ src/Castle.ActiveRecord.Web/packages.config | 4 + .../ByteCode/LazyInitializer.cs | 75 +++++---- .../ByteCode/ProxyFactory.cs | 49 ++---- .../Castle.ActiveRecord-vs2010.csproj | 53 ++++--- .../Framework/ActiveRecordStarter.cs | 6 +- .../Config/DefaultDatabaseConfiguration.cs | 2 - .../EventListener/EventListenerContributor.cs | 6 +- .../Visitors/SemanticVerifierVisitor.cs | 6 +- .../Framework/Queries/LinqQuery.cs | 95 +++++------ .../Framework/SessionFactoryHolder.cs | 28 ++-- .../Framework/StatelessSessionWrapper.cs | 125 +++++++++++++-- .../Framework/SupportingUtils.cs | 35 ++--- src/Castle.ActiveRecord/packages.config | 11 ++ 35 files changed, 655 insertions(+), 403 deletions(-) create mode 100644 src/Castle.ActiveRecord.Framework.Internal.Tests/packages.config create mode 100644 src/Castle.ActiveRecord.Tests.Model/app.config create mode 100644 src/Castle.ActiveRecord.Tests.Model/packages.config create mode 100644 src/Castle.ActiveRecord.Tests/packages.config create mode 100644 src/Castle.ActiveRecord.Web/app.config create mode 100644 src/Castle.ActiveRecord.Web/packages.config create mode 100644 src/Castle.ActiveRecord/packages.config diff --git a/.gitignore b/.gitignore index a62522e..97b831b 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,6 @@ _ReSharper* *ReSharper.* *.suo *.cache -* Thumbs.db \ No newline at end of file +* Thumbs.db +*.user +**/packages/** \ No newline at end of file diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config b/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config index d167f95..74f8820 100644 --- a/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config @@ -1,20 +1,18 @@ - + -
-
+
+
- - + + @@ -46,4 +44,20 @@ --> + + + + + + + + + + + + + + + + diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/Castle.ActiveRecord.Framework.Internal.Tests-vs2010.csproj b/src/Castle.ActiveRecord.Framework.Internal.Tests/Castle.ActiveRecord.Framework.Internal.Tests-vs2010.csproj index 15d8eb1..90b359a 100644 --- a/src/Castle.ActiveRecord.Framework.Internal.Tests/Castle.ActiveRecord.Framework.Internal.Tests-vs2010.csproj +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/Castle.ActiveRecord.Framework.Internal.Tests-vs2010.csproj @@ -6,6 +6,7 @@ Client NET40-Debug AnyCPU + 2b20b678 Local @@ -100,17 +101,17 @@ False ..\..\lib\$(BuildConfigKey)\Castle.Components.Validator.dll - - False - ..\..\lib\$(BuildConfigKey)\Castle.Core.dll + + ..\..\packages\Castle.Core.3.3.3\lib\net40-client\Castle.Core.dll + True - - False - ..\..\lib\Iesi.Collections.dll + + ..\..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll + True - - False - ..\..\lib\NHibernate.dll + + ..\..\packages\NHibernate.4.0.3.4000\lib\net40\NHibernate.dll + True nunit.framework @@ -126,6 +127,10 @@ System.Data + + ..\..\packages\System.Data.SQLite.Core.1.0.96.0\lib\net40\System.Data.SQLite.dll + True + System.XML @@ -247,6 +252,7 @@ + @@ -291,4 +297,11 @@ xcopy "$(ProjectDir)App.config" "$(TargetDir)" /y/c move /y "$(TargetDir)App.config" "$(TargetDir)$(TargetFileName).config" + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/packages.config b/src/Castle.ActiveRecord.Framework.Internal.Tests/packages.config new file mode 100644 index 0000000..73cd3e3 --- /dev/null +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/src/Castle.ActiveRecord.Tests.Model/Castle.ActiveRecord.Tests.Model-vs2010.csproj b/src/Castle.ActiveRecord.Tests.Model/Castle.ActiveRecord.Tests.Model-vs2010.csproj index 5ebf5bc..c4f0eb2 100644 --- a/src/Castle.ActiveRecord.Tests.Model/Castle.ActiveRecord.Tests.Model-vs2010.csproj +++ b/src/Castle.ActiveRecord.Tests.Model/Castle.ActiveRecord.Tests.Model-vs2010.csproj @@ -4,8 +4,9 @@ $(MSBuildProjectDirectory)\..\.. v4.0 Client - NET40-Debug + NET40-Debug AnyCPU + c355086d 9.0.30729 @@ -21,11 +22,10 @@ 3.5 - v4.0 - + bin\NET40-Debug\ true full @@ -42,7 +42,7 @@ v4.0 - + bin\NET40-Release\ pdbonly true @@ -81,20 +81,27 @@ AnyCPU prompt - False ..\..\lib\$(BuildConfigKey)\Castle.Components.Validator.dll - - False - ..\..\lib\NHibernate.dll + + ..\..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll + True + + + ..\..\packages\NHibernate.4.0.3.4000\lib\net40\NHibernate.dll + True 3.5 + + ..\..\packages\System.Data.SQLite.Core.1.0.96.0\lib\net40\System.Data.SQLite.dll + True + 3.5 @@ -140,9 +147,20 @@ Castle.ActiveRecord-vs2010 + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/src/Castle.ActiveRecord.Tests/App.config b/src/Castle.ActiveRecord.Tests/App.config index d65f0e7..4718b5e 100644 --- a/src/Castle.ActiveRecord.Tests/App.config +++ b/src/Castle.ActiveRecord.Tests/App.config @@ -1,65 +1,85 @@ - + + +
+
+ - -
-
- + - + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + + + - - - - + - - - - - + + - - - - + + + + + - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Castle.ActiveRecord.Tests/Castle.ActiveRecord.Tests-vs2010.csproj b/src/Castle.ActiveRecord.Tests/Castle.ActiveRecord.Tests-vs2010.csproj index 2ffae67..3742a52 100644 --- a/src/Castle.ActiveRecord.Tests/Castle.ActiveRecord.Tests-vs2010.csproj +++ b/src/Castle.ActiveRecord.Tests/Castle.ActiveRecord.Tests-vs2010.csproj @@ -6,6 +6,7 @@ Client NET40-Debug AnyCPU + 5454b8ca Local @@ -99,44 +100,44 @@ Castle.ActiveRecord.Tests.Model-vs2010 - {3A0B9A64-8140-429E-A3F0-5B1617CEB466} + {3a0b9a64-8140-429e-a3f0-5b1617ceb466} Castle.ActiveRecord.Web - {652F95D4-86E2-40B6-919D-CFC6E449386B} + {652f95d4-86e2-40b6-919d-cfc6e449386b} Castle.ActiveRecord-vs2010 False ..\..\lib\$(BuildConfigKey)\Castle.Components.Validator.dll - - False - ..\..\lib\$(BuildConfigKey)\Castle.Core.dll + + ..\..\packages\Castle.Core.3.3.3\lib\net40-client\Castle.Core.dll + True - - False - ..\..\lib\Iesi.Collections.dll + + ..\..\packages\SharpZipLib.0.86.0\lib\20\ICSharpCode.SharpZipLib.dll + True + + + ..\..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll + True False ..\..\lib\$(BuildConfigKey)\log4net.dll - - False - ..\..\lib\Lucene.Net.dll + + ..\..\packages\Lucene.Net.3.0.3\lib\NET40\Lucene.Net.dll + True - - False - ..\..\lib\NHibernate.dll + + ..\..\packages\NHibernate.4.0.3.4000\lib\net40\NHibernate.dll + True - - False - ..\..\lib\NHibernate.ByteCode.Castle.dll - - - False - ..\..\lib\NHibernate.Search.dll + + ..\..\packages\NHibernate.Search.MB.4.0.3.4000\lib\net40\NHibernate.Search.dll + True nunit.framework @@ -152,9 +153,9 @@ System.Data - - False - ..\..\lib\$(BuildConfigKey)\System.Data.SQLite.DLL + + ..\..\packages\System.Data.SQLite.Core.1.0.96.0\lib\net40\System.Data.SQLite.dll + True System.XML @@ -332,6 +333,7 @@ + @@ -440,4 +442,11 @@ + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs b/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs index fbbfdf7..6bf40b0 100644 --- a/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs +++ b/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs @@ -18,6 +18,8 @@ namespace Castle.ActiveRecord.Tests.Event { using Iesi.Collections; using System; + using System.Collections.Generic; + using NUnit.Framework; using Castle.ActiveRecord; using Castle.ActiveRecord.Tests.Model; @@ -244,7 +246,7 @@ private class MultipleSkippedReplacementListener : ILoadEventListener, IDeleteEv { public void OnLoad(LoadEvent @event, LoadType loadType){} public void OnDelete(DeleteEvent @event){} - public void OnDelete(DeleteEvent @event, ISet transientEntities){} + public void OnDelete(DeleteEvent @event, ISet transientEntities) {} } [EventListener(Singleton = true)] diff --git a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Company.cs b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Company.cs index 9e2c504..c9222ed 100644 --- a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Company.cs +++ b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Company.cs @@ -16,6 +16,8 @@ namespace Castle.ActiveRecord.Tests.Model.GenericModel { using System; using System.Collections; + using System.Collections.Generic; + using Iesi.Collections.Generic; [ActiveRecord( "Companies", DiscriminatorColumn = "type", DiscriminatorType = "String", DiscriminatorValue = "company" )] @@ -23,7 +25,7 @@ public class Company : ActiveRecordBase { private int id; private String name; - private ISet _people = new HashedSet(); + private ISet _people = new HashSet(); private PostalAddress _address; public Company() diff --git a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs index da54351..d6720b0 100644 --- a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs +++ b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs @@ -16,17 +16,18 @@ namespace Castle.ActiveRecord.Tests.Model.GenericModel { using System; using System.Collections; + using System.Collections.Generic; - [ActiveRecord("People")] + [ActiveRecord("People")] public class Person : ActiveRecordBase { private int _id; private String _name; - private IList _companies; + private IList _companies; public Person() { - _companies = new ArrayList(); + _companies = new List(); } [PrimaryKey] @@ -44,7 +45,7 @@ public string Name } [HasAndBelongsToMany( typeof(Company), RelationType.Bag, Table="PeopleCompanies", ColumnRef="company_id", ColumnKey="person_id" )] - public IList Companies + public IList Companies { get { return _companies; } set { _companies = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs b/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs index d465d5c..7d17afe 100644 --- a/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs +++ b/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs @@ -15,6 +15,7 @@ namespace Castle.ActiveRecord.Tests.Model.LazyModel { using System; + using System.Collections.Generic; using Iesi.Collections; @@ -23,7 +24,7 @@ namespace Castle.ActiveRecord.Tests.Model.LazyModel public class ProductLazy : ActiveRecordValidationBase { private int id; - private ISet categories = new HashedSet(); + private ISet categories = new HashSet(); public ProductLazy() { @@ -37,7 +38,7 @@ public int Id } [HasMany( typeof(CategoryLazy), Lazy=true, Cascade=ManyRelationCascadeEnum.All )] - public ISet Categories + public ISet Categories { get { return categories; } set { categories = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/Order.cs b/src/Castle.ActiveRecord.Tests/Model/Order.cs index 46bcdb5..6da2fcd 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Order.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Order.cs @@ -16,6 +16,7 @@ namespace Castle.ActiveRecord.Tests.Model { using System; using System.Collections; + using System.Collections.Generic; using Iesi.Collections; @@ -26,7 +27,7 @@ public class Order : ActiveRecordBase private int id; private DateTime ordered_date; private Boolean shipped; - private ISet _products; + private ISet _products; [PrimaryKey(PrimaryKeyType.Native, "OrderID")] public int ID @@ -57,7 +58,7 @@ public static Order Find(int id) [HasAndBelongsToMany(typeof (Product), RelationType.Set, Table="line_item", ColumnRef="product_id", ColumnKey="order_id")] - public ISet Products + public ISet Products { get { return _products; } set { _products = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/Product.cs b/src/Castle.ActiveRecord.Tests/Model/Product.cs index 8bdf0aa..39cc65d 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Product.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Product.cs @@ -15,6 +15,8 @@ namespace Castle.ActiveRecord.Tests.Model { using System.Collections; + using System.Collections.Generic; + using Iesi.Collections; [ActiveRecord("Product")] @@ -24,7 +26,7 @@ public class Product : ActiveRecordBase private string product_name; private float price; private string serial_number; - private ISet _orders; + private ISet _orders; [PrimaryKey(PrimaryKeyType.Native, "ProductID")] public int ID @@ -57,7 +59,7 @@ public float Price [HasAndBelongsToMany(typeof (Order), RelationType.Set, Table="line_item", ColumnRef="order_id", ColumnKey="product_id", Inverse=true)] - public ISet Orders + public ISet Orders { get { return _orders; } set { _orders = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs b/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs index b7157fb..5031fe3 100644 --- a/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs +++ b/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs @@ -15,6 +15,7 @@ namespace Castle.ActiveRecord.Tests.Model.StrictModel { using System; + using System.Collections.Generic; using Iesi.Collections; @@ -32,8 +33,8 @@ public class Estrato : ActiveRecordValidationBase private EstratoType type; private QuestionContainer container; private Estrato parentEstrato; - private ISet subestratos = new ListSet(); - private ISet references = new ListSet(); + private ISet subestratos = new HashSet(); + private ISet references = new HashSet(); public Estrato() { @@ -61,7 +62,7 @@ public QuestionContainer Container } [HasAndBelongsToMany( typeof(Estrato), Table="EstratoRefEstrato", ColumnRef="ref_estrato_id", ColumnKey="estrato_id" )] - public ISet ReferencedEstratos + public ISet ReferencedEstratos { get { return references; } set { references = value; } @@ -75,7 +76,7 @@ public Estrato ParentEstrato } [HasMany( typeof(Estrato), Inverse=true, Cascade=ManyRelationCascadeEnum.All)] - public ISet SubEstratos + public ISet SubEstratos { get { return subestratos; } set { subestratos = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs b/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs index 5b2d08e..19154d6 100644 --- a/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs +++ b/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs @@ -15,6 +15,7 @@ namespace Castle.ActiveRecord.Tests.Model.StrictModel { using System; + using System.Collections.Generic; using Iesi.Collections; @@ -30,7 +31,7 @@ public class QuestionContainer : ActiveRecordValidationBase { private int id; private ContainerType type; - private ISet estratos = new ListSet(); + private ISet estratos = new HashSet(); public QuestionContainer() { @@ -51,7 +52,7 @@ public ContainerType Type } [HasMany( typeof(Estrato), Inverse=true)] - public ISet Estratos + public ISet Estratos { get { return estratos; } set { estratos = value; } diff --git a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs index df434ca..ce4fa18 100644 --- a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs @@ -16,6 +16,7 @@ namespace Castle.ActiveRecord.Tests { using System; using System.Collections; + using System.Collections.Generic; using NUnit.Framework; @@ -112,14 +113,14 @@ public void ManyToManyUsingSet() using (new SessionScope()) { coolGadget.Save(); - ISet products = new ListSet(); + ISet products = new HashSet(); products.Add(coolGadget); myOrder.Products = products; myOrder.Save(); } Order secondRef2Order = Order.Find(myOrder.ID); - Assert.IsFalse(secondRef2Order.Products.IsEmpty); + Assert.IsFalse(secondRef2Order.Products.Count == 0); Product secondRef2Product = Product.Find(coolGadget.ID); Assert.AreEqual(1, secondRef2Product.Orders.Count); diff --git a/src/Castle.ActiveRecord.Tests/packages.config b/src/Castle.ActiveRecord.Tests/packages.config new file mode 100644 index 0000000..4c7fd8f --- /dev/null +++ b/src/Castle.ActiveRecord.Tests/packages.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/Castle.ActiveRecord.Web/Castle.ActiveRecord.Web.csproj b/src/Castle.ActiveRecord.Web/Castle.ActiveRecord.Web.csproj index de734ed..effca95 100644 --- a/src/Castle.ActiveRecord.Web/Castle.ActiveRecord.Web.csproj +++ b/src/Castle.ActiveRecord.Web/Castle.ActiveRecord.Web.csproj @@ -4,8 +4,9 @@ $(MSBuildProjectDirectory)\..\.. v4.0 Client - NET40-Debug + NET40-Debug AnyCPU + c107c0fb 8.0.30703 @@ -21,7 +22,7 @@ v4.0 - + bin\NET40-Debug\ true full @@ -38,12 +39,12 @@ v4.0 - + bin\NET40-Release\ pdbonly true TRACE;PHYSICALASSEMBLY DOTNET DOTNET40 CLIENTPROFILE - bin\NET40-Release\Castle.ActiveRecord.Web.xml + bin\NET40-Release\Castle.ActiveRecord.Web.xml prompt 4 1591 @@ -71,7 +72,7 @@ bin\NET35-Release\ TRACE;PHYSICALASSEMBLY DOTNET DOTNET35 - bin\NET40-Release\Castle.ActiveRecord.Web.xml + bin\NET40-Release\Castle.ActiveRecord.Web.xml true true 1591 @@ -83,11 +84,12 @@ ..\..\lib\$(BuildConfigKey)\Castle.Components.Validator.dll - - ..\..\lib\NHibernate.dll - + + ..\..\packages\System.Data.SQLite.Core.1.0.96.0\lib\net40\System.Data.SQLite.dll + True + @@ -101,18 +103,29 @@ + + + + + + + - {652F95D4-86E2-40B6-919D-CFC6E449386B} + {652f95d4-86e2-40b6-919d-cfc6e449386b} Castle.ActiveRecord-vs2010 - - - + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/AssemblyXmlGenerationTestCase.cs b/src/Castle.ActiveRecord.Framework.Internal.Tests/AssemblyXmlGenerationTestCase.cs index 3cfbfae..9eb4ec4 100644 --- a/src/Castle.ActiveRecord.Framework.Internal.Tests/AssemblyXmlGenerationTestCase.cs +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/AssemblyXmlGenerationTestCase.cs @@ -62,14 +62,9 @@ public void CanGetCustomValueFromRawXmlDerivedAttribute() public void WillUseRegisteredAssembliesToLookForRawMappingXmlEvenIfThereAreNoActiveRecordTypesInThatAssembly() { ActiveRecordStarter.ResetInitializationFlag(); - ActiveRecordStarter.Initialize( - typeof(RegisterNHibernateClassMapping).Assembly, - GetConfigSource() - ); - ISessionFactory factory = ActiveRecordMediator.GetSessionFactoryHolder() - .GetSessionFactory(typeof(ActiveRecordBase)); - IClassMetadata metadata = factory - .GetClassMetadata(typeof(NHibernateClass)); + ActiveRecordStarter.Initialize(typeof(RegisterNHibernateClassMapping).Assembly, GetConfigSource()); + ISessionFactory factory = ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof(ActiveRecordBase)); + IClassMetadata metadata = factory.GetClassMetadata(typeof(NHibernateClass)); Assert.IsNotNull(metadata); } } diff --git a/src/Castle.ActiveRecord.Tests/App-net-2.0.config b/src/Castle.ActiveRecord.Tests/App-net-2.0.config index 5ee50b1..f979fd0 100644 --- a/src/Castle.ActiveRecord.Tests/App-net-2.0.config +++ b/src/Castle.ActiveRecord.Tests/App-net-2.0.config @@ -1,55 +1,55 @@ - - - - - -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -57,26 +57,26 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Castle.ActiveRecord.Tests/App.config b/src/Castle.ActiveRecord.Tests/App.config index 4718b5e..29c72bb 100644 --- a/src/Castle.ActiveRecord.Tests/App.config +++ b/src/Castle.ActiveRecord.Tests/App.config @@ -9,7 +9,7 @@ - + @@ -18,7 +18,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -36,7 +36,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs b/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs index c03c786..f822bd7 100644 --- a/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs +++ b/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs @@ -232,9 +232,9 @@ private static string GetDefaultHibernateConfigAndCloseActiveRecordSection() { return @" - + - + "; } diff --git a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs index 87ddf09..a56f67b 100644 --- a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs @@ -14,42 +14,42 @@ namespace Castle.ActiveRecord.Tests { - using System.Collections.Generic; - using Castle.ActiveRecord.Framework; - using Castle.ActiveRecord.Framework.Config; - using NUnit.Framework; - - [TestFixture] - public class InvalidRootTypeTestCase - { - protected IConfigurationSource GetConfigSource() - { - InPlaceConfigurationSource source = new InPlaceConfigurationSource(); - - Dictionary properties = new Dictionary(); - properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); - properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2000Dialect"); - properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); - properties.Add("hibernate.connection.connection_string", - "Data Source=.;Initial Catalog=test;Integrated Security=SSPI"); - - source.Add(typeof(ActiveRecordBase), properties); - source.Add(typeof(NonAbstractRootType), properties); - - return source; - } - - [Test, ExpectedException(typeof(ActiveRecordException))] - public void RootTypeIsNotAbstract() - { - ActiveRecordStarter.ResetInitializationFlag(); - - ActiveRecordStarter.Initialize(GetConfigSource(), - typeof(NonAbstractRootType)); - } - - public class NonAbstractRootType : ActiveRecordBase - { - } - } + using System.Collections.Generic; + using Castle.ActiveRecord.Framework; + using Castle.ActiveRecord.Framework.Config; + using NUnit.Framework; + + [TestFixture] + public class InvalidRootTypeTestCase + { + protected IConfigurationSource GetConfigSource() + { + InPlaceConfigurationSource source = new InPlaceConfigurationSource(); + + Dictionary properties = new Dictionary(); + properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); + properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2008Dialect"); + properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); + properties.Add("hibernate.connection.connection_string", + "Data Source=.;Initial Catalog=Test;Integrated Security=true"); + + source.Add(typeof(ActiveRecordBase), properties); + source.Add(typeof(NonAbstractRootType), properties); + + return source; + } + + [Test, ExpectedException(typeof(ActiveRecordException))] + public void RootTypeIsNotAbstract() + { + ActiveRecordStarter.ResetInitializationFlag(); + + ActiveRecordStarter.Initialize(GetConfigSource(), + typeof(NonAbstractRootType)); + } + + public class NonAbstractRootType : ActiveRecordBase + { + } + } } diff --git a/src/Castle.ActiveRecord.Tests/Model/Person.cs b/src/Castle.ActiveRecord.Tests/Model/Person.cs index d69559a..33e7c16 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Person.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Person.cs @@ -16,8 +16,9 @@ namespace Castle.ActiveRecord.Tests.Model { using System; using System.Collections; + using System.Collections.Generic; - [ActiveRecord("People"), + [ActiveRecord("People"), JoinedTable("Addresses", Column = "person_id")] public class Person : ActiveRecordBase { @@ -25,12 +26,12 @@ public class Person : ActiveRecordBase private String _name; private FullName _fullName; private String _address; - private IList _companies; + private IList _companies; private Blog _blog; public Person() { - _companies = new ArrayList(); + _companies = new List(); } [PrimaryKey] @@ -72,7 +73,7 @@ public Blog Blog } [HasAndBelongsToMany( typeof(Company), RelationType.Bag, Table="PeopleCompanies", ColumnRef="company_id", ColumnKey="person_id" )] - public IList Companies + public IList Companies { get { return _companies; } set { _companies = value; } diff --git a/src/Castle.ActiveRecord/Framework/ActiveRecordBase.cs b/src/Castle.ActiveRecord/Framework/ActiveRecordBase.cs index 09d3d7d..7533591 100644 --- a/src/Castle.ActiveRecord/Framework/ActiveRecordBase.cs +++ b/src/Castle.ActiveRecord/Framework/ActiveRecordBase.cs @@ -14,628 +14,1376 @@ namespace Castle.ActiveRecord { - using System; - using System.Collections; - using System.Collections.Generic; - using Castle.ActiveRecord.Framework; - using Castle.ActiveRecord.Framework.Internal; - using Castle.ActiveRecord.Queries; - - using NHibernate; - using NHibernate.Criterion; - using Castle.Components.Validator; - - /// - /// Allow custom executions using the NHibernate's ISession. - /// - public delegate object NHibernateDelegate(ISession session, object instance); - - /// - /// Base class for all ActiveRecord classes. Implements - /// all the functionality to simplify the code on the - /// subclasses. - /// - [Serializable] - public abstract class ActiveRecordBase : ActiveRecordHooksBase - { - /// - /// The global holder for the session factories. - /// - protected internal static ISessionFactoryHolder holder; - - #region internal static - - internal static void EnsureInitialized(Type type) - { - if (holder == null) - { - String message = String.Format("An ActiveRecord class ({0}) was used but the framework seems not " + - "properly initialized. Did you forget about ActiveRecordStarter.Initialize() ?", - type.FullName); - throw new ActiveRecordException(message); - } - if (type != typeof(ActiveRecordBase) && GetModel(type) == null) - { - String message = String.Format("You have accessed an ActiveRecord class that wasn't properly initialized. " + - "There are two possible explanations: that the call to ActiveRecordStarter.Initialize() didn't include {0} class, or that {0} class is not decorated with the [ActiveRecord] attribute.", - type.FullName); - throw new ActiveRecordException(message); - } - } - - /// - /// Internally used - /// - /// The type. - /// The model. - internal static void Register(Type arType, ActiveRecordModel model) - { - ActiveRecordModel.Register(arType, model); - } - - /// - /// Internally used - /// - /// The type. - /// An - internal static ActiveRecordModel GetModel(Type arType) - { - return ActiveRecordModel.GetModel(arType); - } - - #endregion - - #region protected internal static - - #region Create/Update/Save/Delete/DeleteAll/Refresh - - #region Create - - /// - /// Creates (Saves) a new instance to the database. - /// - /// The ActiveRecord instance to be created on the database - protected internal static void Create(object instance) - { - InternalCreate(instance, false); - } - - /// - /// Creates (Saves) a new instance to the database and flushes the session. - /// - /// The ActiveRecord instance to be created on the database - protected internal static void CreateAndFlush(object instance) - { - InternalCreate(instance, true); - } - - /// - /// Creates (Saves) a new instance to the database. - /// - /// The ActiveRecord instance to be created on the database - /// if set to true, the operation will be followed by a session flush. - private static void InternalCreate(object instance, bool flush) - { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.Save(instance); - - if (flush) - { - session.Flush(); - } - } - catch(Exception ex) - { - holder.FailSession(session); - - // NHibernate catches our ValidationException, and as such it is the innerexception here - if (ex is ValidationException) - throw ; - - if (ex.InnerException is ValidationException) - throw ex.InnerException; - - throw new ActiveRecordException("Could not perform Create for " + instance.GetType().Name, ex); - - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region Delete - - /// - /// Deletes the instance from the database. - /// - /// The ActiveRecord instance to be deleted - protected internal static void Delete(object instance) - { - InternalDelete(instance, false); - } - - /// - /// Deletes the instance from the database and flushes the session. - /// - /// The ActiveRecord instance to be deleted - protected internal static void DeleteAndFlush(object instance) - { - InternalDelete(instance, true); - } - - /// - /// Deletes the instance from the database. - /// - /// The ActiveRecord instance to be deleted - /// if set to true, the operation will be followed by a session flush. - private static void InternalDelete(object instance, bool flush) - { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.Delete(instance); - - if (flush) - { - session.Flush(); - } - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform Delete for " + instance.GetType().Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region Replicate - - /// - /// From NHibernate documentation: - /// Persist all reachable transient objects, reusing the current identifier - /// values. Note that this will not trigger the Interceptor of the Session. - /// - /// The instance. - /// The replication mode. - protected internal static void Replicate(object instance, ReplicationMode replicationMode) - { - if (instance == null) - { - throw new ArgumentNullException("instance"); - } - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.Replicate(instance, replicationMode); - } - catch(Exception ex) - { - holder.FailSession(session); - - // NHibernate catches our ValidationException, and as such it is the innerexception here - if (ex.InnerException is ValidationException) - { - throw ex.InnerException; - } - else - { - throw new ActiveRecordException("Could not perform Replicate for " + instance.GetType().Name, ex); - } - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region Refresh - - /// - /// Refresh the instance from the database. - /// - /// The ActiveRecord instance to be reloaded - protected internal static void Refresh(object instance) - { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.Refresh(instance); - } - catch (Exception ex) - { - holder.FailSession(session); - - // NHibernate catches our ValidationException, and as such it is the innerexception here - if (ex.InnerException is ValidationException) - { - throw ex.InnerException; - } - else - { - throw new ActiveRecordException("Could not perform Refresh for " + instance.GetType().Name, ex); - } - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region DeleteAll - - /// - /// Deletes all rows for the specified ActiveRecord type - /// - /// - /// This method is usually useful for test cases. - /// - /// ActiveRecord type on which the rows on the database should be deleted - protected internal static void DeleteAll(Type type) - { - - EnsureInitialized(type); - - ActiveRecordModel model = GetModel (type); + using System; + using System.Collections; + using System.Collections.Generic; + using Castle.ActiveRecord.Framework; + using Castle.ActiveRecord.Framework.Internal; + using Castle.ActiveRecord.Queries; + + using NHibernate; + using NHibernate.Criterion; + using Castle.Components.Validator; + + /// + /// Allow custom executions using the NHibernate's ISession. + /// + public delegate object NHibernateDelegate(ISession session, object instance); + + /// + /// Base class for all ActiveRecord classes. Implements + /// all the functionality to simplify the code on the + /// subclasses. + /// + [Serializable] + public abstract class ActiveRecordBase : ActiveRecordHooksBase + { + /// + /// The global holder for the session factories. + /// + protected internal static ISessionFactoryHolder holder; + + #region internal static + + internal static void EnsureInitialized(Type type) + { + if (holder == null) + { + String message = String.Format("An ActiveRecord class ({0}) was used but the framework seems not " + + "properly initialized. Did you forget about ActiveRecordStarter.Initialize() ?", + type.FullName); + throw new ActiveRecordException(message); + } + if (type != typeof(ActiveRecordBase) && GetModel(type) == null) + { + String message = String.Format("You have accessed an ActiveRecord class that wasn't properly initialized. " + + "There are two possible explanations: that the call to ActiveRecordStarter.Initialize() didn't include {0} class, or that {0} class is not decorated with the [ActiveRecord] attribute.", + type.FullName); + throw new ActiveRecordException(message); + } + } + + /// + /// Internally used + /// + /// The type. + /// The model. + internal static void Register(Type arType, ActiveRecordModel model) + { + ActiveRecordModel.Register(arType, model); + } + + /// + /// Internally used + /// + /// The type. + /// An + internal static ActiveRecordModel GetModel(Type arType) + { + return ActiveRecordModel.GetModel(arType); + } + + #endregion + + #region protected internal static + + #region Create/Update/Save/Delete/DeleteAll/Refresh + + #region Create + + /// + /// Creates (Saves) a new instance to the database. + /// + /// The ActiveRecord instance to be created on the database + protected internal static void Create(object instance) + { + InternalCreate(instance, false); + } + + /// + /// Creates (Saves) a new instance to the database and flushes the session. + /// + /// The ActiveRecord instance to be created on the database + protected internal static void CreateAndFlush(object instance) + { + InternalCreate(instance, true); + } + + /// + /// Creates (Saves) a new instance to the database. + /// + /// The ActiveRecord instance to be created on the database + /// if set to true, the operation will be followed by a session flush. + private static void InternalCreate(object instance, bool flush) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.Save(instance); + + if (flush) + { + session.Flush(); + } + } + catch (Exception ex) + { + holder.FailSession(session); + + // NHibernate catches our ValidationException, and as such it is the innerexception here + if (ex is ValidationException) + throw; + + if (ex.InnerException is ValidationException) + throw ex.InnerException; + + throw new ActiveRecordException("Could not perform Create for " + instance.GetType().Name, ex); + + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region Delete + + /// + /// Deletes the instance from the database. + /// + /// The ActiveRecord instance to be deleted + protected internal static void Delete(object instance) + { + InternalDelete(instance, false); + } + + /// + /// Deletes the instance from the database and flushes the session. + /// + /// The ActiveRecord instance to be deleted + protected internal static void DeleteAndFlush(object instance) + { + InternalDelete(instance, true); + } + + /// + /// Deletes the instance from the database. + /// + /// The ActiveRecord instance to be deleted + /// if set to true, the operation will be followed by a session flush. + private static void InternalDelete(object instance, bool flush) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.Delete(instance); + + if (flush) + { + session.Flush(); + } + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform Delete for " + instance.GetType().Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region Replicate + + /// + /// From NHibernate documentation: + /// Persist all reachable transient objects, reusing the current identifier + /// values. Note that this will not trigger the Interceptor of the Session. + /// + /// The instance. + /// The replication mode. + protected internal static void Replicate(object instance, ReplicationMode replicationMode) + { + if (instance == null) + { + throw new ArgumentNullException("instance"); + } + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.Replicate(instance, replicationMode); + } + catch (Exception ex) + { + holder.FailSession(session); + + // NHibernate catches our ValidationException, and as such it is the innerexception here + if (ex.InnerException is ValidationException) + { + throw ex.InnerException; + } + else + { + throw new ActiveRecordException("Could not perform Replicate for " + instance.GetType().Name, ex); + } + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region Refresh + + /// + /// Refresh the instance from the database. + /// + /// The ActiveRecord instance to be reloaded + protected internal static void Refresh(object instance) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.Refresh(instance); + } + catch (Exception ex) + { + holder.FailSession(session); + + // NHibernate catches our ValidationException, and as such it is the innerexception here + if (ex.InnerException is ValidationException) + { + throw ex.InnerException; + } + else + { + throw new ActiveRecordException("Could not perform Refresh for " + instance.GetType().Name, ex); + } + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region DeleteAll + + /// + /// Deletes all rows for the specified ActiveRecord type + /// + /// + /// This method is usually useful for test cases. + /// + /// ActiveRecord type on which the rows on the database should be deleted + protected internal static void DeleteAll(Type type) + { + + EnsureInitialized(type); + + ActiveRecordModel model = GetModel(type); string typeName = model.UseAutoImport ? type.Name : type.FullName; - - ISession session = holder.CreateSession(type); - - try - { - session.Delete(String.Format("from {0}", typeName)); - - session.Flush(); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform DeleteAll for " + typeName, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Deletes all rows for the specified ActiveRecord type that matches - /// the supplied HQL condition - /// - /// - /// This method is usually useful for test cases. - /// - /// ActiveRecord type on which the rows on the database should be deleted - /// HQL condition to select the rows to be deleted - protected internal static void DeleteAll(Type type, String where) - { - EnsureInitialized(type); - - ActiveRecordModel model = GetModel (type); + + ISession session = holder.CreateSession(type); + + try + { + session.Delete(String.Format("from {0}", typeName)); + + session.Flush(); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform DeleteAll for " + typeName, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Deletes all rows for the specified ActiveRecord type that matches + /// the supplied HQL condition + /// + /// + /// This method is usually useful for test cases. + /// + /// ActiveRecord type on which the rows on the database should be deleted + /// HQL condition to select the rows to be deleted + protected internal static void DeleteAll(Type type, String where) + { + EnsureInitialized(type); + + ActiveRecordModel model = GetModel(type); string typeName = model.UseAutoImport ? type.Name : type.FullName; - ISession session = holder.CreateSession(type); - - try - { - session.Delete(String.Format("from {0} where {1}", typeName, where)); - - session.Flush(); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform DeleteAll for " + typeName, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Deletes all objects, based on the primary keys - /// supplied on . - /// - /// The target ActiveRecord type - /// A list of primary keys - /// The number of objects deleted - protected internal static int DeleteAll(Type targetType, IEnumerable pkValues) - { - if (pkValues == null) - { - return 0; - } - - int counter = 0; - - foreach (object pk in pkValues) - { - Object obj = FindByPrimaryKey(targetType, pk, false); - - if (obj != null) - { - ActiveRecordBase arBase = obj as ActiveRecordBase; - - if (arBase != null) - { - arBase.Delete(); // in order to allow override of the virtual "Delete()" method - } - else - { - Delete(obj); - } - - counter++; - } - } - - return counter; - } - - #endregion - - #region Update - - /// - /// Persists the modification on the instance - /// state to the database. - /// - /// The ActiveRecord instance to be updated on the database - protected internal static void Update(object instance) - { - InternalUpdate(instance, false); - } - - /// - /// Persists the modification on the instance - /// state to the database and flushes the session. - /// - /// The ActiveRecord instance to be updated on the database - protected internal static void UpdateAndFlush(object instance) - { - InternalUpdate(instance, true); - } - - /// - /// Persists the modification on the instance - /// state to the database. - /// - /// The ActiveRecord instance to be updated on the database - /// if set to true, the operation will be followed by a session flush. - private static void InternalUpdate(object instance, bool flush) - { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.Update(instance); - - if (flush) - { - session.Flush(); - } - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform Update for " + instance.GetType().Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region Save - - /// - /// Saves the instance to the database. If the primary key is unitialized - /// it creates the instance on the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// - /// - /// The ActiveRecord instance to be saved - protected internal static void Save(object instance) - { - InternalSave(instance, false); - } - - /// - /// Saves the instance to the database and flushes the session. If the primary key is unitialized - /// it creates the instance on the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// - /// - /// The ActiveRecord instance to be saved - protected internal static void SaveAndFlush(object instance) - { - InternalSave(instance, true); - } + ISession session = holder.CreateSession(type); + + try + { + session.Delete(String.Format("from {0} where {1}", typeName, where)); + + session.Flush(); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform DeleteAll for " + typeName, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Deletes all objects, based on the primary keys + /// supplied on . + /// + /// The target ActiveRecord type + /// A list of primary keys + /// The number of objects deleted + protected internal static int DeleteAll(Type targetType, IEnumerable pkValues) + { + if (pkValues == null) + { + return 0; + } + + int counter = 0; + + foreach (object pk in pkValues) + { + Object obj = FindByPrimaryKey(targetType, pk, false); + + if (obj != null) + { + ActiveRecordBase arBase = obj as ActiveRecordBase; + + if (arBase != null) + { + arBase.Delete(); // in order to allow override of the virtual "Delete()" method + } + else + { + Delete(obj); + } + + counter++; + } + } + + return counter; + } + + #endregion + + #region Update + + /// + /// Persists the modification on the instance + /// state to the database. + /// + /// The ActiveRecord instance to be updated on the database + protected internal static void Update(object instance) + { + InternalUpdate(instance, false); + } + + /// + /// Persists the modification on the instance + /// state to the database and flushes the session. + /// + /// The ActiveRecord instance to be updated on the database + protected internal static void UpdateAndFlush(object instance) + { + InternalUpdate(instance, true); + } + + /// + /// Persists the modification on the instance + /// state to the database. + /// + /// The ActiveRecord instance to be updated on the database + /// if set to true, the operation will be followed by a session flush. + private static void InternalUpdate(object instance, bool flush) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.Update(instance); + + if (flush) + { + session.Flush(); + } + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform Update for " + instance.GetType().Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region Save + + /// + /// Saves the instance to the database. If the primary key is unitialized + /// it creates the instance on the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The ActiveRecord instance to be saved + protected internal static void Save(object instance) + { + InternalSave(instance, false); + } + + /// + /// Saves the instance to the database and flushes the session. If the primary key is unitialized + /// it creates the instance on the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The ActiveRecord instance to be saved + protected internal static void SaveAndFlush(object instance) + { + InternalSave(instance, true); + } + + /// + /// Saves a copy of the instance to the database. If the primary key is uninitialized + /// it creates the instance in the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The transient instance to be saved + /// The saved ActiveRecord instance + protected internal static object SaveCopy(object instance) + { + return InternalSaveCopy(instance, false); + } + + /// + /// Saves a copy of the instance to the database and flushes the session. If the primary key is uninitialized + /// it creates the instance in the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The transient instance to be saved + /// The saved ActiveRecord instance + protected internal static object SaveCopyAndFlush(object instance) + { + return InternalSaveCopy(instance, true); + } + + /// + /// Saves the instance to the database. If the primary key is unitialized + /// it creates the instance on the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The ActiveRecord instance to be saved + /// if set to true, the operation will be followed by a session flush. + private static void InternalSave(object instance, bool flush) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + session.SaveOrUpdate(instance); + + if (flush) + { + session.Flush(); + } + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + // NHibernate catches our ValidationException on Create so it could be the innerexception here + if (ex.InnerException is ValidationException) + { + throw ex.InnerException; + } + else + { + throw new ActiveRecordException("Could not perform Save for " + instance.GetType().Name, ex); + } + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Saves a copy of the instance to the database. If the primary key is unitialized + /// it creates the instance on the database. Otherwise it updates it. + /// + /// If the primary key is assigned, then you must invoke + /// or instead. + /// + /// + /// The transient instance to be saved + /// if set to true, the operation will be followed by a session flush. + /// The saved ActiveRecord instance. + private static object InternalSaveCopy(object instance, bool flush) + { + if (instance == null) throw new ArgumentNullException("instance"); + + EnsureInitialized(instance.GetType()); + + ISession session = holder.CreateSession(instance.GetType()); + + try + { + object persistent = session.Merge(instance); + + if (flush) + { + session.Flush(); + } + + return persistent; + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + // NHibernate catches our ValidationException on Create so it could be the innerexception here + if (ex.InnerException is ValidationException) + { + throw ex.InnerException; + } + else + { + throw new ActiveRecordException("Could not perform SaveCopy for " + instance.GetType().Name, ex); + } + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #endregion + + #region Execute + + /// + /// Invokes the specified delegate passing a valid + /// NHibernate session. Used for custom NHibernate queries. + /// + /// The target ActiveRecordType + /// The delegate instance + /// The ActiveRecord instance + /// Whatever is returned by the delegate invocation + protected internal static object Execute(Type targetType, NHibernateDelegate call, object instance) + { + if (targetType == null) throw new ArgumentNullException("targetType", "Target type must be informed"); + if (call == null) throw new ArgumentNullException("call", "Delegate must be passed"); + + EnsureInitialized(targetType); + + ISession session = holder.CreateSession(targetType); + + try + { + return call(session, instance); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Error performing Execute for " + targetType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region ExecuteQuery + + /// + /// Enumerates the query + /// Note: only use if you expect most of the values to exist on the second level cache. + /// + /// The query. + /// An + protected internal static IEnumerable EnumerateQuery(IActiveRecordQuery query) + { + Type rootType = query.RootType; + + EnsureInitialized(rootType); + + ISession session = holder.CreateSession(rootType); + + try + { + return query.Enumerate(session); + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform EnumerateQuery for " + rootType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region ExecuteQuery + + /// + /// Executes the query. + /// + /// The query. + /// The query result. + public static object ExecuteQuery(IActiveRecordQuery query) + { + Type rootType = query.RootType; + + EnsureInitialized(rootType); + + ISession session = holder.CreateSession(rootType); + + try + { + return query.Execute(session); + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform ExecuteQuery for " + rootType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region Count + + /// + /// Returns the number of records of the specified + /// type in the database + /// + /// + /// + /// [ActiveRecord] + /// public class User : ActiveRecordBase + /// { + /// ... + /// + /// public static int CountAllUsers() + /// { + /// return Count(typeof(User)); + /// } + /// } + /// + /// + /// The target type. + /// The count result + protected internal static int Count(Type targetType) + { + CountQuery query = new CountQuery(targetType); + + return (int)ExecuteQuery(query); + } + + /// + /// Returns the number of records of the specified + /// type in the database + /// + /// + /// + /// [ActiveRecord] + /// public class User : ActiveRecordBase + /// { + /// ... + /// + /// public static int CountAllUsersLocked() + /// { + /// return Count(typeof(User), "IsLocked = ?", true); + /// } + /// } + /// + /// + /// The target type. + /// A sql where string i.e. Person=? and DOB > ? + /// Positional parameters for the filter string + /// The count result + protected internal static int Count(Type targetType, string filter, params object[] args) + { + CountQuery query = new CountQuery(targetType, filter, args); + + return (int)ExecuteQuery(query); + } + + /// + /// Returns the number of records of the specified + /// type in the database + /// + /// The target type. + /// The criteria expression + /// The count result + protected internal static int Count(Type targetType, ICriterion[] criteria) + { + CountQuery query = new CountQuery(targetType, criteria); + + return (int)ExecuteQuery(query); + } + + /// + /// Returns the number of records of the specified + /// type in the database + /// + /// The target type. + /// The criteria expression + /// The count result + protected internal static int Count(Type targetType, DetachedCriteria detachedCriteria) + { + CountQuery query = new CountQuery(targetType, detachedCriteria); + + return (int)ExecuteQuery(query); + } + + #endregion + + #region Exists + + /// + /// Check if there is any records in the db for the target type + /// + /// The target type. + /// true if there's at least one row + protected internal static bool Exists(Type targetType) + { + return Count(targetType) > 0; + } + + /// + /// Check if there is any records in the db for the target type + /// + /// The target type. + /// A sql where string i.e. Person=? and DOB > ? + /// Positional parameters for the filter string + /// true if there's at least one row + protected internal static bool Exists(Type targetType, string filter, params object[] args) + { + return Count(targetType, filter, args) > 0; + } + + /// + /// Check if the exists in the database. + /// + /// The target type. + /// The id to check on + /// true if the ID exists; otherwise false. + protected internal static bool Exists(Type targetType, object id) + { + EnsureInitialized(targetType); + ISession session = holder.CreateSession(targetType); + + try + { + return session.Get(targetType, id) != null; + } + catch (Exception ex) + { + throw new ActiveRecordException("Could not perform Exists for " + targetType.Name + ". Id: " + id, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Check if any instance matching the criteria exists in the database. + /// + /// The target type. + /// The criteria expression + /// true if an instance is found; otherwise false. + protected internal static bool Exists(Type targetType, params ICriterion[] criteria) + { + return Count(targetType, criteria) > 0; + } + + /// + /// Check if any instance matching the criteria exists in the database. + /// + /// The target type. + /// The criteria expression + /// true if an instance is found; otherwise false. + protected internal static bool Exists(Type targetType, DetachedCriteria detachedCriteria) + { + return Count(targetType, detachedCriteria) > 0; + } + + /// + /// Check if there is any records in the db for the target type + /// + /// The target type. + /// + /// true if there's at least one row + protected internal static bool Exists(Type targetType, IDetachedQuery detachedQuery) + { + Array array = SlicedFindAll(targetType, 0, 1, detachedQuery); + + return array.Length > 0; + } + + #endregion + + #region FindAll + + /// + /// Returns all instances found for the specified type according to the criteria + /// + /// The target type. + /// The criteria. + /// An of objects. + /// The of results. + protected internal static Array FindAll(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders) + { + EnsureInitialized(targetType); + + ISession session = holder.CreateSession(targetType); + + try + { + ICriteria criteria = detachedCriteria.GetExecutableCriteria(session); + + AddOrdersToCriteria(criteria, orders); + + return SupportingUtils.BuildArray(targetType, criteria.List()); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Returns all instances found for the specified type. + /// + /// The target type. + /// The of results + protected internal static Array FindAll(Type targetType) + { + // to ensure we have no duplicates when an outer join is being used. + // NOTE: perhaps we could detect such scenario and do it only then? + var criteria = DetachedCriteria.For(targetType) + .SetResultTransformer(CriteriaSpecification.DistinctRootEntity); + return FindAll(targetType, criteria, null); + } + + /// + /// Returns all instances found for the specified type + /// using sort orders and criteria. + /// + /// The The target type. + /// An of objects. + /// The criteria expression + /// The of results. + protected internal static Array FindAll(Type targetType, Order[] orders, params ICriterion[] criteria) + { + EnsureInitialized(targetType); + + ISession session = holder.CreateSession(targetType); + + try + { + ICriteria sessionCriteria = session.CreateCriteria(targetType); + + foreach (ICriterion cond in criteria) + { + sessionCriteria.Add(cond); + } + + AddOrdersToCriteria(sessionCriteria, orders); + + return SupportingUtils.BuildArray(targetType, sessionCriteria.List()); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + private static void AddOrdersToCriteria(ICriteria criteria, IEnumerable orders) + { + if (orders != null) + { + foreach (Order order in orders) + { + criteria.AddOrder(order); + } + } + } + + /// + /// Returns all instances found for the specified type + /// using criteria. + /// + /// The target type. + /// The criteria expression + /// The of results. + protected internal static Array FindAll(Type targetType, params ICriterion[] criteria) + { + return FindAll(targetType, null, criteria); + } + + /// + /// Returns all instances found for the specified type according to the criteria + /// + /// The target type. + /// The query expression + /// The of results. + protected internal static Array FindAll(Type targetType, IDetachedQuery detachedQuery) + { + EnsureInitialized(targetType); + + ISession session = holder.CreateSession(targetType); + try + { + IQuery executableQuery = detachedQuery.GetExecutableQuery(session); + return SupportingUtils.BuildArray(targetType, executableQuery.List()); + } + catch (ValidationException) + { + holder.FailSession(session); + throw; + } + catch (Exception exception) + { + holder.FailSession(session); + throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, exception); + } + finally + { + holder.ReleaseSession(session); + } + } + + + #endregion + + #region FindAllByProperty + + /// + /// Finds records based on a property value - automatically converts null values to IS NULL style queries. + /// + /// The target type + /// A property name (not a column name) + /// The value to be equals to + /// The of results. + protected internal static Array FindAllByProperty(Type targetType, String property, object value) + { + ICriterion criteria = (value == null) ? Expression.IsNull(property) : Expression.Eq(property, value); + return FindAll(targetType, criteria); + } + + /// + /// Finds records based on a property value - automatically converts null values to IS NULL style queries. + /// + /// The target type + /// The column name to be ordered ASC + /// A property name (not a column name) + /// The value to be equals to + /// The of results. + protected internal static Array FindAllByProperty(Type targetType, String orderByColumn, String property, object value) + { + ICriterion criteria = (value == null) ? Expression.IsNull(property) : Expression.Eq(property, value); + return FindAll(targetType, new Order[] { Order.Asc(orderByColumn) }, criteria); + } + + #endregion + + #region FindByPrimaryKey + + /// + /// Finds an object instance by an unique ID + /// + /// The AR subclass type + /// ID value + /// The object instance. + protected internal static object FindByPrimaryKey(Type targetType, object id) + { + return FindByPrimaryKey(targetType, id, true); + } + + /// + /// Finds an object instance by an unique ID + /// + /// The AR subclass type + /// ID value + /// true if you want to catch an exception + /// if the object is not found + /// The object instance. + /// if throwOnNotFound is set to + /// true and the row is not found + protected internal static object FindByPrimaryKey(Type targetType, object id, bool throwOnNotFound) + { + EnsureInitialized(targetType); + bool hasScope = holder.ThreadScopeInfo.HasInitializedScope; + ISession session = holder.CreateSession(targetType); + + try + { + object loaded; + // Load() and Get() has different semantics with regard to the way they + // handle null values, Get() _must_ check that the value exists, Load() is allowed + // to return an uninitialized proxy that will throw when you access it later. + // in order to play well with proxies, we need to use this approach. + if (throwOnNotFound) + { + loaded = session.Load(targetType, id); + } + else + { + loaded = session.Get(targetType, id); + } + //If we are not in a scope, we want to initialize the entity eagerly, since other wise the + //user will get an exception when it access the entity's property, and it will try to lazy load itself and find that + //it has no session. + //If we are in a scope, it is the user responsability to keep the scope alive if he wants to use + if (!hasScope) + { + NHibernateUtil.Initialize(loaded); + } + return loaded; + } + catch (ObjectNotFoundException ex) + { + holder.FailSession(session); + + String message = String.Format("Could not find {0} with id {1}", targetType.Name, id); + throw new NotFoundException(message, ex); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform FindByPrimaryKey for " + targetType.Name + ". Id: " + id, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + #endregion + + #region FindFirst + + /// + /// Searches and returns the first row. + /// + /// The target type. + /// The criteria. + /// The sort order - used to determine which record is the first one. + /// A targetType instance or null. + protected internal static object FindFirst(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders) + { + Array result = SlicedFindAll(targetType, 0, 1, orders, detachedCriteria); + return (result != null && result.Length > 0 ? result.GetValue(0) : null); + } + + /// + /// Searches and returns the first row. + /// + /// The target type + /// The sort order - used to determine which record is the first one + /// The criteria expression + /// A targetType instance or null + protected internal static object FindFirst(Type targetType, Order[] orders, params ICriterion[] criteria) + { + Array result = SlicedFindAll(targetType, 0, 1, orders, criteria); + return (result != null && result.Length > 0 ? result.GetValue(0) : null); + } + + /// + /// Searches and returns the first row. + /// + /// The target type + /// The criteria expression + /// A targetType instance or null + protected internal static object FindFirst(Type targetType, params ICriterion[] criteria) + { + return FindFirst(targetType, null, criteria); + } + + /// + /// Searches and returns the first row. + /// + /// The target type. + /// The expression query. + /// A targetType instance or null. + protected internal static object FindFirst(Type targetType, IDetachedQuery detachedQuery) + { + Array array = SlicedFindAll(targetType, 0, 1, detachedQuery); + if ((array != null) && (array.Length > 0)) + { + return array.GetValue(0); + } + return null; + } + + #endregion + + #region FindOne + + /// + /// Searches and returns a row. If more than one is found, + /// throws + /// + /// The target type + /// The criteria expression + /// A targetType instance or null + protected internal static object FindOne(Type targetType, params ICriterion[] criteria) + { + Array result = SlicedFindAll(targetType, 0, 2, criteria); + + if (result.Length > 1) + { + throw new ActiveRecordException(targetType.Name + ".FindOne returned " + result.Length + + " rows. Expecting one or none"); + } + + return (result.Length == 0) ? null : result.GetValue(0); + } /// - /// Saves a copy of the instance to the database. If the primary key is uninitialized - /// it creates the instance in the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// + /// Searches and returns a row. If more than one is found, + /// throws /// - /// The transient instance to be saved - /// The saved ActiveRecord instance - protected internal static object SaveCopy(object instance) + /// The target type + /// The criteria + /// A targetType instance or null + protected internal static object FindOne(Type targetType, DetachedCriteria criteria) { - return InternalSaveCopy(instance, false); + Array result = SlicedFindAll(targetType, 0, 2, criteria); + + if (result.Length > 1) + { + throw new ActiveRecordException(targetType.Name + ".FindOne returned " + result.Length + + " rows. Expecting one or none"); + } + + return (result.Length == 0) ? null : result.GetValue(0); } /// - /// Saves a copy of the instance to the database and flushes the session. If the primary key is uninitialized - /// it creates the instance in the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// + /// Searches and returns a row. If more than one is found, + /// throws /// - /// The transient instance to be saved - /// The saved ActiveRecord instance - protected internal static object SaveCopyAndFlush(object instance) + /// The target type + /// The query expression + /// A targetType instance or null + protected internal static object FindOne(Type targetType, IDetachedQuery detachedQuery) { - return InternalSaveCopy(instance, true); + Array array = SlicedFindAll(targetType, 0, 2, detachedQuery); + if (array.Length > 1) + { + throw new ActiveRecordException( + string.Concat( + new object[] { targetType.Name, ".FindOne returned ", array.Length, " rows. Expecting one or none" })); + } + if (array.Length != 0) + { + return array.GetValue(0); + } + return null; } - /// - /// Saves the instance to the database. If the primary key is unitialized - /// it creates the instance on the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// - /// - /// The ActiveRecord instance to be saved - /// if set to true, the operation will be followed by a session flush. - private static void InternalSave(object instance, bool flush) - { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); - - ISession session = holder.CreateSession(instance.GetType()); - - try - { - session.SaveOrUpdate(instance); - - if (flush) - { - session.Flush(); - } - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch(Exception ex) - { - holder.FailSession(session); - - // NHibernate catches our ValidationException on Create so it could be the innerexception here - if (ex.InnerException is ValidationException) - { - throw ex.InnerException; - } - else - { - throw new ActiveRecordException("Could not perform Save for " + instance.GetType().Name, ex); - } - } - finally - { - holder.ReleaseSession(session); - } - } + #endregion + + #region SlicedFindAll /// - /// Saves a copy of the instance to the database. If the primary key is unitialized - /// it creates the instance on the database. Otherwise it updates it. - /// - /// If the primary key is assigned, then you must invoke - /// or instead. - /// + /// Returns a portion of the query results (sliced) /// - /// The transient instance to be saved - /// if set to true, the operation will be followed by a session flush. - /// The saved ActiveRecord instance. - private static object InternalSaveCopy(object instance, bool flush) + /// The target type. + /// The number of the first row to retrieve. + /// The maximum number of results retrieved. + /// An of objects. + /// The criteria expression + /// The sliced query results. + protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, + Order[] orders, params ICriterion[] criteria) { - if (instance == null) throw new ArgumentNullException("instance"); - - EnsureInitialized(instance.GetType()); + EnsureInitialized(targetType); - ISession session = holder.CreateSession(instance.GetType()); + ISession session = holder.CreateSession(targetType); try { - object persistent = session.Merge(instance); + ICriteria sessionCriteria = session.CreateCriteria(targetType); - if (flush) + foreach (ICriterion cond in criteria) { - session.Flush(); + sessionCriteria.Add(cond); } - return persistent; + if (orders != null) + { + foreach (Order order in orders) + { + sessionCriteria.AddOrder(order); + } + } + + sessionCriteria.SetFirstResult(firstResult); + sessionCriteria.SetMaxResults(maxResults); + + return SupportingUtils.BuildArray(targetType, sessionCriteria.List()); } catch (ValidationException) { @@ -647,15 +1395,114 @@ private static object InternalSaveCopy(object instance, bool flush) { holder.FailSession(session); - // NHibernate catches our ValidationException on Create so it could be the innerexception here - if (ex.InnerException is ValidationException) - { - throw ex.InnerException; - } - else - { - throw new ActiveRecordException("Could not perform SaveCopy for " + instance.GetType().Name, ex); - } + throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Returns a portion of the query results (sliced) + /// + /// The target type. + /// The number of the first row to retrieve. + /// The maximum number of results retrieved. + /// An of objects. + /// The criteria expression + /// The sliced query results. + protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, + Order[] orders, DetachedCriteria criteria) + { + EnsureInitialized(targetType); + + ISession session = holder.CreateSession(targetType); + + try + { + ICriteria executableCriteria = criteria.GetExecutableCriteria(session); + AddOrdersToCriteria(executableCriteria, orders); + executableCriteria.SetFirstResult(firstResult); + executableCriteria.SetMaxResults(maxResults); + + return SupportingUtils.BuildArray(targetType, executableCriteria.List()); + } + catch (ValidationException) + { + holder.FailSession(session); + + throw; + } + catch (Exception ex) + { + holder.FailSession(session); + + throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex); + } + finally + { + holder.ReleaseSession(session); + } + } + + /// + /// Returns a portion of the query results (sliced) + /// + /// The target type. + /// The number of the first row to retrieve. + /// The maximum number of results retrieved. + /// The criteria expression + /// The sliced query results. + protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, + params ICriterion[] criteria) + { + return SlicedFindAll(targetType, firstResult, maxResults, null, criteria); + } + + /// + /// Returns a portion of the query results (sliced) + /// + /// The target type. + /// The number of the first row to retrieve. + /// The maximum number of results retrieved. + /// The criteria expression + /// The sliced query results. + protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, + DetachedCriteria criteria) + { + return SlicedFindAll(targetType, firstResult, maxResults, null, criteria); + } + + /// + /// Returns a portion of the query results (sliced) + /// + /// The target type. + /// The number of the first row to retrieve. + /// The maximum number of results retrieved. + /// The query expression + /// The sliced query results. + public static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, IDetachedQuery detachedQuery) + { + + EnsureInitialized(targetType); + ISession session = holder.CreateSession(targetType); + try + { + IQuery executableQuery = detachedQuery.GetExecutableQuery(session); + executableQuery.SetFirstResult(firstResult); + executableQuery.SetMaxResults(maxResults); + return SupportingUtils.BuildArray(targetType, executableQuery.List()); + } + catch (ValidationException) + { + holder.FailSession(session); + throw; + } + catch (Exception exception) + { + holder.FailSession(session); + throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, exception); } finally { @@ -663,904 +1510,57 @@ private static object InternalSaveCopy(object instance, bool flush) } } - #endregion - - #endregion - - #region Execute - - /// - /// Invokes the specified delegate passing a valid - /// NHibernate session. Used for custom NHibernate queries. - /// - /// The target ActiveRecordType - /// The delegate instance - /// The ActiveRecord instance - /// Whatever is returned by the delegate invocation - protected internal static object Execute(Type targetType, NHibernateDelegate call, object instance) - { - if (targetType == null) throw new ArgumentNullException("targetType", "Target type must be informed"); - if (call == null) throw new ArgumentNullException("call", "Delegate must be passed"); - - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - - try - { - return call(session, instance); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Error performing Execute for " + targetType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region ExecuteQuery - - /// - /// Enumerates the query - /// Note: only use if you expect most of the values to exist on the second level cache. - /// - /// The query. - /// An - protected internal static IEnumerable EnumerateQuery(IActiveRecordQuery query) - { - Type rootType = query.RootType; - - EnsureInitialized(rootType); - - ISession session = holder.CreateSession(rootType); - - try - { - return query.Enumerate(session); - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform EnumerateQuery for " + rootType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region ExecuteQuery - - /// - /// Executes the query. - /// - /// The query. - /// The query result. - public static object ExecuteQuery(IActiveRecordQuery query) - { - Type rootType = query.RootType; - - EnsureInitialized(rootType); - - ISession session = holder.CreateSession(rootType); - - try - { - return query.Execute(session); - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform ExecuteQuery for " + rootType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region Count - - /// - /// Returns the number of records of the specified - /// type in the database - /// - /// - /// - /// [ActiveRecord] - /// public class User : ActiveRecordBase - /// { - /// ... - /// - /// public static int CountAllUsers() - /// { - /// return Count(typeof(User)); - /// } - /// } - /// - /// - /// The target type. - /// The count result - protected internal static int Count(Type targetType) - { - CountQuery query = new CountQuery(targetType); - - return (int)ExecuteQuery(query); - } - - /// - /// Returns the number of records of the specified - /// type in the database - /// - /// - /// - /// [ActiveRecord] - /// public class User : ActiveRecordBase - /// { - /// ... - /// - /// public static int CountAllUsersLocked() - /// { - /// return Count(typeof(User), "IsLocked = ?", true); - /// } - /// } - /// - /// - /// The target type. - /// A sql where string i.e. Person=? and DOB > ? - /// Positional parameters for the filter string - /// The count result - protected internal static int Count(Type targetType, string filter, params object[] args) - { - CountQuery query = new CountQuery(targetType, filter, args); - - return (int)ExecuteQuery(query); - } - - /// - /// Returns the number of records of the specified - /// type in the database - /// - /// The target type. - /// The criteria expression - /// The count result - protected internal static int Count(Type targetType, ICriterion[] criteria) - { - CountQuery query = new CountQuery(targetType, criteria); - - return (int) ExecuteQuery(query); - } - - /// - /// Returns the number of records of the specified - /// type in the database - /// - /// The target type. - /// The criteria expression - /// The count result - protected internal static int Count(Type targetType, DetachedCriteria detachedCriteria) - { - CountQuery query = new CountQuery(targetType, detachedCriteria); - - return (int)ExecuteQuery(query); - } - - #endregion - - #region Exists - - /// - /// Check if there is any records in the db for the target type - /// - /// The target type. - /// true if there's at least one row - protected internal static bool Exists(Type targetType) - { - return Count(targetType) > 0; - } - - /// - /// Check if there is any records in the db for the target type - /// - /// The target type. - /// A sql where string i.e. Person=? and DOB > ? - /// Positional parameters for the filter string - /// true if there's at least one row - protected internal static bool Exists(Type targetType, string filter, params object[] args) - { - return Count(targetType, filter, args) > 0; - } - - /// - /// Check if the exists in the database. - /// - /// The target type. - /// The id to check on - /// true if the ID exists; otherwise false. - protected internal static bool Exists(Type targetType, object id) - { - EnsureInitialized(targetType); - ISession session = holder.CreateSession(targetType); - - try - { - return session.Get(targetType, id) != null; - } - catch(Exception ex) - { - throw new ActiveRecordException("Could not perform Exists for " + targetType.Name + ". Id: " + id, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Check if any instance matching the criteria exists in the database. - /// - /// The target type. - /// The criteria expression - /// true if an instance is found; otherwise false. - protected internal static bool Exists(Type targetType, params ICriterion[] criteria) - { - return Count(targetType, criteria) > 0; - } - - /// - /// Check if any instance matching the criteria exists in the database. - /// - /// The target type. - /// The criteria expression - /// true if an instance is found; otherwise false. - protected internal static bool Exists(Type targetType, DetachedCriteria detachedCriteria) - { - return Count(targetType, detachedCriteria) > 0; - } - - /// - /// Check if there is any records in the db for the target type - /// - /// The target type. - /// - /// true if there's at least one row - protected internal static bool Exists(Type targetType, IDetachedQuery detachedQuery) - { - Array array = SlicedFindAll(targetType, 0, 1, detachedQuery); - - return array.Length > 0; - } - - #endregion - - #region FindAll - - /// - /// Returns all instances found for the specified type according to the criteria - /// - /// The target type. - /// The criteria. - /// An of objects. - /// The of results. - protected internal static Array FindAll(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders) - { - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - - try - { - ICriteria criteria = detachedCriteria.GetExecutableCriteria(session); - - AddOrdersToCriteria(criteria, orders); - - return SupportingUtils.BuildArray(targetType, criteria.List()); - } - catch(ValidationException) - { - holder.FailSession(session); - - throw; - } - catch(Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Returns all instances found for the specified type. - /// - /// The target type. - /// The of results - protected internal static Array FindAll(Type targetType) - { - // to ensure we have no duplicates when an outer join is being used. - // NOTE: perhaps we could detect such scenario and do it only then? - var criteria = DetachedCriteria.For(targetType) - .SetResultTransformer(CriteriaSpecification.DistinctRootEntity); - return FindAll(targetType, criteria, null); - } - - /// - /// Returns all instances found for the specified type - /// using sort orders and criteria. - /// - /// The The target type. - /// An of objects. - /// The criteria expression - /// The of results. - protected internal static Array FindAll(Type targetType, Order[] orders, params ICriterion[] criteria) - { - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - - try - { - ICriteria sessionCriteria = session.CreateCriteria(targetType); - - foreach(ICriterion cond in criteria) - { - sessionCriteria.Add(cond); - } - - AddOrdersToCriteria(sessionCriteria, orders); - - return SupportingUtils.BuildArray(targetType, sessionCriteria.List()); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - private static void AddOrdersToCriteria(ICriteria criteria, IEnumerable orders) - { - if (orders != null) - { - foreach (Order order in orders) - { - criteria.AddOrder(order); - } - } - } - - /// - /// Returns all instances found for the specified type - /// using criteria. - /// - /// The target type. - /// The criteria expression - /// The of results. - protected internal static Array FindAll(Type targetType, params ICriterion[] criteria) - { - return FindAll(targetType, null, criteria); - } - - /// - /// Returns all instances found for the specified type according to the criteria - /// - /// The target type. - /// The query expression - /// The of results. - protected internal static Array FindAll(Type targetType, IDetachedQuery detachedQuery) - { - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - try - { - IQuery executableQuery = detachedQuery.GetExecutableQuery(session); - return SupportingUtils.BuildArray(targetType, executableQuery.List()); - } - catch (ValidationException) - { - holder.FailSession(session); - throw; - } - catch (Exception exception) - { - holder.FailSession(session); - throw new ActiveRecordException("Could not perform FindAll for " + targetType.Name, exception); - } - finally - { - holder.ReleaseSession(session); - } - } - - - #endregion - - #region FindAllByProperty - - /// - /// Finds records based on a property value - automatically converts null values to IS NULL style queries. - /// - /// The target type - /// A property name (not a column name) - /// The value to be equals to - /// The of results. - protected internal static Array FindAllByProperty(Type targetType, String property, object value) - { - ICriterion criteria = (value == null) ? Expression.IsNull(property) : Expression.Eq(property, value); - return FindAll(targetType, criteria); - } - - /// - /// Finds records based on a property value - automatically converts null values to IS NULL style queries. - /// - /// The target type - /// The column name to be ordered ASC - /// A property name (not a column name) - /// The value to be equals to - /// The of results. - protected internal static Array FindAllByProperty(Type targetType, String orderByColumn, String property, object value) - { - ICriterion criteria = (value == null) ? Expression.IsNull(property) : Expression.Eq(property, value); - return FindAll(targetType, new Order[] {Order.Asc(orderByColumn)}, criteria); - } - - #endregion - - #region FindByPrimaryKey - - /// - /// Finds an object instance by an unique ID - /// - /// The AR subclass type - /// ID value - /// The object instance. - protected internal static object FindByPrimaryKey(Type targetType, object id) - { - return FindByPrimaryKey(targetType, id, true); - } - - /// - /// Finds an object instance by an unique ID - /// - /// The AR subclass type - /// ID value - /// true if you want to catch an exception - /// if the object is not found - /// The object instance. - /// if throwOnNotFound is set to - /// true and the row is not found - protected internal static object FindByPrimaryKey(Type targetType, object id, bool throwOnNotFound) - { - EnsureInitialized(targetType); - bool hasScope = holder.ThreadScopeInfo.HasInitializedScope; - ISession session = holder.CreateSession(targetType); - - try - { - object loaded; - // Load() and Get() has different semantics with regard to the way they - // handle null values, Get() _must_ check that the value exists, Load() is allowed - // to return an uninitialized proxy that will throw when you access it later. - // in order to play well with proxies, we need to use this approach. - if (throwOnNotFound) - { - loaded = session.Load(targetType, id); - } - else - { - loaded = session.Get(targetType, id); - } - //If we are not in a scope, we want to initialize the entity eagerly, since other wise the - //user will get an exception when it access the entity's property, and it will try to lazy load itself and find that - //it has no session. - //If we are in a scope, it is the user responsability to keep the scope alive if he wants to use - if (!hasScope) - { - NHibernateUtil.Initialize(loaded); - } - return loaded; - } - catch (ObjectNotFoundException ex) - { - holder.FailSession(session); - - String message = String.Format("Could not find {0} with id {1}", targetType.Name, id); - throw new NotFoundException(message, ex); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform FindByPrimaryKey for " + targetType.Name + ". Id: " + id, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - #endregion - - #region FindFirst - - /// - /// Searches and returns the first row. - /// - /// The target type. - /// The criteria. - /// The sort order - used to determine which record is the first one. - /// A targetType instance or null. - protected internal static object FindFirst(Type targetType, DetachedCriteria detachedCriteria, params Order[] orders) - { - Array result = SlicedFindAll(targetType, 0, 1, orders, detachedCriteria); - return (result != null && result.Length > 0 ? result.GetValue(0) : null); - } - - /// - /// Searches and returns the first row. - /// - /// The target type - /// The sort order - used to determine which record is the first one - /// The criteria expression - /// A targetType instance or null - protected internal static object FindFirst(Type targetType, Order[] orders, params ICriterion[] criteria) - { - Array result = SlicedFindAll(targetType, 0, 1, orders, criteria); - return (result != null && result.Length > 0 ? result.GetValue(0) : null); - } - - /// - /// Searches and returns the first row. - /// - /// The target type - /// The criteria expression - /// A targetType instance or null - protected internal static object FindFirst(Type targetType, params ICriterion[] criteria) - { - return FindFirst(targetType, null, criteria); - } - - /// - /// Searches and returns the first row. - /// - /// The target type. - /// The expression query. - /// A targetType instance or null. - protected internal static object FindFirst(Type targetType, IDetachedQuery detachedQuery) - { - Array array = SlicedFindAll(targetType, 0, 1, detachedQuery); - if ((array != null) && (array.Length > 0)) - { - return array.GetValue(0); - } - return null; - } - - #endregion - - #region FindOne - - /// - /// Searches and returns a row. If more than one is found, - /// throws - /// - /// The target type - /// The criteria expression - /// A targetType instance or null - protected internal static object FindOne(Type targetType, params ICriterion[] criteria) - { - Array result = SlicedFindAll(targetType, 0, 2, criteria); - - if (result.Length > 1) - { - throw new ActiveRecordException(targetType.Name + ".FindOne returned " + result.Length + - " rows. Expecting one or none"); - } - - return (result.Length == 0) ? null : result.GetValue(0); - } - - /// - /// Searches and returns a row. If more than one is found, - /// throws - /// - /// The target type - /// The criteria - /// A targetType instance or null - protected internal static object FindOne(Type targetType, DetachedCriteria criteria) - { - Array result = SlicedFindAll(targetType, 0, 2, criteria); - - if (result.Length > 1) - { - throw new ActiveRecordException(targetType.Name + ".FindOne returned " + result.Length + - " rows. Expecting one or none"); - } - - return (result.Length == 0) ? null : result.GetValue(0); - } - - /// - /// Searches and returns a row. If more than one is found, - /// throws - /// - /// The target type - /// The query expression - /// A targetType instance or null - protected internal static object FindOne(Type targetType, IDetachedQuery detachedQuery) - { - Array array = SlicedFindAll(targetType, 0, 2, detachedQuery); - if (array.Length > 1) - { - throw new ActiveRecordException( - string.Concat( - new object[] { targetType.Name, ".FindOne returned ", array.Length, " rows. Expecting one or none" })); - } - if (array.Length != 0) - { - return array.GetValue(0); - } - return null; - } - - #endregion - - #region SlicedFindAll - - /// - /// Returns a portion of the query results (sliced) - /// - /// The target type. - /// The number of the first row to retrieve. - /// The maximum number of results retrieved. - /// An of objects. - /// The criteria expression - /// The sliced query results. - protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, - Order[] orders, params ICriterion[] criteria) - { - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - - try - { - ICriteria sessionCriteria = session.CreateCriteria(targetType); - - foreach(ICriterion cond in criteria) - { - sessionCriteria.Add(cond); - } - - if (orders != null) - { - foreach (Order order in orders) - { - sessionCriteria.AddOrder(order); - } - } - - sessionCriteria.SetFirstResult(firstResult); - sessionCriteria.SetMaxResults(maxResults); - - return SupportingUtils.BuildArray(targetType, sessionCriteria.List()); - } - catch (ValidationException) - { - holder.FailSession(session); - - throw; - } - catch (Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Returns a portion of the query results (sliced) - /// - /// The target type. - /// The number of the first row to retrieve. - /// The maximum number of results retrieved. - /// An of objects. - /// The criteria expression - /// The sliced query results. - protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, - Order[] orders, DetachedCriteria criteria) - { - EnsureInitialized(targetType); - - ISession session = holder.CreateSession(targetType); - - try - { - ICriteria executableCriteria = criteria.GetExecutableCriteria(session); - AddOrdersToCriteria(executableCriteria, orders); - executableCriteria.SetFirstResult(firstResult); - executableCriteria.SetMaxResults(maxResults); - - return SupportingUtils.BuildArray(targetType, executableCriteria.List()); - } - catch(ValidationException) - { - holder.FailSession(session); - - throw; - } - catch(Exception ex) - { - holder.FailSession(session); - - throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, ex); - } - finally - { - holder.ReleaseSession(session); - } - } - - /// - /// Returns a portion of the query results (sliced) - /// - /// The target type. - /// The number of the first row to retrieve. - /// The maximum number of results retrieved. - /// The criteria expression - /// The sliced query results. - protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, - params ICriterion[] criteria) - { - return SlicedFindAll(targetType, firstResult, maxResults, null, criteria); - } - - /// - /// Returns a portion of the query results (sliced) - /// - /// The target type. - /// The number of the first row to retrieve. - /// The maximum number of results retrieved. - /// The criteria expression - /// The sliced query results. - protected internal static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, - DetachedCriteria criteria) - { - return SlicedFindAll(targetType, firstResult, maxResults, null, criteria); - } - - /// - /// Returns a portion of the query results (sliced) - /// - /// The target type. - /// The number of the first row to retrieve. - /// The maximum number of results retrieved. - /// The query expression - /// The sliced query results. - public static Array SlicedFindAll(Type targetType, int firstResult, int maxResults, IDetachedQuery detachedQuery) - { - - EnsureInitialized(targetType); - ISession session = holder.CreateSession(targetType); - try - { - IQuery executableQuery = detachedQuery.GetExecutableQuery(session); - executableQuery.SetFirstResult(firstResult); - executableQuery.SetMaxResults(maxResults); - return SupportingUtils.BuildArray(targetType, executableQuery.List()); - } - catch (ValidationException) - { - holder.FailSession(session); - throw; - } - catch (Exception exception) - { - holder.FailSession(session); - throw new ActiveRecordException("Could not perform SlicedFindAll for " + targetType.Name, exception); - } - finally - { - holder.ReleaseSession(session); - } - } - - - #endregion - - #endregion - - #region protected internal - - /// - /// Invokes the specified delegate passing a valid - /// NHibernate session. Used for custom NHibernate queries. - /// - /// The delegate instance - /// Whatever is returned by the delegate invocation - protected virtual internal object Execute(NHibernateDelegate call) - { - return Execute(GetType(), call, this); - } - - #endregion - - #region public virtual - - /// - /// Saves the instance information to the database. - /// May Create or Update the instance depending - /// on whether it has a valid ID. - /// - /// - /// If within a the operation - /// is going to be on hold until NHibernate (or you) decides to flush - /// the session. - /// - public virtual void Save() - { - Save(this); - } - - /// - /// Saves the instance information to the database. - /// May Create or Update the instance depending - /// on whether it has a valid ID. - /// - /// - /// Even within a the operation - /// is going to be flushed immediately. This might have side effects such as - /// flushing (persisting) others operations that were on hold. - /// - public virtual void SaveAndFlush() - { - SaveAndFlush(this); - } + + #endregion + + #endregion + + #region protected internal + + /// + /// Invokes the specified delegate passing a valid + /// NHibernate session. Used for custom NHibernate queries. + /// + /// The delegate instance + /// Whatever is returned by the delegate invocation + protected virtual internal object Execute(NHibernateDelegate call) + { + return Execute(GetType(), call, this); + } + + #endregion + + #region public virtual + + /// + /// Saves the instance information to the database. + /// May Create or Update the instance depending + /// on whether it has a valid ID. + /// + /// + /// If within a the operation + /// is going to be on hold until NHibernate (or you) decides to flush + /// the session. + /// + public virtual void Save() + { + Save(this); + } + + /// + /// Saves the instance information to the database. + /// May Create or Update the instance depending + /// on whether it has a valid ID. + /// + /// + /// Even within a the operation + /// is going to be flushed immediately. This might have side effects such as + /// flushing (persisting) others operations that were on hold. + /// + public virtual void SaveAndFlush() + { + SaveAndFlush(this); + } /// /// Saves a copy of the instance information to the database. @@ -1594,162 +1594,162 @@ public virtual object SaveCopyAndFlush() return SaveCopyAndFlush(this); } - /// - /// Creates (Saves) a new instance to the database. - /// - /// - /// If within a the operation - /// is going to be on hold until NHibernate (or you) decides to flush - /// the session. - /// - public virtual void Create() - { - Create(this); - } - - /// - /// Creates (Saves) a new instance to the database. - /// - /// - /// Even within a the operation - /// is going to be flushed immediately. This might have side effects such as - /// flushing (persisting) others operations that were on hold. - /// - public virtual void CreateAndFlush() - { - CreateAndFlush(this); - } - - /// - /// Persists the modification on the instance - /// state to the database. - /// - /// - /// If within a the operation - /// is going to be on hold until NHibernate (or you) decides to flush - /// the session. - /// - public virtual void Update() - { - Update(this); - } - - /// - /// Persists the modification on the instance - /// state to the database. - /// - /// - /// Even within a the operation - /// is going to be flushed immediately. This might have side effects such as - /// flushing (persisting) others operations that were on hold. - /// - public virtual void UpdateAndFlush() - { - UpdateAndFlush(this); - } - - /// - /// Deletes the instance from the database. - /// - /// - /// If within a the operation - /// is going to be on hold until NHibernate (or you) decides to flush - /// the session. - /// - public virtual void Delete() - { - Delete(this); - } - - /// - /// Deletes the instance from the database. - /// - /// - /// Even within a the operation - /// is going to be flushed immediately. This might have side effects such as - /// flushing (persisting) others operations that were on hold. - /// - public virtual void DeleteAndFlush() - { - DeleteAndFlush(this); - } - - /// - /// Refresh the instance from the database. - /// - public virtual void Refresh() - { - Refresh(this); - } - - #endregion - - #region public override - - /// - /// Return the type of the object with its PK value. - /// Useful for logging/debugging - /// - /// A string representation of this object. - public override String ToString() - { - ActiveRecordModel model = GetModel(GetType()); - - if (model == null || model.PrimaryKey == null) - { - return base.ToString(); - } - - PrimaryKeyModel pkModel = model.PrimaryKey; - - object pkVal = pkModel.Property.GetValue(this, null); - - return base.ToString() + "#" + pkVal; - } - - #endregion - - #region Sort Order - - internal static Order[] PropertyNamesToOrderArray(bool asc, params string[] propertyNames) - { - Order[] orders = new Order[propertyNames.Length]; - - for (int i = 0; i < propertyNames.Length; i++) - { - orders[i] = new Order(propertyNames[i], asc); - } - return orders; - } - - /// - /// Ascending Order - /// - /// - /// Returns an array of Ascending instances specifing which properties to use to - /// order a result. - /// - /// List of property names to order by ascending - /// Array of objects suitable for passing to FindAll and variants - public static Order[] Asc(params string[] propertyNames) - { - return PropertyNamesToOrderArray(true, propertyNames); - } - - /// - /// Descending Order - /// - /// - /// Returns an array of Descending instances specifing which properties to use to - /// order a result. - /// - /// List of property names to order by descending - /// Array of objects suitable for passing to FindAll and variants - public static Order[] Desc(params string[] propertyNames) - { - return PropertyNamesToOrderArray(false, propertyNames); - } - - #endregion - } + /// + /// Creates (Saves) a new instance to the database. + /// + /// + /// If within a the operation + /// is going to be on hold until NHibernate (or you) decides to flush + /// the session. + /// + public virtual void Create() + { + Create(this); + } + + /// + /// Creates (Saves) a new instance to the database. + /// + /// + /// Even within a the operation + /// is going to be flushed immediately. This might have side effects such as + /// flushing (persisting) others operations that were on hold. + /// + public virtual void CreateAndFlush() + { + CreateAndFlush(this); + } + + /// + /// Persists the modification on the instance + /// state to the database. + /// + /// + /// If within a the operation + /// is going to be on hold until NHibernate (or you) decides to flush + /// the session. + /// + public virtual void Update() + { + Update(this); + } + + /// + /// Persists the modification on the instance + /// state to the database. + /// + /// + /// Even within a the operation + /// is going to be flushed immediately. This might have side effects such as + /// flushing (persisting) others operations that were on hold. + /// + public virtual void UpdateAndFlush() + { + UpdateAndFlush(this); + } + + /// + /// Deletes the instance from the database. + /// + /// + /// If within a the operation + /// is going to be on hold until NHibernate (or you) decides to flush + /// the session. + /// + public virtual void Delete() + { + Delete(this); + } + + /// + /// Deletes the instance from the database. + /// + /// + /// Even within a the operation + /// is going to be flushed immediately. This might have side effects such as + /// flushing (persisting) others operations that were on hold. + /// + public virtual void DeleteAndFlush() + { + DeleteAndFlush(this); + } + + /// + /// Refresh the instance from the database. + /// + public virtual void Refresh() + { + Refresh(this); + } + + #endregion + + #region public override + + /// + /// Return the type of the object with its PK value. + /// Useful for logging/debugging + /// + /// A string representation of this object. + public override String ToString() + { + ActiveRecordModel model = GetModel(GetType()); + + if (model == null || model.PrimaryKey == null) + { + return base.ToString(); + } + + PrimaryKeyModel pkModel = model.PrimaryKey; + + object pkVal = pkModel.Property.GetValue(this, null); + + return base.ToString() + "#" + pkVal; + } + + #endregion + + #region Sort Order + + internal static Order[] PropertyNamesToOrderArray(bool asc, params string[] propertyNames) + { + Order[] orders = new Order[propertyNames.Length]; + + for (int i = 0; i < propertyNames.Length; i++) + { + orders[i] = new Order(propertyNames[i], asc); + } + return orders; + } + + /// + /// Ascending Order + /// + /// + /// Returns an array of Ascending instances specifing which properties to use to + /// order a result. + /// + /// List of property names to order by ascending + /// Array of objects suitable for passing to FindAll and variants + public static Order[] Asc(params string[] propertyNames) + { + return PropertyNamesToOrderArray(true, propertyNames); + } + + /// + /// Descending Order + /// + /// + /// Returns an array of Descending instances specifing which properties to use to + /// order a result. + /// + /// List of property names to order by descending + /// Array of objects suitable for passing to FindAll and variants + public static Order[] Desc(params string[] propertyNames) + { + return PropertyNamesToOrderArray(false, propertyNames); + } + + #endregion + } } From 491de66f4d3ed2571007598cfbb3b745728572cd Mon Sep 17 00:00:00 2001 From: Vilen Tambovtsev Date: Thu, 14 May 2015 14:18:01 +0300 Subject: [PATCH 3/6] fix connection strings --- .../App.config | 2 +- .../App-net-2.0.config | 6 +- .../App-net-3.5.config | 10 +- src/Castle.ActiveRecord.Tests/App.config | 8 +- .../Config/ConfigurationSource.cs | 2 +- .../Config/ConfigureTests.cs | 2 +- .../Config/StorageConfigurationTests.cs | 2 +- .../DefaultConfigurationsTestCase.cs | 4 +- .../InvalidRootTypeTestCase.cs | 2 +- .../Framework/Config/DatabaseType.cs | 130 +++++++++--------- .../Config/DefaultDatabaseConfiguration.cs | 6 +- .../Config/InPlaceConfigurationSource.cs | 4 +- 12 files changed, 92 insertions(+), 86 deletions(-) diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config b/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config index c26e95c..deefe26 100644 --- a/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/App.config @@ -11,7 +11,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/App-net-2.0.config b/src/Castle.ActiveRecord.Tests/App-net-2.0.config index f979fd0..2a13766 100644 --- a/src/Castle.ActiveRecord.Tests/App-net-2.0.config +++ b/src/Castle.ActiveRecord.Tests/App-net-2.0.config @@ -25,7 +25,7 @@ - + @@ -34,7 +34,7 @@ - + @@ -43,7 +43,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/App-net-3.5.config b/src/Castle.ActiveRecord.Tests/App-net-3.5.config index e6e189e..0a840ad 100644 --- a/src/Castle.ActiveRecord.Tests/App-net-3.5.config +++ b/src/Castle.ActiveRecord.Tests/App-net-3.5.config @@ -25,25 +25,25 @@ - + - + - + - + - + diff --git a/src/Castle.ActiveRecord.Tests/App.config b/src/Castle.ActiveRecord.Tests/App.config index 29c72bb..939a6b4 100644 --- a/src/Castle.ActiveRecord.Tests/App.config +++ b/src/Castle.ActiveRecord.Tests/App.config @@ -9,7 +9,7 @@ - + @@ -18,7 +18,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -36,7 +36,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs b/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs index f822bd7..aa9fad8 100644 --- a/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs +++ b/src/Castle.ActiveRecord.Tests/Config/ConfigurationSource.cs @@ -232,7 +232,7 @@ private static string GetDefaultHibernateConfigAndCloseActiveRecordSection() { return @" - + diff --git a/src/Castle.ActiveRecord.Tests/Config/ConfigureTests.cs b/src/Castle.ActiveRecord.Tests/Config/ConfigureTests.cs index 8fbdfe9..113850a 100644 --- a/src/Castle.ActiveRecord.Tests/Config/ConfigureTests.cs +++ b/src/Castle.ActiveRecord.Tests/Config/ConfigureTests.cs @@ -58,7 +58,7 @@ public void BasicSyntaxStorageConfiguration() .ConnectionStringName("a_string") .Driver() .ConnectionProvider() - .Dialect() + .Dialect() .ProxiedBy() .ShowSql(); diff --git a/src/Castle.ActiveRecord.Tests/Config/StorageConfigurationTests.cs b/src/Castle.ActiveRecord.Tests/Config/StorageConfigurationTests.cs index cad4525..e12630f 100644 --- a/src/Castle.ActiveRecord.Tests/Config/StorageConfigurationTests.cs +++ b/src/Castle.ActiveRecord.Tests/Config/StorageConfigurationTests.cs @@ -67,7 +67,7 @@ public void ConnectionProviderClassIsAdded() [Test] public void DialectIsAdded() { - AssertConfiguration(_configuration.Dialect(), "dialect", "NHibernate.Dialect.MsSql2005Dialect"); + AssertConfiguration(_configuration.Dialect(), "dialect", "NHibernate.Dialect.MsSql2012Dialect"); } [Test] diff --git a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs index ea3c4c3..871eb48 100644 --- a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs @@ -53,7 +53,7 @@ public void SetUp() public void SqlServer2005Defaults() { var configuration = BuildConfiguration("MsSqlServer2005"); - AssertPropertyEquals(configuration, dialect, typeof(MsSql2005Dialect).AssemblyQualifiedName); + AssertPropertyEquals(configuration, dialect, typeof(MsSql2012Dialect).AssemblyQualifiedName); AssertPropertyEquals(configuration, connection_provider, typeof(DriverConnectionProvider).AssemblyQualifiedName); AssertPropertyEquals(configuration, connection_driver_class, typeof(SqlClientDriver).AssemblyQualifiedName); AssertPropertyEquals(configuration, proxyfactory_factory_class, typeof(ProxyFactoryFactory).AssemblyQualifiedName); @@ -129,7 +129,7 @@ public void Can_use_shorthand_attribute_form() "; var configuration = BuildConfiguration(ReadConfiguration(value)); - AssertPropertyEquals(configuration, dialect, typeof(MsSql2005Dialect).AssemblyQualifiedName); + AssertPropertyEquals(configuration, dialect, typeof(MsSql2012Dialect).AssemblyQualifiedName); AssertPropertyEquals(configuration, connection_connection_string_name, "foobar"); } diff --git a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs index a56f67b..30f7b68 100644 --- a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs @@ -28,7 +28,7 @@ protected IConfigurationSource GetConfigSource() Dictionary properties = new Dictionary(); properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); - properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2008Dialect"); + properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2012Dialect"); properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); properties.Add("hibernate.connection.connection_string", "Data Source=.;Initial Catalog=Test;Integrated Security=true"); diff --git a/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs b/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs index 8c3dcf5..1c0449d 100644 --- a/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs +++ b/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs @@ -14,67 +14,71 @@ namespace Castle.ActiveRecord.Framework.Config { - /// - /// Enum for database types support for configuration construction. - /// Not to be confused by databases supported by ActiveRecord - /// - public enum DatabaseType - { - /// - /// Microsoft SQL Server 2000 - /// - MsSqlServer2000, - /// - /// Microsoft SQL Server 2005 - /// - MsSqlServer2005, - /// - /// Microsoft SQL Server 2008 - /// - MsSqlServer2008, - /// - /// SQLite - /// - SQLite, - /// - /// MySQL 3 or 4 - /// - MySql, - /// - /// MySQL 5 - /// - MySql5, - /// - /// Firebird - /// - Firebird, - /// - /// PostgreSQL - /// - PostgreSQL, - /// - /// PostgreSQL 8.1 - /// - PostgreSQL81, - /// - /// PostgreSQL 8.2 - /// - PostgreSQL82, - /// - /// Microsoft SQL Server 2005 Compact Edition - /// - MsSqlCe, - /// - /// Oracle - /// - Oracle8i, - /// - /// Oracle 9 - /// - Oracle9i, - /// - /// Oracle 10g - /// - Oracle10g - } + /// + /// Enum for database types support for configuration construction. + /// Not to be confused by databases supported by ActiveRecord + /// + public enum DatabaseType + { + /// + /// Microsoft SQL Server 2000 + /// + MsSqlServer2000, + /// + /// Microsoft SQL Server 2005 + /// + MsSqlServer2005, + /// + /// Microsoft SQL Server 2008 + /// + MsSqlServer2008, + /// + /// Microsoft SQL Server 2012 + /// + MsSqlServer2012, + /// + /// SQLite + /// + SQLite, + /// + /// MySQL 3 or 4 + /// + MySql, + /// + /// MySQL 5 + /// + MySql5, + /// + /// Firebird + /// + Firebird, + /// + /// PostgreSQL + /// + PostgreSQL, + /// + /// PostgreSQL 8.1 + /// + PostgreSQL81, + /// + /// PostgreSQL 8.2 + /// + PostgreSQL82, + /// + /// Microsoft SQL Server 2005 Compact Edition + /// + MsSqlCe, + /// + /// Oracle + /// + Oracle8i, + /// + /// Oracle 9 + /// + Oracle9i, + /// + /// Oracle 10g + /// + Oracle10g + } } diff --git a/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs b/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs index 6530aa6..43de4b8 100644 --- a/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs +++ b/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs @@ -57,9 +57,11 @@ public IDictionary For(DatabaseType databaseType) case DatabaseType.MsSqlServer2000: return Configure(); case DatabaseType.MsSqlServer2005: - return Configure(); + return Configure(); case DatabaseType.MsSqlServer2008: - return Configure(); + return Configure(); + case DatabaseType.MsSqlServer2012: + return Configure(); case DatabaseType.SQLite: return Configure(SQLite()); case DatabaseType.MySql: diff --git a/src/Castle.ActiveRecord/Framework/Config/InPlaceConfigurationSource.cs b/src/Castle.ActiveRecord/Framework/Config/InPlaceConfigurationSource.cs index e0d1c02..10aa75c 100644 --- a/src/Castle.ActiveRecord/Framework/Config/InPlaceConfigurationSource.cs +++ b/src/Castle.ActiveRecord/Framework/Config/InPlaceConfigurationSource.cs @@ -162,7 +162,7 @@ public static InPlaceConfigurationSource BuildForMSSqlServer(string server, stri if (string.IsNullOrEmpty(server)) throw new ArgumentNullException("server"); if (string.IsNullOrEmpty(initialCatalog)) throw new ArgumentNullException("initialCatalog"); - return Build(DatabaseType.MsSqlServer2005, "Server=" + server + ";initial catalog=" + initialCatalog + ";Integrated Security=SSPI"); + return Build(DatabaseType.MsSqlServer2008, "Server=" + server + ";initial catalog=" + initialCatalog + ";Integrated Security=SSPI"); } /// @@ -180,7 +180,7 @@ public static InPlaceConfigurationSource BuildForMSSqlServer(string server, stri if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username"); if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); - return Build(DatabaseType.MsSqlServer2005, "Server=" + server + ";initial catalog=" + initialCatalog + ";User id=" + username + ";password=" + password); + return Build(DatabaseType.MsSqlServer2008, "Server=" + server + ";initial catalog=" + initialCatalog + ";User id=" + username + ";password=" + password); } /// From 41184dd8d771f6d8582249e9300ba145573df397 Mon Sep 17 00:00:00 2001 From: Vilen Tambovtsev Date: Thu, 14 May 2015 14:37:41 +0300 Subject: [PATCH 4/6] more test fixes --- .../ActiveRecordLinqTestCase.cs | 4 ++-- .../DefaultConfigurationsTestCase.cs | 2 +- src/Castle.ActiveRecord.Tests/Model/Blog.cs | 18 ++++++++++-------- .../Model/CompositeModel/Agent.cs | 7 ++++--- .../Model/CompositeModel/Group.cs | 14 ++++++++------ .../Model/CompositeModel/Org.cs | 9 +++++---- src/Castle.ActiveRecord.Tests/Model/Order.cs | 4 ++-- .../StatelessSessionScopeTestCase.cs | 4 +++- .../TableHierarchyTestCase.cs | 14 ++++++++------ .../ByteCode/ProxyFactory.cs | 4 ++-- .../ByteCode/ProxyFactoryFactory.cs | 11 ++++++----- 11 files changed, 51 insertions(+), 40 deletions(-) diff --git a/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs b/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs index c2531d0..ed65b1e 100644 --- a/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs @@ -214,7 +214,7 @@ public void UsingLinqFromNonLinqBaseClass() Assert.IsNotNull(widget); Assert.AreEqual("Hello world", widget.Name); - var widget2 = ActiveRecordLinq.AsQueryable().First(w => w.Name == "Hello World"); + var widget2 = ActiveRecordLinq.AsQueryable().First(w => w.Name == "Hello world"); Assert.IsNotNull(widget2); Assert.AreEqual("Hello world", widget2.Name); @@ -240,7 +240,7 @@ public void UsingLinqViaSessionScopeVariable() Widget widget = new Widget { Name = "Hello world" }; widget.Save(); - widgets = from w in scope.AsQueryable() where w.Name == "Hello World" select w; + widgets = from w in scope.AsQueryable() where w.Name == "Hello world" select w; Assert.IsNotNull(widgets); Assert.AreEqual(1, widgets.Count()); } diff --git a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs index 871eb48..c421506 100644 --- a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs @@ -117,7 +117,7 @@ public void Throws_when_invalid_database_specified() var ex = Assert.Throws(action); Assert.AreEqual( - "Specified value (IDontExist!) is not valid for 'database' attribute. Valid values are: 'MsSqlServer2000' 'MsSqlServer2005' 'MsSqlServer2008' " + + "Specified value (IDontExist!) is not valid for 'database' attribute. Valid values are: 'MsSqlServer2000' 'MsSqlServer2005' 'MsSqlServer2008' 'MsSqlServer2012' " + "'SQLite' 'MySql' 'MySql5' 'Firebird' 'PostgreSQL' 'PostgreSQL81' 'PostgreSQL82' 'MsSqlCe' 'Oracle8i' 'Oracle9i' 'Oracle10g'.", ex.Message); } diff --git a/src/Castle.ActiveRecord.Tests/Model/Blog.cs b/src/Castle.ActiveRecord.Tests/Model/Blog.cs index 66976c1..abac130 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Blog.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Blog.cs @@ -16,6 +16,8 @@ namespace Castle.ActiveRecord.Tests.Model { using System; using System.Collections; + using System.Collections.Generic; + using Castle.ActiveRecord.Framework; using NHibernate; using NHibernate.Criterion; @@ -26,10 +28,10 @@ public class Blog : ActiveRecordBase private int _id; private String _name; private String _author; - private IList _posts; - private IList _publishedposts; - private IList _unpublishedposts; - private IList _recentposts; + private IList _posts; + private IList _publishedposts; + private IList _unpublishedposts; + private IList _recentposts; private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; public Blog() @@ -63,28 +65,28 @@ public String Author } [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid")] - public IList Posts + public IList Posts { get { return _posts; } set { _posts = value; } } [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", Where="published = 1")] - public IList PublishedPosts + public IList PublishedPosts { get { return _publishedposts; } set { _publishedposts = value; } } [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", Where="published = 0")] - public IList UnPublishedPosts + public IList UnPublishedPosts { get { return _unpublishedposts; } set { _unpublishedposts = value; } } [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", OrderBy="created desc")] - public IList RecentPosts + public IList RecentPosts { get { return _recentposts; } set { _recentposts = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs index 5c1ee69..dc417e3 100644 --- a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs +++ b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs @@ -16,6 +16,7 @@ namespace Castle.ActiveRecord.Tests.Model.CompositeModel { using System; using System.Collections; + using System.Collections.Generic; using NHibernate; @@ -27,12 +28,12 @@ public class Agent : ActiveRecordBase { private AgentKey _userKey; private Org _org; - private IList _groups; + private IList _groups; private int _version; public Agent() { - _groups = new ArrayList(); + _groups = new List(); _version = -1; } @@ -78,7 +79,7 @@ public Org Org CompositeKeyColumnKeys = new String[]{"OrgId","Name"}, Lazy = true, Cascade = ManyRelationCascadeEnum.SaveUpdate)] - public IList Groups + public IList Groups { get { return _groups; } set { _groups = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Group.cs b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Group.cs index 9010110..6ff9972 100644 --- a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Group.cs +++ b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Group.cs @@ -16,6 +16,8 @@ namespace Castle.ActiveRecord.Tests.Model.CompositeModel { using System; using System.Collections; + using System.Collections.Generic; + using Castle.ActiveRecord.Framework; using NHibernate; @@ -24,14 +26,14 @@ public class Group : ActiveRecordBase { private int _id; private String _name; - private IList _agents; - private IList _groups; + private IList _agents; + private IList _groups; private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; public Group() { - _agents = new ArrayList(); - _groups = new ArrayList(); + _agents = new List(); + _groups = new List(); } [PrimaryKey(PrimaryKeyType.Native)] @@ -50,7 +52,7 @@ public String Name [HasAndBelongsToMany(typeof(Agent), Table = "GroupAgents", CompositeKeyColumnRefs = new String[] {"OrgId", "Name"}, ColumnKey = "GroupId", Lazy = true, Inverse=true, Cascade = ManyRelationCascadeEnum.SaveUpdate)] - public IList Agents + public IList Agents { get { return _agents; } set { _agents = value; } @@ -58,7 +60,7 @@ public IList Agents [HasAndBelongsToMany(typeof(Group), Table = "GroupOrgs", ColumnRef = "GroupId", ColumnKey = "OrgId", Lazy = true, Inverse=true, Cascade = ManyRelationCascadeEnum.SaveUpdate)] - public IList Groups + public IList Groups { get { return _groups; } set { _groups = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs index a666cb6..98acbf8 100644 --- a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs +++ b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs @@ -16,19 +16,20 @@ namespace Castle.ActiveRecord.Tests.Model.CompositeModel { using System; using System.Collections; + using System.Collections.Generic; - [ActiveRecord("Orgs")] + [ActiveRecord("Orgs")] public class Org : ActiveRecordBase { private string _id; private String _description; private DateTime _created; - private IList _agents; + private IList _agents; private int _version; public Org() { - _agents = new ArrayList(); + _agents = new List(); _created = DateTime.Now; _version = -1; } @@ -63,7 +64,7 @@ public String Contents [HasMany(typeof(Agent), Inverse=true, Lazy=true)] - public IList Agents + public IList Agents { get { return _agents; } set { _agents = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/Order.cs b/src/Castle.ActiveRecord.Tests/Model/Order.cs index 6da2fcd..32f03c7 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Order.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Order.cs @@ -76,7 +76,7 @@ public class OrderWithIDBag : ActiveRecordBase private int id; private DateTime ordered_date; private Boolean shipped; - private IList _products; + private IList _products; [PrimaryKey(PrimaryKeyType.Native, "OrderID")] public int ID @@ -109,7 +109,7 @@ public static OrderWithIDBag Find(int id) ColumnRef="product_id", ColumnKey="order_id"), CollectionID(CollectionIDType.HiLo, "line_number", "Int32"), Hilo(Table="testing_hilo", Column="sequence", MaxLo=150)] - public IList Products + public IList Products { get { return _products; } set { _products = value; } diff --git a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs index 52d2b51..f04ad4c 100644 --- a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs @@ -25,6 +25,8 @@ namespace Castle.ActiveRecord.Tests using NHibernate.Criterion; using NUnit.Framework; using System.Collections; + using System.Collections.Generic; + using Castle.ActiveRecord.Queries; [TestFixture] @@ -208,7 +210,7 @@ public void Updating_detached_entities_collections_does_not_work() using (new StatelessSessionScope()) { - blog.Posts = new ArrayList(); + blog.Posts = new List(); for (int i = 0; i < 10; i++) { diff --git a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs index ce4fa18..6bc46f7 100644 --- a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs @@ -182,14 +182,16 @@ public void ManyToManyUsingIDBag() OrderWithIDBag myOrder = new OrderWithIDBag(); myOrder.OrderedDate = new DateTime(2006, 12, 25); - ProductWithIDBag coolGadget = new ProductWithIDBag(); - coolGadget.Name = "Xbox 2"; - coolGadget.Price = 330.23f; - - using (new SessionScope()) + ProductWithIDBag coolGadget = new ProductWithIDBag + { + Name = "Xbox 2", + Price = 330.23f + }; + + using (new SessionScope()) { coolGadget.Save(); - IList products = new ArrayList(); + var products = new List(); products.Add(coolGadget); myOrder.Products = products; myOrder.Save(); diff --git a/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs b/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs index 2bfa20f..b9e5131 100644 --- a/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs +++ b/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs @@ -23,8 +23,8 @@ namespace Castle.ActiveRecord.ByteCode internal class ProxyFactory : AbstractProxyFactory { + private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ProxyFactory)); private readonly NHibernate.Proxy.DynamicProxy.ProxyFactory factory = new NHibernate.Proxy.DynamicProxy.ProxyFactory(); - protected static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ProxyFactory)); /// /// Build a proxy using the Castle.DynamicProxy library, that overrides the default @@ -37,7 +37,7 @@ public override INHibernateProxy GetProxy(object id, ISessionImplementor session try { var defaultLazyInitializer = new LazyInitializer(this.EntityName, this.PersistentClass, id, this.GetIdentifierMethod, this.SetIdentifierMethod, this.ComponentIdType, session); - return this.IsClassProxy ? (INHibernateProxy)this.factory.CreateProxy(this.PersistentClass, defaultLazyInitializer, this.Interfaces) : (INHibernateProxy)this.factory.CreateProxy(this.Interfaces[0], (NHibernate.Proxy.DynamicProxy.IInterceptor)defaultLazyInitializer, this.Interfaces); + return this.IsClassProxy ? (INHibernateProxy)this.factory.CreateProxy(this.PersistentClass, defaultLazyInitializer, this.Interfaces) : (INHibernateProxy)this.factory.CreateProxy(this.Interfaces[0], defaultLazyInitializer, this.Interfaces); } catch (Exception ex) { diff --git a/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs b/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs index b23ccab..e34816f 100644 --- a/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs +++ b/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs @@ -23,6 +23,12 @@ namespace Castle.ActiveRecord.ByteCode /// public class ProxyFactoryFactory : IProxyFactoryFactory { + + public IProxyValidator ProxyValidator + { + get { return new DynProxyTypeValidator(); } + } + public IProxyFactory BuildProxyFactory() { return new ProxyFactory(); @@ -33,11 +39,6 @@ public bool IsProxy(object entity) return entity is INHibernateProxy; } - public IProxyValidator ProxyValidator - { - get { return new DynProxyTypeValidator(); } - } - public bool IsInstrumented(System.Type entityClass) { return true; From 66544d97e8ab8a40f7106606e0b708d7f2c4fde9 Mon Sep 17 00:00:00 2001 From: Vilen Tambovtsev Date: Thu, 14 May 2015 17:49:09 +0300 Subject: [PATCH 5/6] fix more tests --- src/Castle.ActiveRecord.Tests/LazyTestCase.cs | 186 +-- src/Castle.ActiveRecord.Tests/Model/Blog.cs | 434 +++---- .../StatelessSessionScopeTestCase.cs | 696 +++++----- .../Castle.ActiveRecord-vs2010.csproj | 1 + .../Internal/Model/ActiveRecordModel.cs | 1122 +++++++++-------- .../Framework/StatelessSessionWrapper.cs | 8 +- 6 files changed, 1228 insertions(+), 1219 deletions(-) diff --git a/src/Castle.ActiveRecord.Tests/LazyTestCase.cs b/src/Castle.ActiveRecord.Tests/LazyTestCase.cs index e1b7419..b010312 100644 --- a/src/Castle.ActiveRecord.Tests/LazyTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/LazyTestCase.cs @@ -14,97 +14,97 @@ namespace Castle.ActiveRecord.Tests { - using NUnit.Framework; - - using Castle.ActiveRecord.Tests.Model; - - [TestFixture] - public class LazyTestCase : AbstractActiveRecordTest - { - [Test] - public void CanSaveAndLoadLazyEntityOutsideOfScope() - { - ActiveRecordStarter.Initialize(GetConfigSource(), - typeof(BlogLazy), typeof(PostLazy)); - Recreate(); - BlogLazy blog = new BlogLazy(); - blog.Save(); - PostLazy post = new PostLazy(blog, "a", "b", "c"); - post.Save(); - - PostLazy postFromDb = PostLazy.Find(post.Id); - Assert.AreEqual("a", postFromDb.Title); - } - - [Test] - public void CanSaveAndLoadLazy() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(VeryLazyObject)); - Recreate(); - VeryLazyObject lazy = new VeryLazyObject(); - lazy.Title = "test"; - - ActiveRecordMediator.Save(lazy); - - VeryLazyObject lazyFromDb = (VeryLazyObject) ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); - Assert.AreEqual("test", lazyFromDb.Title); - - lazyFromDb.Title = "test for update"; - ActiveRecordMediator.Update(lazyFromDb); - - lazyFromDb = (VeryLazyObject) ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); - Assert.AreEqual("test for update", lazyFromDb.Title); - } - - [Test] - public void CanLoadLazyProperty() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(LazyObjectWithLazyBlobProperty)); - Recreate(); - - string teststring = @"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg=="; - int id; - - using (new SessionScope()) - { - LazyObjectWithLazyBlobProperty lazy = new LazyObjectWithLazyBlobProperty(); - - lazy.BlobData = System.Text.Encoding.UTF8.GetBytes(teststring); - ActiveRecordMediator.Save(lazy); - id = lazy.Id; - } - - using (new SessionScope()) - { - LazyObjectWithLazyBlobProperty lazyFromDb = (LazyObjectWithLazyBlobProperty) ActiveRecordMediator.FindByPrimaryKey(typeof(LazyObjectWithLazyBlobProperty), id); - Assert.True(!NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); - - byte[] fromDb = lazyFromDb.BlobData; - Assert.True(NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); - - Assert.AreEqual(teststring, System.Text.Encoding.UTF8.GetString(fromDb)); - } - } - - [Test] - public void CanLoadLazyBelongsToOutsideOfScope() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(ScopelessLazy), typeof(ObjectWithLazyAssociation), typeof(VeryLazyObject2)); - - Recreate(); - - var lazy = new VeryLazyObject2(); - lazy.Title = "test"; - ActiveRecordMediator.Save(lazy); - - var obj = new ObjectWithLazyAssociation(); - obj.LazyObj = lazy; - ActiveRecordMediator.Save(obj); - - var objFromDb = (ObjectWithLazyAssociation) ActiveRecordMediator.FindByPrimaryKey(typeof(ObjectWithLazyAssociation), obj.Id); - Assert.False(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); - Assert.AreEqual("test", objFromDb.LazyObj.Title); - Assert.True(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); - } - } + using NUnit.Framework; + + using Castle.ActiveRecord.Tests.Model; + + [TestFixture] + public class LazyTestCase : AbstractActiveRecordTest + { + [Test] + public void CanSaveAndLoadLazyEntityOutsideOfScope() + { + ActiveRecordStarter.Initialize(GetConfigSource(), + typeof(BlogLazy), typeof(PostLazy)); + Recreate(); + BlogLazy blog = new BlogLazy(); + blog.Save(); + PostLazy post = new PostLazy(blog, "a", "b", "c"); + post.Save(); + + PostLazy postFromDb = PostLazy.Find(post.Id); + Assert.AreEqual("a", postFromDb.Title); + } + + [Test] + public void CanSaveAndLoadLazy() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(VeryLazyObject)); + Recreate(); + VeryLazyObject lazy = new VeryLazyObject(); + lazy.Title = "test"; + + ActiveRecordMediator.Save(lazy); + + VeryLazyObject lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); + Assert.AreEqual("test", lazyFromDb.Title); + + lazyFromDb.Title = "test for update"; + ActiveRecordMediator.Update(lazyFromDb); + + lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); + Assert.AreEqual("test for update", lazyFromDb.Title); + } + + [Test] + public void CanLoadLazyProperty() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(LazyObjectWithLazyBlobProperty)); + Recreate(); + + string teststring = @"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg=="; + int id; + + using (new SessionScope()) + { + LazyObjectWithLazyBlobProperty lazy = new LazyObjectWithLazyBlobProperty(); + + lazy.BlobData = System.Text.Encoding.UTF8.GetBytes(teststring); + ActiveRecordMediator.Save(lazy); + id = lazy.Id; + } + + using (new SessionScope()) + { + LazyObjectWithLazyBlobProperty lazyFromDb = (LazyObjectWithLazyBlobProperty)ActiveRecordMediator.FindByPrimaryKey(typeof(LazyObjectWithLazyBlobProperty), id); + Assert.True(!NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); + + byte[] fromDb = lazyFromDb.BlobData; + Assert.True(NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); + + Assert.AreEqual(teststring, System.Text.Encoding.UTF8.GetString(fromDb)); + } + } + + [Test] + public void CanLoadLazyBelongsToOutsideOfScope() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(ScopelessLazy), typeof(ObjectWithLazyAssociation), typeof(VeryLazyObject2)); + + Recreate(); + + var lazy = new VeryLazyObject2(); + lazy.Title = "test"; + ActiveRecordMediator.Save(lazy); + + var obj = new ObjectWithLazyAssociation(); + obj.LazyObj = lazy; + ActiveRecordMediator.Save(obj); + + var objFromDb = (ObjectWithLazyAssociation)ActiveRecordMediator.FindByPrimaryKey(typeof(ObjectWithLazyAssociation), obj.Id); + Assert.False(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); + Assert.AreEqual("test", objFromDb.LazyObj.Title); + Assert.True(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); + } + } } diff --git a/src/Castle.ActiveRecord.Tests/Model/Blog.cs b/src/Castle.ActiveRecord.Tests/Model/Blog.cs index abac130..bcf5a94 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Blog.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Blog.cs @@ -14,151 +14,151 @@ namespace Castle.ActiveRecord.Tests.Model { - using System; - using System.Collections; - using System.Collections.Generic; - - using Castle.ActiveRecord.Framework; - using NHibernate; - using NHibernate.Criterion; - - [ActiveRecord("BlogTable")] - public class Blog : ActiveRecordBase - { - private int _id; - private String _name; - private String _author; - private IList _posts; - private IList _publishedposts; - private IList _unpublishedposts; - private IList _recentposts; - private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; - - public Blog() - { - } - - public Blog(int _id) - { - this._id = _id; - } - - [PrimaryKey(PrimaryKeyType.Native)] - public int Id - { - get { return _id; } - set { _id = value; } - } - - [Property] - public String Name - { - get { return _name; } - set { _name = value; } - } - - [Property] - public String Author - { - get { return _author; } - set { _author = value; } - } - - [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid")] - public IList Posts - { - get { return _posts; } - set { _posts = value; } - } - - [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", Where="published = 1")] + using System; + using System.Collections; + using System.Collections.Generic; + + using Castle.ActiveRecord.Framework; + using NHibernate; + using NHibernate.Criterion; + + [ActiveRecord("BlogTable")] + public class Blog : ActiveRecordBase + { + private int _id; + private String _name; + private String _author; + private IList _posts; + private IList _publishedposts; + private IList _unpublishedposts; + private IList _recentposts; + private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; + + public Blog() + { + } + + public Blog(int _id) + { + this._id = _id; + } + + [PrimaryKey(PrimaryKeyType.Native)] + public int Id + { + get { return _id; } + set { _id = value; } + } + + [Property] + public String Name + { + get { return _name; } + set { _name = value; } + } + + [Property] + public String Author + { + get { return _author; } + set { _author = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid")] + public IList Posts + { + get { return _posts; } + set { _posts = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 1")] public IList PublishedPosts - { - get { return _publishedposts; } - set { _publishedposts = value; } - } + { + get { return _publishedposts; } + set { _publishedposts = value; } + } - [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", Where="published = 0")] + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 0")] public IList UnPublishedPosts - { - get { return _unpublishedposts; } - set { _unpublishedposts = value; } - } + { + get { return _unpublishedposts; } + set { _unpublishedposts = value; } + } - [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", OrderBy="created desc")] + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", OrderBy = "created desc")] public IList RecentPosts - { - get { return _recentposts; } - set { _recentposts = value; } - } + { + get { return _recentposts; } + set { _recentposts = value; } + } - [Property(Formula = "1 + 1")] - public int SomeFormula { get; set; } + [Property(Formula = "1 + 1")] + public int SomeFormula { get; set; } - public static void DeleteAll() - { - ActiveRecordMediator.DeleteAll(typeof(Blog)); - } + public static void DeleteAll() + { + ActiveRecordMediator.DeleteAll(typeof(Blog)); + } - public static void DeleteAll(string where) - { - ActiveRecordMediator.DeleteAll(typeof(Blog), where); - } + public static void DeleteAll(string where) + { + ActiveRecordMediator.DeleteAll(typeof(Blog), where); + } - public static Blog[] FindAll() - { - return (Blog[]) ActiveRecordMediator.FindAll(typeof(Blog)); - } + public static Blog[] FindAll() + { + return (Blog[])ActiveRecordMediator.FindAll(typeof(Blog)); + } public static Blog[] FindAll(IDetachedQuery dq) { - return (Blog[]) FindAll(typeof(Blog), dq); + return (Blog[])FindAll(typeof(Blog), dq); } - public static Blog Find(int id) - { - return (Blog) ActiveRecordMediator.FindByPrimaryKey(typeof(Blog), id); - } + public static Blog Find(int id) + { + return (Blog)ActiveRecordMediator.FindByPrimaryKey(typeof(Blog), id); + } public static Blog FindOne(IDetachedQuery dq) { - return (Blog) FindOne(typeof(Blog), dq); + return (Blog)FindOne(typeof(Blog), dq); } - public static int FetchCount() - { - return Count(typeof(Blog)); - } + public static int FetchCount() + { + return Count(typeof(Blog)); + } - public static int FetchCount(string filter, params object[] args) - { - return Count(typeof(Blog), filter, args); - } + public static int FetchCount(string filter, params object[] args) + { + return Count(typeof(Blog), filter, args); + } - public static int FetchCount(params ICriterion[] criterias) - { - return Count(typeof(Blog), criterias); - } + public static int FetchCount(params ICriterion[] criterias) + { + return Count(typeof(Blog), criterias); + } - public static bool Exists() - { - return Exists(typeof(Blog)); - } + public static bool Exists() + { + return Exists(typeof(Blog)); + } - public static bool Exists(string filter, params object[] args) - { - return Exists(typeof(Blog), filter, args); - } + public static bool Exists(string filter, params object[] args) + { + return Exists(typeof(Blog), filter, args); + } - public static bool Exists(int id) - { - return Exists(typeof(Blog), id); - } + public static bool Exists(int id) + { + return Exists(typeof(Blog), id); + } - public static bool Exists(params ICriterion[] criteria) - { - return Exists(typeof(Blog), criteria); - } + public static bool Exists(params ICriterion[] criteria) + { + return Exists(typeof(Blog), criteria); + } public static bool Exists(IDetachedQuery dq) { @@ -167,101 +167,101 @@ public static bool Exists(IDetachedQuery dq) public static Blog[] SlicedFindAll(int FirstResult, int MaxResult, IDetachedQuery dq) { - return (Blog[]) SlicedFindAll(typeof(Blog), FirstResult, MaxResult, dq); - } - - public static Blog[] FindByProperty(String property, object value) - { - return (Blog[]) FindAllByProperty(typeof(Blog), property, value); - } - - public static Blog[] FindByProperty(String property, String orderByColumn, object value) - { - return (Blog[]) FindAllByProperty(typeof(Blog), orderByColumn, property, value); - } - - /// - /// Lifecycle method invoked during Save of the entity - /// - protected override void OnSave() - { - onSaveCalled = true; - } - - /// - /// Lifecycle method invoked during Update of the entity - /// - protected override void OnUpdate() - { - onUpdateCalled = true; - } - - /// - /// Lifecycle method invoked during Delete of the entity - /// - protected override void OnDelete() - { - onDeleteCalled = true; - } - - /// - /// Lifecycle method invoked during Load of the entity - /// - protected override void OnLoad(object id) - { - onLoadCalled = true; - } - - public bool OnSaveCalled - { - get { return onSaveCalled; } - } - - public bool OnUpdateCalled - { - get { return onUpdateCalled; } - } - - public bool OnDeleteCalled - { - get { return onDeleteCalled; } - } - - public bool OnLoadCalled - { - get { return onLoadCalled; } - } - - public ISession CurrentSession - { - get - { - return (ISession) - ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(GrabSession), this); - } - } - - private static object GrabSession(ISession session, object instance) - { - return session; - } - - public void CustomAction() - { - ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(MyCustomMethod), this); - } - - private static object MyCustomMethod(ISession session, object blogInstance) - { - session.Delete(blogInstance); - session.Flush(); - - return null; - } - - internal static ISessionFactoryHolder Holder - { - get { return ActiveRecordMediator.GetSessionFactoryHolder(); } - } - } + return (Blog[])SlicedFindAll(typeof(Blog), FirstResult, MaxResult, dq); + } + + public static Blog[] FindByProperty(String property, object value) + { + return (Blog[])FindAllByProperty(typeof(Blog), property, value); + } + + public static Blog[] FindByProperty(String property, String orderByColumn, object value) + { + return (Blog[])FindAllByProperty(typeof(Blog), orderByColumn, property, value); + } + + /// + /// Lifecycle method invoked during Save of the entity + /// + protected override void OnSave() + { + onSaveCalled = true; + } + + /// + /// Lifecycle method invoked during Update of the entity + /// + protected override void OnUpdate() + { + onUpdateCalled = true; + } + + /// + /// Lifecycle method invoked during Delete of the entity + /// + protected override void OnDelete() + { + onDeleteCalled = true; + } + + /// + /// Lifecycle method invoked during Load of the entity + /// + protected override void OnLoad(object id) + { + onLoadCalled = true; + } + + public bool OnSaveCalled + { + get { return onSaveCalled; } + } + + public bool OnUpdateCalled + { + get { return onUpdateCalled; } + } + + public bool OnDeleteCalled + { + get { return onDeleteCalled; } + } + + public bool OnLoadCalled + { + get { return onLoadCalled; } + } + + public ISession CurrentSession + { + get + { + return (ISession) + ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(GrabSession), this); + } + } + + private static object GrabSession(ISession session, object instance) + { + return session; + } + + public void CustomAction() + { + ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(MyCustomMethod), this); + } + + private static object MyCustomMethod(ISession session, object blogInstance) + { + session.Delete(blogInstance); + session.Flush(); + + return null; + } + + internal static ISessionFactoryHolder Holder + { + get { return ActiveRecordMediator.GetSessionFactoryHolder(); } + } + } } diff --git a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs index f04ad4c..84eac0d 100644 --- a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs @@ -14,353 +14,355 @@ namespace Castle.ActiveRecord.Tests { - using System; - using Castle.ActiveRecord; - using Castle.ActiveRecord.Framework; - using Castle.ActiveRecord.Framework.Config; - using Castle.ActiveRecord.Framework.Scopes; - using Castle.ActiveRecord.Tests.Model; - using Castle.ActiveRecord.Tests.Model.LazyModel; - using NHibernate; - using NHibernate.Criterion; - using NUnit.Framework; - using System.Collections; - using System.Collections.Generic; - - using Castle.ActiveRecord.Queries; - - [TestFixture] - public class StatelessSessionScopeTestCase : AbstractActiveRecordTest - { - [Test] - public void SessionIsStateless() - { - Initialize(); - using (new StatelessSessionScope()) - { - Assert.IsAssignableFrom(typeof(StatelessSessionWrapper), Blog.Holder.CreateSession(typeof(Blog))); - } - } - - [Test] - public void Unsupported_actions_should_have_squattery_exceptions() - { - Initialize(); - using (new StatelessSessionScope()) - { - try - { - Blog.Holder.CreateSession(typeof(Blog)).Merge(null); - Assert.Fail(); - } - catch (NotImplementedException ex) - { - Assert.AreEqual(@"The called method is not supported. + using System; + using Castle.ActiveRecord; + using Castle.ActiveRecord.Framework; + using Castle.ActiveRecord.Framework.Config; + using Castle.ActiveRecord.Framework.Scopes; + using Castle.ActiveRecord.Tests.Model; + using Castle.ActiveRecord.Tests.Model.LazyModel; + using NHibernate; + using NHibernate.Criterion; + using NUnit.Framework; + using System.Collections; + using System.Collections.Generic; + + using Castle.ActiveRecord.Queries; + + [TestFixture] + public class StatelessSessionScopeTestCase : AbstractActiveRecordTest + { + [Test] + public void SessionIsStateless() + { + Initialize(); + using (new StatelessSessionScope()) + { + Assert.IsAssignableFrom(typeof(StatelessSessionWrapper), Blog.Holder.CreateSession(typeof(Blog))); + } + } + + [Test] + public void Unsupported_actions_should_have_squattery_exceptions() + { + Initialize(); + using (new StatelessSessionScope()) + { + try + { + Blog.Holder.CreateSession(typeof(Blog)).Merge(null); + Assert.Fail(); + } + catch (NotImplementedException ex) + { + Assert.AreEqual(@"The called method is not supported. ActiveRecord is currently running within a StatelessSessionScope. Stateless sessions are faster than normal sessions, but they do not support all methods and properties that a normal session allows. Please check the stacktrace and change your code accordingly.", ex.Message); - } - } - } - - [Test] - public void A_simple_object_can_be_created() - { - Initialize(); - using (new StatelessSessionScope()) - CreateBlog(); - - Blog[] blogs = Blog.FindAll(); - Assert.AreEqual(1, blogs.Length); - Assert.AreEqual("Mort", blogs[0].Author); - } - - [Test] - public void A_simple_object_can_be_read() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Ship)); - Recreate(); - - using (new SessionScope()) - ActiveRecordMediator.Create(new Ship { Name = "Andrea Doria" }); - - using (new StatelessSessionScope()) - { - Assert.IsTrue(ActiveRecordMediator.Exists(1)); - Assert.AreEqual("Andrea Doria",ActiveRecordMediator.FindByPrimaryKey(1).Name); - } - } - - [Test] - public void Get_with_lazy_classes_does_work() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(BlogLazy), typeof(PostLazy)); - Recreate(); - - using (new SessionScope()) - new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); - - using (new StatelessSessionScope()) - { - Assert.AreEqual("Mort", BlogLazy.Find(1).Author); - // The assert below cannot work, stateless sessions cannot serve proxies. - // Assert.AreEqual(0, BlogLazy.Find(1).Posts.Count); - } - } - - [Test] - public void Get_with_nonlazy_classes_does_not_work() - { - Initialize(); - - using (new SessionScope()) - new Blog { Author = "Mort", Name = "Hourglass" }.Create(); - - using (new StatelessSessionScope()) - { - try - { - Blog.Find(1); - Assert.Fail(); - } - catch(ActiveRecordException ex) - { - Assert.AreEqual(typeof(SessionException),ex.InnerException.GetType()); - Assert.AreEqual("collections cannot be fetched by a stateless session", ex.InnerException.Message); - } - } - } - - [Test] - public void Updating_stateless_fetched_entities_works() - { - InitializeLazy(); - - using (new SessionScope()) - CreateLazyBlog(); - - using (new StatelessSessionScope()) - { - var blog = BlogLazy.Find(1); - Assert.AreEqual("Hourglass", blog.Name); - blog.Name = "HOURGLASS"; - blog.Update(); - } - - Assert.AreEqual("HOURGLASS", BlogLazy.Find(1).Name); - } - - [Test] - public void Updating_detached_entities_works() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - Assert.AreEqual("Hourglass", blog.Name); - blog.Name = "HOURGLASS"; - blog.Update(); - } - - Assert.AreEqual("HOURGLASS", Blog.Find(1).Name); - } - - [Test] - public void Inversively_adding_to_a_detached_entitys_collections_works() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - for (int i = 0; i < 10; i++) - { - var post = new Post() { Blog = blog, Title = "Post" + i, Created = DateTime.Now }; - post.Create(); - } - } - - Assert.AreEqual(10, Blog.Find(1).Posts.Count); - } - - - [Test] - public void Updating_detached_entities_collections_does_not_work() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - blog.Posts = new List(); - - for (int i = 0; i < 10; i++) - { - var post = new Post() { Title = "Post" + i, Created = DateTime.Now}; - post.Create(); - blog.Posts.Add(post); - } - - blog.Update(); - } - - Assert.AreEqual(0, Blog.Find(1).Posts.Count); - } - - [Test] - public void Transactions_are_supported() - { - Initialize(); - - using (new StatelessSessionScope()) - using (new TransactionScope()) - { - CreateBlog(); - } - - Assert.AreEqual("Mort", Blog.Find(1).Author); - } - - [Test] - public void Querying_works_with_HQL() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - Assert.AreEqual(1, query.Execute().Length); - - } - - [Test] - public void Enumerating_with_queries_doesnt_work() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - query.Enumerate(); - } - - [Test] - public void Can_delete_instances() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - { - foreach (var blog in query.Execute()) - blog.Delete(); - } - - Assert.AreEqual(0, BlogLazy.FindAll().Length); - } - - [Test] - public void Querying_works_with_Detached_Criteria() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var crit = DetachedCriteria.For().Add(Expression.Eq("Author", "Mort")); - using (new StatelessSessionScope()) - Assert.AreEqual(1, ActiveRecordMediator.FindAll(crit).Length); - - } - - [Test] - public void Collections_can_be_fetched_with_queries() - { - InitializeLazy(); - - var blog = new BlogLazy { Author = "Mort", Name = "Hourglass" }; - var post = new PostLazy { Blog = blog, Title = "...", Created = DateTime.Now }; - - blog.Save(); - post.Save(); - - var query = new SimpleQuery("from BlogLazy b join fetch b.Posts"); - - using (new StatelessSessionScope()) - { - var result = query.Execute(); - Assert.AreEqual(1, result.Length); - Assert.AreEqual(1, result[0].Posts.Count); - var queriedPost = result[0].Posts[0] as PostLazy; - Assert.AreEqual("...", queriedPost.Title); - } - } - - [Test] - public void Nonlazy_collections_can_be_fetched_with_queries() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(SimpleBlog), typeof(SimplePost)); - Recreate(); - - var blog = new SimpleBlog { Name = "Blog" }; - var post = new SimplePost { Blog = blog, Title = "Post" }; - blog.Save(); - post.Save(); - - var query = new SimpleQuery("from SimpleBlog b join fetch b.Posts"); - - using (new StatelessSessionScope()) - { - var result = query.Execute(); - Assert.AreEqual(1, result.Length); - Assert.AreEqual(1, result[0].Posts.Count); - Assert.AreEqual("Post", result[0].Posts[0].Title); - Assert.AreSame(result[0], result[0].Posts[0].Blog); - } - } - - private void Initialize() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog)); - Recreate(); - } - - private void InitializeLazy() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy)); - Recreate(); - } - - private void CreateBlog() - { - new Blog { Author = "Mort", Name = "Hourglass" }.Create(); - } - - - private void CreateLazyBlog() - { - new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); - } - } + } + } + } + + [Test] + public void A_simple_object_can_be_created() + { + Initialize(); + using (new StatelessSessionScope()) + CreateBlog(); + + Blog[] blogs = Blog.FindAll(); + Assert.AreEqual(1, blogs.Length); + Assert.AreEqual("Mort", blogs[0].Author); + } + + [Test] + public void A_simple_object_can_be_read() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Ship)); + Recreate(); + + using (new SessionScope()) + ActiveRecordMediator.Create(new Ship { Name = "Andrea Doria" }); + + using (new StatelessSessionScope()) + { + Assert.IsTrue(ActiveRecordMediator.Exists(1)); + Assert.AreEqual("Andrea Doria", ActiveRecordMediator.FindByPrimaryKey(1).Name); + } + } + + [Test] + public void Get_with_lazy_classes_does_work() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(BlogLazy), typeof(PostLazy)); + Recreate(); + + using (new SessionScope()) + new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); + + using (new StatelessSessionScope()) + { + Assert.AreEqual("Mort", BlogLazy.Find(1).Author); + // The assert below cannot work, stateless sessions cannot serve proxies. + // Assert.AreEqual(0, BlogLazy.Find(1).Posts.Count); + } + } + + [Test] + public void Get_with_nonlazy_classes_does_not_work() + { + Initialize(); + + using (new SessionScope()) + new Blog { Author = "Mort", Name = "Hourglass" }.Create(); + + using (new StatelessSessionScope()) + { + try + { + Blog.Find(1); + Assert.Fail(); + } + catch (ActiveRecordException ex) + { + Assert.AreEqual(typeof(SessionException), ex.InnerException.GetType()); + Assert.AreEqual("collections cannot be fetched by a stateless session", ex.InnerException.Message); + } + } + } + + [Test] + public void Updating_stateless_fetched_entities_works() + { + InitializeLazy(); + + using (new SessionScope()) + { + CreateLazyBlog(); + } + + using (new StatelessSessionScope()) + { + var blog = BlogLazy.Find(1); + Assert.AreEqual("Hourglass", blog.Name); + blog.Name = "HOURGLASS"; + blog.Update(); + } + + Assert.AreEqual("HOURGLASS", BlogLazy.Find(1).Name); + } + + [Test] + public void Updating_detached_entities_works() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + Assert.AreEqual("Hourglass", blog.Name); + blog.Name = "HOURGLASS"; + blog.Update(); + } + + Assert.AreEqual("HOURGLASS", Blog.Find(1).Name); + } + + [Test] + public void Inversively_adding_to_a_detached_entitys_collections_works() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + for (int i = 0; i < 10; i++) + { + var post = new Post() { Blog = blog, Title = "Post" + i, Created = DateTime.Now }; + post.Create(); + } + } + + Assert.AreEqual(10, Blog.Find(1).Posts.Count); + } + + + [Test] + public void Updating_detached_entities_collections_does_not_work() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + blog.Posts = new List(); + + for (int i = 0; i < 10; i++) + { + var post = new Post() { Title = "Post" + i, Created = DateTime.Now }; + post.Create(); + blog.Posts.Add(post); + } + + blog.Update(); + } + + Assert.AreEqual(0, Blog.Find(1).Posts.Count); + } + + [Test] + public void Transactions_are_supported() + { + Initialize(); + + using (new StatelessSessionScope()) + using (new TransactionScope()) + { + CreateBlog(); + } + + Assert.AreEqual("Mort", Blog.Find(1).Author); + } + + [Test] + public void Querying_works_with_HQL() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + Assert.AreEqual(1, query.Execute().Length); + + } + + [Test] + public void Enumerating_with_queries_doesnt_work() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + query.Enumerate(); + } + + [Test] + public void Can_delete_instances() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + { + foreach (var blog in query.Execute()) + blog.Delete(); + } + + Assert.AreEqual(0, BlogLazy.FindAll().Length); + } + + [Test] + public void Querying_works_with_Detached_Criteria() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var crit = DetachedCriteria.For().Add(Expression.Eq("Author", "Mort")); + using (new StatelessSessionScope()) + Assert.AreEqual(1, ActiveRecordMediator.FindAll(crit).Length); + + } + + [Test] + public void Collections_can_be_fetched_with_queries() + { + InitializeLazy(); + + var blog = new BlogLazy { Author = "Mort", Name = "Hourglass" }; + var post = new PostLazy { Blog = blog, Title = "...", Created = DateTime.Now }; + + blog.Save(); + post.Save(); + + var query = new SimpleQuery("from BlogLazy b join fetch b.Posts"); + + using (new StatelessSessionScope()) + { + var result = query.Execute(); + Assert.AreEqual(1, result.Length); + Assert.AreEqual(1, result[0].Posts.Count); + var queriedPost = result[0].Posts[0] as PostLazy; + Assert.AreEqual("...", queriedPost.Title); + } + } + + [Test] + public void Nonlazy_collections_can_be_fetched_with_queries() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(SimpleBlog), typeof(SimplePost)); + Recreate(); + + var blog = new SimpleBlog { Name = "Blog" }; + var post = new SimplePost { Blog = blog, Title = "Post" }; + blog.Save(); + post.Save(); + + var query = new SimpleQuery("from SimpleBlog b join fetch b.Posts"); + + using (new StatelessSessionScope()) + { + var result = query.Execute(); + Assert.AreEqual(1, result.Length); + Assert.AreEqual(1, result[0].Posts.Count); + Assert.AreEqual("Post", result[0].Posts[0].Title); + Assert.AreSame(result[0], result[0].Posts[0].Blog); + } + } + + private void Initialize() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog)); + Recreate(); + } + + private void InitializeLazy() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy)); + Recreate(); + } + + private void CreateBlog() + { + new Blog { Author = "Mort", Name = "Hourglass" }.Create(); + } + + + private void CreateLazyBlog() + { + new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); + } + } } diff --git a/src/Castle.ActiveRecord/Castle.ActiveRecord-vs2010.csproj b/src/Castle.ActiveRecord/Castle.ActiveRecord-vs2010.csproj index 528e8e1..48eee07 100644 --- a/src/Castle.ActiveRecord/Castle.ActiveRecord-vs2010.csproj +++ b/src/Castle.ActiveRecord/Castle.ActiveRecord-vs2010.csproj @@ -65,6 +65,7 @@ 1591 true + true v4.0 diff --git a/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs b/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs index 3872595..3315661 100644 --- a/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs +++ b/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs @@ -14,564 +14,566 @@ namespace Castle.ActiveRecord.Framework.Internal { - using System; - using System.Collections; - using System.Collections.Generic; - using System.Reflection; - using Castle.Components.Validator; - - /// - /// This model of a full Active Record persistent class. - /// - [Serializable] - public class ActiveRecordModel : IVisitable - { - /// - /// The mapping between a type and a model - /// - protected internal static IDictionary type2Model = Hashtable.Synchronized(new Hashtable()); - - /// - /// Whatever Active Record will generate debug information or not - /// - protected internal static bool isDebug = false; - - /// - /// Whatever types that does not explicitly state that they are lazy should be lazy. - /// - protected internal static bool isLazyByDefault = false; - - /// - /// Whether the default inferred table name is plural - /// - protected internal static bool pluralizeTableNames = false; - - private readonly Type type; - - private bool isJoinedSubClassBase; - private bool isDiscriminatorBase; - private bool isDiscriminatorSubClass; - private bool isJoinedSubClass; - private bool isNestedType; - private bool isNestedCompositeType; - - private ActiveRecordAttribute arAtt; - private ActiveRecordModel parent; - private PrimaryKeyModel primaryKey; - private CompositeKeyModel compositeKey; - private KeyModel key; - private TimestampModel timestamp; - private VersionModel version; - private NestedModel parentNested; - - private readonly IList imports = new List(); - private readonly IList hasManyToAny = new List(); - private readonly IList anys = new List(); - private readonly IList properties = new List(); - private readonly IList fields = new List(); - private readonly IList componentParent = new List(); - private readonly IList classes = new List(); - private readonly IList joinedclasses = new List(); - private readonly IList joinedTables = new List(); - private readonly IList components = new List(); - private readonly IList belongsTo = new List(); - private readonly IList hasMany = new List(); - private readonly IList hasAndBelongsToMany = new List(); - private readonly IList oneToOne = new List(); - private readonly IList collectionIds = new List(); - private readonly IList hilos = new List(); - private readonly IList notMappedProperties = new List(); - private readonly IList compositeUserType = new List(); - private readonly IList validators = new List(); - - private readonly IDictionary extendedProperties = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary propertyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary belongsToDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasManyToAnyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasManyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasAndBelongsToManyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - /// - /// Initializes a new instance of the class. - /// - /// The type. - public ActiveRecordModel(Type type) - { - this.type = type; - } - - /// - /// Gets or sets the parent model - /// - /// The parent. - public ActiveRecordModel Parent - { - get { return parent; } - set { parent = value; } - } - - /// - /// Gets the type for this model - /// - /// The type. - public Type Type - { - get { return type; } - } - - /// - /// Gets or sets a value indicating whether this instance is joined sub class base. - /// - /// - /// true if this instance is joined sub class base; otherwise, false. - /// - public bool IsJoinedSubClassBase - { - get { return isJoinedSubClassBase; } - set { isJoinedSubClassBase = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is discriminator base. - /// - /// - /// true if this instance is discriminator base; otherwise, false. - /// - public bool IsDiscriminatorBase - { - get { return isDiscriminatorBase; } - set { isDiscriminatorBase = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is discriminator sub class. - /// - /// - /// true if this instance is discriminator sub class; otherwise, false. - /// - public bool IsDiscriminatorSubClass - { - get { return isDiscriminatorSubClass; } - set { isDiscriminatorSubClass = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is joined sub class. - /// - /// - /// true if this instance is joined sub class; otherwise, false. - /// - public bool IsJoinedSubClass - { - get { return isJoinedSubClass; } - set { isJoinedSubClass = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is nested type. - /// - /// - /// true if this instance is nested type; otherwise, false. - /// - public bool IsNestedType - { - get { return isNestedType; } - set { isNestedType = value; } - } - - /// - /// Gets or sets the parent nested. - /// - /// The parent nested. - public NestedModel ParentNested - { - get { return parentNested; } - set { parentNested = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is nested type. - /// - /// - /// true if this instance is nested type; otherwise, false. - /// - public bool IsNestedCompositeType - { - get { return isNestedCompositeType; } - set { isNestedCompositeType = value; } - } - - /// - /// Gets or sets the active record attribute - /// - /// The active record att. - public ActiveRecordAttribute ActiveRecordAtt - { - get { return arAtt; } - set { arAtt = value; } - } - - /// - /// Used only by joined subclasses - /// - public KeyModel Key - { - get { return key; } - set { key = value; } - } - - /// - /// Gets or sets the timestamp model - /// - /// The timestamp. - public TimestampModel Timestamp - { - get { return timestamp; } - set { timestamp = value; } - } - - /// - /// Gets or sets the version model - /// - /// The version. - public VersionModel Version - { - get { return version; } - set { version = value; } - } - - /// - /// Gets all the imports - /// - /// The imports. - public IList Imports - { - get { return imports; } - } - - /// - /// Gets all the properties - /// - /// The properties. - public IList Properties - { - get { return properties; } - } - - /// - /// Gets all the fields - /// - /// The fields. - public IList Fields - { - get { return fields; } - } - - /// - /// If the object is a component, will return the objects declared parent property. - /// There should only be one, but implemented as a list - /// - public IList ComponentParent - { - get { return componentParent; } - } - - /// - /// Gets the list of [has many to any] models - /// - /// The has many to any. - public IList HasManyToAny - { - get { return hasManyToAny; } - } - - /// - /// Gets the list of [any] model - /// - /// The anys. - public IList Anys - { - get { return anys; } - } - - /// - /// Gets the list of the derived classes - /// - /// The classes. - public IList Classes - { - get { return classes; } - } - - /// - /// Gets the list of derived joined classes. - /// - /// The joined classes. - public IList JoinedClasses - { - get { return joinedclasses; } - } - - /// - /// Gets the list of joined tables. - /// - /// The joined tables. - public IList JoinedTables - { - get { return joinedTables; } - } - - /// - /// Gets the list of components. - /// - /// The components. - public IList Components - { - get { return components; } - } - - /// - /// Gets the list of [belongs to] models - /// - /// The belongs to. - public IList BelongsTo - { - get { return belongsTo; } - } - - /// - /// Gets the list of [has many] models - /// - /// The has many. - public IList HasMany - { - get { return hasMany; } - } - - /// - /// Gets the list of [has and belongs to many] models - /// - /// The has and belongs to many. - public IList HasAndBelongsToMany - { - get { return hasAndBelongsToMany; } - } - - /// - /// Gets the list of [one to one] models - /// - /// The one to ones. - public IList OneToOnes - { - get { return oneToOne; } - } - - /// - /// Gets the list of [collection id] models - /// - /// The collection I ds. - public IList CollectionIDs - { - get { return collectionIds; } - } - - /// - /// For unique Primary keys - /// - public PrimaryKeyModel PrimaryKey - { - get { return primaryKey; } - set { primaryKey = value; } - } - - /// - /// For Composite Primary keys - /// - public CompositeKeyModel CompositeKey - { - get { return compositeKey; } - set { compositeKey = value; } - } - - /// - /// Gets the list of [hilo] models - /// - /// The hilos. - public IList Hilos - { - get { return hilos; } - } - - /// - /// Gets the list of properties not mapped . - /// - /// The not mapped properties. - public IList NotMappedProperties - { - get { return notMappedProperties; } - } - - /// - /// Gets the validators. - /// - /// The validators. - public IList Validators - { - get { return validators; } - } - - /// - /// Gets a value indicating whether to use auto import - /// - /// true if should use auto import; otherwise, false. - public bool UseAutoImport - { - get - { - if (arAtt != null) - { - return arAtt.UseAutoImport; - } - - return true; - } - } - - /// - /// Gets the composite user types properties. - /// - /// The type of the composite user. - public IList CompositeUserType - { - get { return compositeUserType; } - } - - /// - /// Gets the extended properties. Used to store/retrieve information collected by model builder extensions. - /// - /// - /// The extended properties. - public IDictionary ExtendedProperties - { - get { return extendedProperties; } - } - - /// - /// Gets the property dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The property dictionary. - public IDictionary PropertyDictionary - { - get { return propertyDictionary; } - } - - /// - /// Gets the belongs to dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The belongs to dictionary. - public IDictionary BelongsToDictionary - { - get { return belongsToDictionary; } - } - - /// - /// Gets the has many to any dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has many to any dictionary. - public IDictionary HasManyToAnyDictionary - { - get { return hasManyToAnyDictionary; } - } - - /// - /// Gets the has many dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has many dictionary. - public IDictionary HasManyDictionary - { - get { return hasManyDictionary; } - } - - /// - /// Gets the has and belongs to many dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has and belongs to many dictionary. - public IDictionary HasAndBelongsToManyDictionary - { - get { return hasAndBelongsToManyDictionary; } - } - - /// - /// Used internally register an association between a type and its model - /// - /// - /// - internal static void Register(Type arType, ActiveRecordModel model) - { - type2Model[arType] = model; - } - - /// - /// Gets the for a given ActiveRecord class. - /// - public static ActiveRecordModel GetModel(Type arType) - { - arType = GetNonProxy(arType); - return (ActiveRecordModel) type2Model[arType]; - } - - /// - /// Gets an array containing the for every registered ActiveRecord class. - /// - public static ActiveRecordModel[] GetModels() - { - ActiveRecordModel[] modelArray = new ActiveRecordModel[type2Model.Values.Count]; - - type2Model.Values.CopyTo(modelArray, 0); - - return modelArray; - } - - /// - /// Get the base type is the object is lazy - /// - private static Type GetNonProxy(Type type) - { - if (type.GetField("__interceptor") != null ||//Dynamic Proxy 1.0 - type.GetField("__interceptors")!=null) //Dynamic Proxy 2.0 - { - type = type.BaseType; - } - return type; - } - - #region IVisitable Members - - /// - /// Accepts the specified visitor and call the relevant IVisitor.Visit***() method - /// - /// The visitor. - public void Accept(IVisitor visitor) - { - visitor.VisitModel(this); - } - - #endregion - } + using System; + using System.Collections; + using System.Collections.Generic; + using System.Reflection; + using Castle.Components.Validator; + + /// + /// This model of a full Active Record persistent class. + /// + [Serializable] + public class ActiveRecordModel : IVisitable + { + /// + /// The mapping between a type and a model + /// + protected internal static IDictionary type2Model = Hashtable.Synchronized(new Hashtable()); + + /// + /// Whatever Active Record will generate debug information or not + /// + protected internal static bool isDebug = false; + + /// + /// Whatever types that does not explicitly state that they are lazy should be lazy. + /// + protected internal static bool isLazyByDefault = false; + + /// + /// Whether the default inferred table name is plural + /// + protected internal static bool pluralizeTableNames = false; + + private readonly Type type; + + private bool isJoinedSubClassBase; + private bool isDiscriminatorBase; + private bool isDiscriminatorSubClass; + private bool isJoinedSubClass; + private bool isNestedType; + private bool isNestedCompositeType; + + private ActiveRecordAttribute arAtt; + private ActiveRecordModel parent; + private PrimaryKeyModel primaryKey; + private CompositeKeyModel compositeKey; + private KeyModel key; + private TimestampModel timestamp; + private VersionModel version; + private NestedModel parentNested; + + private readonly IList imports = new List(); + private readonly IList hasManyToAny = new List(); + private readonly IList anys = new List(); + private readonly IList properties = new List(); + private readonly IList fields = new List(); + private readonly IList componentParent = new List(); + private readonly IList classes = new List(); + private readonly IList joinedclasses = new List(); + private readonly IList joinedTables = new List(); + private readonly IList components = new List(); + private readonly IList belongsTo = new List(); + private readonly IList hasMany = new List(); + private readonly IList hasAndBelongsToMany = new List(); + private readonly IList oneToOne = new List(); + private readonly IList collectionIds = new List(); + private readonly IList hilos = new List(); + private readonly IList notMappedProperties = new List(); + private readonly IList compositeUserType = new List(); + private readonly IList validators = new List(); + + private readonly IDictionary extendedProperties = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary propertyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary belongsToDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasManyToAnyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasManyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasAndBelongsToManyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public ActiveRecordModel(Type type) + { + this.type = type; + } + + /// + /// Gets or sets the parent model + /// + /// The parent. + public ActiveRecordModel Parent + { + get { return parent; } + set { parent = value; } + } + + /// + /// Gets the type for this model + /// + /// The type. + public Type Type + { + get { return type; } + } + + /// + /// Gets or sets a value indicating whether this instance is joined sub class base. + /// + /// + /// true if this instance is joined sub class base; otherwise, false. + /// + public bool IsJoinedSubClassBase + { + get { return isJoinedSubClassBase; } + set { isJoinedSubClassBase = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is discriminator base. + /// + /// + /// true if this instance is discriminator base; otherwise, false. + /// + public bool IsDiscriminatorBase + { + get { return isDiscriminatorBase; } + set { isDiscriminatorBase = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is discriminator sub class. + /// + /// + /// true if this instance is discriminator sub class; otherwise, false. + /// + public bool IsDiscriminatorSubClass + { + get { return isDiscriminatorSubClass; } + set { isDiscriminatorSubClass = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is joined sub class. + /// + /// + /// true if this instance is joined sub class; otherwise, false. + /// + public bool IsJoinedSubClass + { + get { return isJoinedSubClass; } + set { isJoinedSubClass = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is nested type. + /// + /// + /// true if this instance is nested type; otherwise, false. + /// + public bool IsNestedType + { + get { return isNestedType; } + set { isNestedType = value; } + } + + /// + /// Gets or sets the parent nested. + /// + /// The parent nested. + public NestedModel ParentNested + { + get { return parentNested; } + set { parentNested = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is nested type. + /// + /// + /// true if this instance is nested type; otherwise, false. + /// + public bool IsNestedCompositeType + { + get { return isNestedCompositeType; } + set { isNestedCompositeType = value; } + } + + /// + /// Gets or sets the active record attribute + /// + /// The active record att. + public ActiveRecordAttribute ActiveRecordAtt + { + get { return arAtt; } + set { arAtt = value; } + } + + /// + /// Used only by joined subclasses + /// + public KeyModel Key + { + get { return key; } + set { key = value; } + } + + /// + /// Gets or sets the timestamp model + /// + /// The timestamp. + public TimestampModel Timestamp + { + get { return timestamp; } + set { timestamp = value; } + } + + /// + /// Gets or sets the version model + /// + /// The version. + public VersionModel Version + { + get { return version; } + set { version = value; } + } + + /// + /// Gets all the imports + /// + /// The imports. + public IList Imports + { + get { return imports; } + } + + /// + /// Gets all the properties + /// + /// The properties. + public IList Properties + { + get { return properties; } + } + + /// + /// Gets all the fields + /// + /// The fields. + public IList Fields + { + get { return fields; } + } + + /// + /// If the object is a component, will return the objects declared parent property. + /// There should only be one, but implemented as a list + /// + public IList ComponentParent + { + get { return componentParent; } + } + + /// + /// Gets the list of [has many to any] models + /// + /// The has many to any. + public IList HasManyToAny + { + get { return hasManyToAny; } + } + + /// + /// Gets the list of [any] model + /// + /// The anys. + public IList Anys + { + get { return anys; } + } + + /// + /// Gets the list of the derived classes + /// + /// The classes. + public IList Classes + { + get { return classes; } + } + + /// + /// Gets the list of derived joined classes. + /// + /// The joined classes. + public IList JoinedClasses + { + get { return joinedclasses; } + } + + /// + /// Gets the list of joined tables. + /// + /// The joined tables. + public IList JoinedTables + { + get { return joinedTables; } + } + + /// + /// Gets the list of components. + /// + /// The components. + public IList Components + { + get { return components; } + } + + /// + /// Gets the list of [belongs to] models + /// + /// The belongs to. + public IList BelongsTo + { + get { return belongsTo; } + } + + /// + /// Gets the list of [has many] models + /// + /// The has many. + public IList HasMany + { + get { return hasMany; } + } + + /// + /// Gets the list of [has and belongs to many] models + /// + /// The has and belongs to many. + public IList HasAndBelongsToMany + { + get { return hasAndBelongsToMany; } + } + + /// + /// Gets the list of [one to one] models + /// + /// The one to ones. + public IList OneToOnes + { + get { return oneToOne; } + } + + /// + /// Gets the list of [collection id] models + /// + /// The collection I ds. + public IList CollectionIDs + { + get { return collectionIds; } + } + + /// + /// For unique Primary keys + /// + public PrimaryKeyModel PrimaryKey + { + get { return primaryKey; } + set { primaryKey = value; } + } + + /// + /// For Composite Primary keys + /// + public CompositeKeyModel CompositeKey + { + get { return compositeKey; } + set { compositeKey = value; } + } + + /// + /// Gets the list of [hilo] models + /// + /// The hilos. + public IList Hilos + { + get { return hilos; } + } + + /// + /// Gets the list of properties not mapped . + /// + /// The not mapped properties. + public IList NotMappedProperties + { + get { return notMappedProperties; } + } + + /// + /// Gets the validators. + /// + /// The validators. + public IList Validators + { + get { return validators; } + } + + /// + /// Gets a value indicating whether to use auto import + /// + /// true if should use auto import; otherwise, false. + public bool UseAutoImport + { + get + { + if (arAtt != null) + { + return arAtt.UseAutoImport; + } + + return true; + } + } + + /// + /// Gets the composite user types properties. + /// + /// The type of the composite user. + public IList CompositeUserType + { + get { return compositeUserType; } + } + + /// + /// Gets the extended properties. Used to store/retrieve information collected by model builder extensions. + /// + /// + /// The extended properties. + public IDictionary ExtendedProperties + { + get { return extendedProperties; } + } + + /// + /// Gets the property dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The property dictionary. + public IDictionary PropertyDictionary + { + get { return propertyDictionary; } + } + + /// + /// Gets the belongs to dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The belongs to dictionary. + public IDictionary BelongsToDictionary + { + get { return belongsToDictionary; } + } + + /// + /// Gets the has many to any dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has many to any dictionary. + public IDictionary HasManyToAnyDictionary + { + get { return hasManyToAnyDictionary; } + } + + /// + /// Gets the has many dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has many dictionary. + public IDictionary HasManyDictionary + { + get { return hasManyDictionary; } + } + + /// + /// Gets the has and belongs to many dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has and belongs to many dictionary. + public IDictionary HasAndBelongsToManyDictionary + { + get { return hasAndBelongsToManyDictionary; } + } + + /// + /// Used internally register an association between a type and its model + /// + /// + /// + internal static void Register(Type arType, ActiveRecordModel model) + { + type2Model[arType] = model; + } + + /// + /// Gets the for a given ActiveRecord class. + /// + public static ActiveRecordModel GetModel(Type arType) + { + arType = GetNonProxy(arType); + return (ActiveRecordModel)type2Model[arType]; + } + + /// + /// Gets an array containing the for every registered ActiveRecord class. + /// + public static ActiveRecordModel[] GetModels() + { + ActiveRecordModel[] modelArray = new ActiveRecordModel[type2Model.Values.Count]; + + type2Model.Values.CopyTo(modelArray, 0); + + return modelArray; + } + + /// + /// Get the base type is the object is lazy + /// + private static Type GetNonProxy(Type type) + { + //Dynamic Proxy 1.0 //Dynamic Proxy 2.0 + if (type.GetField("__interceptor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null + || type.GetField("__interceptors", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null) + { + type = type.BaseType; + } + + return type; + } + + #region IVisitable Members + + /// + /// Accepts the specified visitor and call the relevant IVisitor.Visit***() method + /// + /// The visitor. + public void Accept(IVisitor visitor) + { + visitor.VisitModel(this); + } + + #endregion + } } diff --git a/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs b/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs index 990b5cc..522fe1e 100644 --- a/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs +++ b/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs @@ -37,6 +37,7 @@ public class StatelessSessionWrapper : ISession public StatelessSessionWrapper(IStatelessSession statelessSession) { this.statelessSession = statelessSession; + this.statelessSession.SetBatchSize(1); } #pragma warning disable 1591 @@ -244,6 +245,7 @@ public object Save(string entityName, object obj) /// public void Save(string entityName, object obj, object id) { + statelessSession.Update(entityName, obj); } public object Save(object obj) @@ -267,6 +269,7 @@ public void Update(string entityName, object obj) /// public void Update(string entityName, object obj, object id) { + statelessSession.Update(entityName, obj); } /// @@ -280,6 +283,7 @@ public void Update(string entityName, object obj, object id) /// The name of the entityA transient instance containing new or updated stateIdentifier of persistent instance public void SaveOrUpdate(string entityName, object obj, object id) { + statelessSession.Update(entityName, obj); } public void Update(object obj) @@ -431,7 +435,7 @@ public System.Collections.IList Find(string query) public void Flush() { - throw new NotWrappedException(); + throw new NotWrappedException(); } public FlushMode FlushMode @@ -627,7 +631,7 @@ public ISessionFactory SessionFactory public ISession SetBatchSize(int batchSize) { - throw new NotWrappedException(); + throw new NotWrappedException(); } public NHibernate.Stat.ISessionStatistics Statistics From 35f9c0d544621055c475c68e9d5281fd1a5f6780 Mon Sep 17 00:00:00 2001 From: Vilen Tambovtsev Date: Fri, 15 May 2015 12:46:40 +0300 Subject: [PATCH 6/6] revert to tabs --- .../Model/Company.cs | 2 +- .../ActiveRecordLinqTestCase.cs | 30 +- .../App-net-2.0.config | 10 +- .../App-net-3.5.config | 12 +- src/Castle.ActiveRecord.Tests/App.config | 142 +-- .../DefaultConfigurationsTestCase.cs | 4 +- .../Event/EventListenerAttributeTest.cs | 96 +- .../InvalidRootTypeTestCase.cs | 76 +- src/Castle.ActiveRecord.Tests/LazyTestCase.cs | 186 +-- .../Model/AnyModel/Models.cs | 4 +- src/Castle.ActiveRecord.Tests/Model/Blog.cs | 500 ++++---- .../Model/Company.cs | 14 +- .../Model/CompositeModel/Agent.cs | 27 +- .../Model/CompositeModel/Org.cs | 21 +- .../Model/GenericModel/Person.cs | 8 +- .../Model/LazyModel/ProductLazy.cs | 12 +- src/Castle.ActiveRecord.Tests/Model/Order.cs | 26 +- .../Model/Product.cs | 26 +- .../Model/StrictModel/Estrato.cs | 10 +- .../Model/StrictModel/QuestionContainer.cs | 14 +- .../StatelessSessionScopeTestCase.cs | 698 +++++----- .../TableHierarchyTestCase.cs | 80 +- .../ByteCode/LazyInitializer.cs | 104 +- .../ByteCode/ProxyFactory.cs | 50 +- .../ByteCode/ProxyFactoryFactory.cs | 47 +- .../Framework/ActiveRecordStarter.cs | 118 +- .../Framework/Config/DatabaseType.cs | 134 +- .../Config/DefaultDatabaseConfiguration.cs | 8 +- .../EventListener/EventListenerContributor.cs | 16 +- .../Internal/Model/ActiveRecordModel.cs | 1124 ++++++++--------- .../Visitors/SemanticVerifierVisitor.cs | 232 ++-- .../Framework/Queries/LinqQuery.cs | 96 +- .../Framework/SessionFactoryHolder.cs | 36 +- .../Framework/StatelessSessionWrapper.cs | 230 ++-- .../Framework/SupportingUtils.cs | 38 +- 35 files changed, 2115 insertions(+), 2116 deletions(-) diff --git a/src/Castle.ActiveRecord.Framework.Internal.Tests/Model/Company.cs b/src/Castle.ActiveRecord.Framework.Internal.Tests/Model/Company.cs index 37461f7..9af3eb6 100644 --- a/src/Castle.ActiveRecord.Framework.Internal.Tests/Model/Company.cs +++ b/src/Castle.ActiveRecord.Framework.Internal.Tests/Model/Company.cs @@ -17,7 +17,7 @@ namespace Castle.ActiveRecord.Framework.Internal.Tests.Model /// /// Warning: This is a wrong definition! /// - [ActiveRecord(DiscriminatorColumn="column", DiscriminatorValue="1"), JoinedBase] + [ActiveRecord(DiscriminatorColumn = "column", DiscriminatorValue = "1"), JoinedBase] public class Company : ActiveRecordBase { public Company() diff --git a/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs b/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs index ed65b1e..96fa835 100644 --- a/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/ActiveRecordLinqTestCase.cs @@ -52,10 +52,10 @@ public void SimpleOperations() Assert.AreEqual(0, blogs.Count()); var blog = new Blog - { - Name = "hammett's blog", - Author = "hamilton verissimo" - }; + { + Name = "hammett's blog", + Author = "hamilton verissimo" + }; blog.Save(); blogs = from b in Blog.Queryable select b; @@ -88,10 +88,10 @@ public void SimpleOperationsShowingBug() Assert.AreEqual(0, blogs.Count()); var blog = new Blog - { - Name = "hammett's blog", - Author = "hamilton verissimo" - }; + { + Name = "hammett's blog", + Author = "hamilton verissimo" + }; blog.Save(); blogs = from b in Blog.Queryable select b; @@ -240,7 +240,7 @@ public void UsingLinqViaSessionScopeVariable() Widget widget = new Widget { Name = "Hello world" }; widget.Save(); - widgets = from w in scope.AsQueryable() where w.Name == "Hello world" select w; + widgets = from w in scope.AsQueryable() where w.Name == "Hello world" select w; Assert.IsNotNull(widgets); Assert.AreEqual(1, widgets.Count()); } @@ -268,13 +268,13 @@ public void Projecting() Recreate(); Widget.DeleteAll(); - var widget = new Widget {Name = "foo"}; + var widget = new Widget { Name = "foo" }; widget.Save(); var orderedQueryable = ActiveRecordLinqBase.Queryable; var widgets = (from w in orderedQueryable - where w.Name.StartsWith("f") - select w.Name).ToList(); + where w.Name.StartsWith("f") + select w.Name).ToList(); Assert.IsNotNull(widgets); Assert.AreEqual("foo", widgets.Single()); @@ -290,13 +290,13 @@ public void Projecting2() Recreate(); Widget.DeleteAll(); - var widget = new Widget {Name = "foo"}; + var widget = new Widget { Name = "foo" }; widget.Save(); var orderedQueryable = ActiveRecordLinqBase.Queryable; var name = (from w in orderedQueryable - where w.Name.StartsWith("f") - select w.Name).First(); + where w.Name.StartsWith("f") + select w.Name).First(); Assert.IsNotNull(name); Assert.AreEqual("foo", name); diff --git a/src/Castle.ActiveRecord.Tests/App-net-2.0.config b/src/Castle.ActiveRecord.Tests/App-net-2.0.config index 2a13766..468946b 100644 --- a/src/Castle.ActiveRecord.Tests/App-net-2.0.config +++ b/src/Castle.ActiveRecord.Tests/App-net-2.0.config @@ -10,12 +10,12 @@
- - + - + - + @@ -49,7 +49,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/App-net-3.5.config b/src/Castle.ActiveRecord.Tests/App-net-3.5.config index 0a840ad..ad30acc 100644 --- a/src/Castle.ActiveRecord.Tests/App-net-3.5.config +++ b/src/Castle.ActiveRecord.Tests/App-net-3.5.config @@ -10,12 +10,12 @@
- - + - + - + @@ -49,7 +49,7 @@ - + @@ -59,7 +59,7 @@ - + diff --git a/src/Castle.ActiveRecord.Tests/App.config b/src/Castle.ActiveRecord.Tests/App.config index 939a6b4..ea66eff 100644 --- a/src/Castle.ActiveRecord.Tests/App.config +++ b/src/Castle.ActiveRecord.Tests/App.config @@ -1,85 +1,85 @@  - -
-
- + +
+
+ - + - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + - + - - + + - - - - - + + + + + - - - - + + + + - + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs index c421506..dccf891 100644 --- a/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/DefaultConfigurationsTestCase.cs @@ -80,7 +80,7 @@ public void Throws_when_connectionStringName_not_specified() var value = @" "; - TestDelegate action = () => + TestDelegate action = () => BuildConfiguration(ReadConfiguration(value)); @@ -117,7 +117,7 @@ public void Throws_when_invalid_database_specified() var ex = Assert.Throws(action); Assert.AreEqual( - "Specified value (IDontExist!) is not valid for 'database' attribute. Valid values are: 'MsSqlServer2000' 'MsSqlServer2005' 'MsSqlServer2008' 'MsSqlServer2012' " + + "Specified value (IDontExist!) is not valid for 'database' attribute. Valid values are: 'MsSqlServer2000' 'MsSqlServer2005' 'MsSqlServer2008' 'MsSqlServer2012' " + "'SQLite' 'MySql' 'MySql5' 'Firebird' 'PostgreSQL' 'PostgreSQL81' 'PostgreSQL82' 'MsSqlCe' 'Oracle8i' 'Oracle9i' 'Oracle10g'.", ex.Message); } diff --git a/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs b/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs index 6bf40b0..0034ef5 100644 --- a/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs +++ b/src/Castle.ActiveRecord.Tests/Event/EventListenerAttributeTest.cs @@ -39,7 +39,7 @@ public void C1_ListenerMustBeAddedWhenInitialized() public void C1_Listener_must_be_added_when_initialized_with_assembly() { ActiveRecordStarter.Initialize(Assembly.GetAssembly(typeof(AttributedPreLoadListener)), GetConfigSource()); - AssertListenerWasRegistered(e=>e.PreLoadEventListeners); + AssertListenerWasRegistered(e => e.PreLoadEventListeners); } [Test] @@ -119,7 +119,7 @@ public void U3d_Multiple_events_are_served_by_different_instances_by_default() { InitializeSingleBase(typeof(MultipleListener)); Assert.AreNotSame(Array.Find(GetRegisteredListeners(e => e.PreLoadEventListeners), l => (l is MultipleListener)), - Array.Find(GetRegisteredListeners(e => e.PostLoadEventListeners), l => (l is MultipleListener))); + Array.Find(GetRegisteredListeners(e => e.PostLoadEventListeners), l => (l is MultipleListener))); } [Test] @@ -130,21 +130,21 @@ public void U3d_Multiple_events_are_served_by_the_same_instance_when_singleton_i Array.Find(GetRegisteredListeners(e => e.PostLoadEventListeners), l => (l is MultipleSingletonListener))); } - [Test] - public void Event_listeners_are_registered_only_once() - { - InitializeSingleBase(typeof(SamplePostInsertListener), typeof(SamplePostUpdateListener), typeof(SamplePostDeleteListener)); - Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostInsertEventListeners), l => (l is SamplePostInsertListener)).Length); - Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostUpdateEventListeners), l => (l is SamplePostUpdateListener)).Length); - Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostDeleteEventListeners), l => (l is SamplePostDeleteListener)).Length); - } + [Test] + public void Event_listeners_are_registered_only_once() + { + InitializeSingleBase(typeof(SamplePostInsertListener), typeof(SamplePostUpdateListener), typeof(SamplePostDeleteListener)); + Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostInsertEventListeners), l => (l is SamplePostInsertListener)).Length); + Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostUpdateEventListeners), l => (l is SamplePostUpdateListener)).Length); + Assert.AreEqual(1, Array.FindAll(GetRegisteredListeners(e => e.PostDeleteEventListeners), l => (l is SamplePostDeleteListener)).Length); + } [Test] public void U1_Listeners_are_registered_for_all_configurations() { InitializeMultipleBases(typeof(SamplePreInsertListener)); AssertListenerWasRegistered(e => e.PreInsertEventListeners); - AssertListenerWasRegistered(e=>e.PreInsertEventListeners); + AssertListenerWasRegistered(e => e.PreInsertEventListeners); } [Test] @@ -170,7 +170,7 @@ public void U1_Excluded_Listeners_are_not_registered() [Test] public void U1_C5_U4_No_replacement_on_excluded_configs() { - InitializeMultipleBases(typeof (SecondBaseReplacementLoadListener)); + InitializeMultipleBases(typeof(SecondBaseReplacementLoadListener)); AssertListenerWasNotRegistered(e => e.LoadEventListeners); AssertListenerWasRegistered(e => e.LoadEventListeners); AssertListenerWasRegistered(e => e.LoadEventListeners); @@ -182,81 +182,81 @@ public void U1_C5_U4_No_replacement_on_excluded_configs() [EventListener] private class SamplePreInsertListener : IPreInsertEventListener { - public bool OnPreInsert(PreInsertEvent @event) {return true; } + public bool OnPreInsert(PreInsertEvent @event) { return true; } } - [EventListener] - private class SamplePostInsertListener : IPostInsertEventListener - { - public void OnPostInsert(PostInsertEvent @event) { } - } + [EventListener] + private class SamplePostInsertListener : IPostInsertEventListener + { + public void OnPostInsert(PostInsertEvent @event) { } + } - [EventListener] - private class SamplePostUpdateListener : IPostUpdateEventListener - { - public void OnPostUpdate(PostUpdateEvent @event) { } - } + [EventListener] + private class SamplePostUpdateListener : IPostUpdateEventListener + { + public void OnPostUpdate(PostUpdateEvent @event) { } + } - [EventListener] - private class SamplePostDeleteListener : IPostDeleteEventListener - { - public void OnPostDelete(PostDeleteEvent @event) { } - } + [EventListener] + private class SamplePostDeleteListener : IPostDeleteEventListener + { + public void OnPostDelete(PostDeleteEvent @event) { } + } [EventListener] private class AdditionalLoadListener : ILoadEventListener { - public void OnLoad(LoadEvent @event, LoadType loadType){} + public void OnLoad(LoadEvent @event, LoadType loadType) { } } [EventListener(ReplaceExisting = true)] private class ReplacementLoadListener : ILoadEventListener { - public void OnLoad(LoadEvent @event, LoadType loadType){} + public void OnLoad(LoadEvent @event, LoadType loadType) { } } [EventListener(Ignore = true)] private class IgnoredListener : IPreLoadEventListener { - public void OnPreLoad(PreLoadEvent @event){} + public void OnPreLoad(PreLoadEvent @event) { } } [EventListener(Ignore = true, ReplaceExisting = true)] private class IgnoredReplacementListener : ILoadEventListener { - public void OnLoad(LoadEvent @event, LoadType loadType){} + public void OnLoad(LoadEvent @event, LoadType loadType) { } } [EventListener] private class MultipleListener : IPreLoadEventListener, IPostLoadEventListener { - public void OnPreLoad(PreLoadEvent @event){} - public void OnPostLoad(PostLoadEvent @event){} + public void OnPreLoad(PreLoadEvent @event) { } + public void OnPostLoad(PostLoadEvent @event) { } } - [EventListener(SkipEvent = new[] {typeof (IPreLoadEventListener)})] + [EventListener(SkipEvent = new[] { typeof(IPreLoadEventListener) })] private class MultipleSkippedListener : IPreLoadEventListener, IPostLoadEventListener { - public void OnPreLoad(PreLoadEvent @event){} - public void OnPostLoad(PostLoadEvent @event){} + public void OnPreLoad(PreLoadEvent @event) { } + public void OnPostLoad(PostLoadEvent @event) { } } - [EventListener(SkipEvent = new[] {typeof (ILoadEventListener)})] + [EventListener(SkipEvent = new[] { typeof(ILoadEventListener) })] private class MultipleSkippedReplacementListener : ILoadEventListener, IDeleteEventListener { - public void OnLoad(LoadEvent @event, LoadType loadType){} - public void OnDelete(DeleteEvent @event){} - public void OnDelete(DeleteEvent @event, ISet transientEntities) {} + public void OnLoad(LoadEvent @event, LoadType loadType) { } + public void OnDelete(DeleteEvent @event) { } + public void OnDelete(DeleteEvent @event, ISet transientEntities) { } } [EventListener(Singleton = true)] private class MultipleSingletonListener : IPreLoadEventListener, IPostLoadEventListener { - public void OnPreLoad(PreLoadEvent @event){} - public void OnPostLoad(PostLoadEvent @event){} + public void OnPreLoad(PreLoadEvent @event) { } + public void OnPostLoad(PostLoadEvent @event) { } } - [EventListener(Include=new[]{typeof(ActiveRecordBase)})] + [EventListener(Include = new[] { typeof(ActiveRecordBase) })] private class FirstBaseIncludeListener : IPreLoadEventListener { public void OnPreLoad(PreLoadEvent @event) { } @@ -290,16 +290,16 @@ public void OnLoad(LoadEvent @event, LoadType loadType) { } protected static void InitializeSingleBase(params Type[] listenerTypes) { - InitializeWithListeners(listenerTypes, new[] {typeof (Blog), typeof (Post)}); + InitializeWithListeners(listenerTypes, new[] { typeof(Blog), typeof(Post) }); } private static void InitializeWithListeners(Type[] listenerTypes, Type[] arTypes) { var typesToRegister = new Type[listenerTypes.Length + arTypes.Length]; - Array.ConstrainedCopy(arTypes,0,typesToRegister,0,arTypes.Length); - Array.ConstrainedCopy(listenerTypes,0,typesToRegister,arTypes.Length,listenerTypes.Length); + Array.ConstrainedCopy(arTypes, 0, typesToRegister, 0, arTypes.Length); + Array.ConstrainedCopy(listenerTypes, 0, typesToRegister, arTypes.Length, listenerTypes.Length); - ActiveRecordStarter.Initialize(GetConfigSource(),typesToRegister); + ActiveRecordStarter.Initialize(GetConfigSource(), typesToRegister); } protected static void InitializeMultipleBases(params Type[] listenerTypes) diff --git a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs index 30f7b68..c0167cb 100644 --- a/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/InvalidRootTypeTestCase.cs @@ -14,42 +14,42 @@ namespace Castle.ActiveRecord.Tests { - using System.Collections.Generic; - using Castle.ActiveRecord.Framework; - using Castle.ActiveRecord.Framework.Config; - using NUnit.Framework; - - [TestFixture] - public class InvalidRootTypeTestCase - { - protected IConfigurationSource GetConfigSource() - { - InPlaceConfigurationSource source = new InPlaceConfigurationSource(); - - Dictionary properties = new Dictionary(); - properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); - properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2012Dialect"); - properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); - properties.Add("hibernate.connection.connection_string", - "Data Source=.;Initial Catalog=Test;Integrated Security=true"); - - source.Add(typeof(ActiveRecordBase), properties); - source.Add(typeof(NonAbstractRootType), properties); - - return source; - } - - [Test, ExpectedException(typeof(ActiveRecordException))] - public void RootTypeIsNotAbstract() - { - ActiveRecordStarter.ResetInitializationFlag(); - - ActiveRecordStarter.Initialize(GetConfigSource(), - typeof(NonAbstractRootType)); - } - - public class NonAbstractRootType : ActiveRecordBase - { - } - } + using System.Collections.Generic; + using Castle.ActiveRecord.Framework; + using Castle.ActiveRecord.Framework.Config; + using NUnit.Framework; + + [TestFixture] + public class InvalidRootTypeTestCase + { + protected IConfigurationSource GetConfigSource() + { + InPlaceConfigurationSource source = new InPlaceConfigurationSource(); + + Dictionary properties = new Dictionary(); + properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); + properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2012Dialect"); + properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); + properties.Add("hibernate.connection.connection_string", + "Data Source=.;Initial Catalog=Test;Integrated Security=true"); + + source.Add(typeof(ActiveRecordBase), properties); + source.Add(typeof(NonAbstractRootType), properties); + + return source; + } + + [Test, ExpectedException(typeof(ActiveRecordException))] + public void RootTypeIsNotAbstract() + { + ActiveRecordStarter.ResetInitializationFlag(); + + ActiveRecordStarter.Initialize(GetConfigSource(), + typeof(NonAbstractRootType)); + } + + public class NonAbstractRootType : ActiveRecordBase + { + } + } } diff --git a/src/Castle.ActiveRecord.Tests/LazyTestCase.cs b/src/Castle.ActiveRecord.Tests/LazyTestCase.cs index b010312..b84dabb 100644 --- a/src/Castle.ActiveRecord.Tests/LazyTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/LazyTestCase.cs @@ -14,97 +14,97 @@ namespace Castle.ActiveRecord.Tests { - using NUnit.Framework; - - using Castle.ActiveRecord.Tests.Model; - - [TestFixture] - public class LazyTestCase : AbstractActiveRecordTest - { - [Test] - public void CanSaveAndLoadLazyEntityOutsideOfScope() - { - ActiveRecordStarter.Initialize(GetConfigSource(), - typeof(BlogLazy), typeof(PostLazy)); - Recreate(); - BlogLazy blog = new BlogLazy(); - blog.Save(); - PostLazy post = new PostLazy(blog, "a", "b", "c"); - post.Save(); - - PostLazy postFromDb = PostLazy.Find(post.Id); - Assert.AreEqual("a", postFromDb.Title); - } - - [Test] - public void CanSaveAndLoadLazy() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(VeryLazyObject)); - Recreate(); - VeryLazyObject lazy = new VeryLazyObject(); - lazy.Title = "test"; - - ActiveRecordMediator.Save(lazy); - - VeryLazyObject lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); - Assert.AreEqual("test", lazyFromDb.Title); - - lazyFromDb.Title = "test for update"; - ActiveRecordMediator.Update(lazyFromDb); - - lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); - Assert.AreEqual("test for update", lazyFromDb.Title); - } - - [Test] - public void CanLoadLazyProperty() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(LazyObjectWithLazyBlobProperty)); - Recreate(); - - string teststring = @"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg=="; - int id; - - using (new SessionScope()) - { - LazyObjectWithLazyBlobProperty lazy = new LazyObjectWithLazyBlobProperty(); - - lazy.BlobData = System.Text.Encoding.UTF8.GetBytes(teststring); - ActiveRecordMediator.Save(lazy); - id = lazy.Id; - } - - using (new SessionScope()) - { - LazyObjectWithLazyBlobProperty lazyFromDb = (LazyObjectWithLazyBlobProperty)ActiveRecordMediator.FindByPrimaryKey(typeof(LazyObjectWithLazyBlobProperty), id); - Assert.True(!NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); - - byte[] fromDb = lazyFromDb.BlobData; - Assert.True(NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); - - Assert.AreEqual(teststring, System.Text.Encoding.UTF8.GetString(fromDb)); - } - } - - [Test] - public void CanLoadLazyBelongsToOutsideOfScope() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(ScopelessLazy), typeof(ObjectWithLazyAssociation), typeof(VeryLazyObject2)); - - Recreate(); - - var lazy = new VeryLazyObject2(); - lazy.Title = "test"; - ActiveRecordMediator.Save(lazy); - - var obj = new ObjectWithLazyAssociation(); - obj.LazyObj = lazy; - ActiveRecordMediator.Save(obj); - - var objFromDb = (ObjectWithLazyAssociation)ActiveRecordMediator.FindByPrimaryKey(typeof(ObjectWithLazyAssociation), obj.Id); - Assert.False(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); - Assert.AreEqual("test", objFromDb.LazyObj.Title); - Assert.True(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); - } - } + using NUnit.Framework; + + using Castle.ActiveRecord.Tests.Model; + + [TestFixture] + public class LazyTestCase : AbstractActiveRecordTest + { + [Test] + public void CanSaveAndLoadLazyEntityOutsideOfScope() + { + ActiveRecordStarter.Initialize(GetConfigSource(), + typeof(BlogLazy), typeof(PostLazy)); + Recreate(); + BlogLazy blog = new BlogLazy(); + blog.Save(); + PostLazy post = new PostLazy(blog, "a", "b", "c"); + post.Save(); + + PostLazy postFromDb = PostLazy.Find(post.Id); + Assert.AreEqual("a", postFromDb.Title); + } + + [Test] + public void CanSaveAndLoadLazy() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(VeryLazyObject)); + Recreate(); + VeryLazyObject lazy = new VeryLazyObject(); + lazy.Title = "test"; + + ActiveRecordMediator.Save(lazy); + + VeryLazyObject lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); + Assert.AreEqual("test", lazyFromDb.Title); + + lazyFromDb.Title = "test for update"; + ActiveRecordMediator.Update(lazyFromDb); + + lazyFromDb = (VeryLazyObject)ActiveRecordMediator.FindByPrimaryKey(typeof(VeryLazyObject), lazy.Id); + Assert.AreEqual("test for update", lazyFromDb.Title); + } + + [Test] + public void CanLoadLazyProperty() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(LazyObjectWithLazyBlobProperty)); + Recreate(); + + string teststring = @"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg=="; + int id; + + using (new SessionScope()) + { + LazyObjectWithLazyBlobProperty lazy = new LazyObjectWithLazyBlobProperty(); + + lazy.BlobData = System.Text.Encoding.UTF8.GetBytes(teststring); + ActiveRecordMediator.Save(lazy); + id = lazy.Id; + } + + using (new SessionScope()) + { + LazyObjectWithLazyBlobProperty lazyFromDb = (LazyObjectWithLazyBlobProperty)ActiveRecordMediator.FindByPrimaryKey(typeof(LazyObjectWithLazyBlobProperty), id); + Assert.True(!NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); + + byte[] fromDb = lazyFromDb.BlobData; + Assert.True(NHibernate.NHibernateUtil.IsPropertyInitialized(lazyFromDb, "BlobData")); + + Assert.AreEqual(teststring, System.Text.Encoding.UTF8.GetString(fromDb)); + } + } + + [Test] + public void CanLoadLazyBelongsToOutsideOfScope() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(ScopelessLazy), typeof(ObjectWithLazyAssociation), typeof(VeryLazyObject2)); + + Recreate(); + + var lazy = new VeryLazyObject2(); + lazy.Title = "test"; + ActiveRecordMediator.Save(lazy); + + var obj = new ObjectWithLazyAssociation(); + obj.LazyObj = lazy; + ActiveRecordMediator.Save(obj); + + var objFromDb = (ObjectWithLazyAssociation)ActiveRecordMediator.FindByPrimaryKey(typeof(ObjectWithLazyAssociation), obj.Id); + Assert.False(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); + Assert.AreEqual("test", objFromDb.LazyObj.Title); + Assert.True(NHibernate.NHibernateUtil.IsInitialized(objFromDb.LazyObj)); + } + } } diff --git a/src/Castle.ActiveRecord.Tests/Model/AnyModel/Models.cs b/src/Castle.ActiveRecord.Tests/Model/AnyModel/Models.cs index f346203..6c5f096 100644 --- a/src/Castle.ActiveRecord.Tests/Model/AnyModel/Models.cs +++ b/src/Castle.ActiveRecord.Tests/Model/AnyModel/Models.cs @@ -16,7 +16,7 @@ namespace Castle.ActiveRecord.Tests.Model.AnyModel { using System; using System.Collections; - + [ActiveRecord("Orders")] public class Order : ActiveRecordBase { @@ -129,7 +129,7 @@ public interface IPayment public class ModelWithInCorrectMapping : ActiveRecordBase { private string payment; - + [Any.MetaValue("CREDIT_CARD", typeof(CreditCards))] [Any.MetaValue("BANK_ACCOUNT", typeof(BankAccounts))] public string Payment diff --git a/src/Castle.ActiveRecord.Tests/Model/Blog.cs b/src/Castle.ActiveRecord.Tests/Model/Blog.cs index bcf5a94..224b119 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Blog.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Blog.cs @@ -14,254 +14,254 @@ namespace Castle.ActiveRecord.Tests.Model { - using System; - using System.Collections; - using System.Collections.Generic; - - using Castle.ActiveRecord.Framework; - using NHibernate; - using NHibernate.Criterion; - - [ActiveRecord("BlogTable")] - public class Blog : ActiveRecordBase - { - private int _id; - private String _name; - private String _author; - private IList _posts; - private IList _publishedposts; - private IList _unpublishedposts; - private IList _recentposts; - private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; - - public Blog() - { - } - - public Blog(int _id) - { - this._id = _id; - } - - [PrimaryKey(PrimaryKeyType.Native)] - public int Id - { - get { return _id; } - set { _id = value; } - } - - [Property] - public String Name - { - get { return _name; } - set { _name = value; } - } - - [Property] - public String Author - { - get { return _author; } - set { _author = value; } - } - - [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid")] - public IList Posts - { - get { return _posts; } - set { _posts = value; } - } - - [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 1")] - public IList PublishedPosts - { - get { return _publishedposts; } - set { _publishedposts = value; } - } - - [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 0")] - public IList UnPublishedPosts - { - get { return _unpublishedposts; } - set { _unpublishedposts = value; } - } - - [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", OrderBy = "created desc")] - public IList RecentPosts - { - get { return _recentposts; } - set { _recentposts = value; } - } - - [Property(Formula = "1 + 1")] - public int SomeFormula { get; set; } - - public static void DeleteAll() - { - ActiveRecordMediator.DeleteAll(typeof(Blog)); - } - - public static void DeleteAll(string where) - { - ActiveRecordMediator.DeleteAll(typeof(Blog), where); - } - - public static Blog[] FindAll() - { - return (Blog[])ActiveRecordMediator.FindAll(typeof(Blog)); - } - - public static Blog[] FindAll(IDetachedQuery dq) - { - return (Blog[])FindAll(typeof(Blog), dq); - } - - public static Blog Find(int id) - { - return (Blog)ActiveRecordMediator.FindByPrimaryKey(typeof(Blog), id); - } - - public static Blog FindOne(IDetachedQuery dq) - { - return (Blog)FindOne(typeof(Blog), dq); - } - - public static int FetchCount() - { - return Count(typeof(Blog)); - } - - public static int FetchCount(string filter, params object[] args) - { - return Count(typeof(Blog), filter, args); - } - - public static int FetchCount(params ICriterion[] criterias) - { - return Count(typeof(Blog), criterias); - } - - public static bool Exists() - { - return Exists(typeof(Blog)); - } - - public static bool Exists(string filter, params object[] args) - { - return Exists(typeof(Blog), filter, args); - } - - public static bool Exists(int id) - { - return Exists(typeof(Blog), id); - } - - public static bool Exists(params ICriterion[] criteria) - { - return Exists(typeof(Blog), criteria); - } - - public static bool Exists(IDetachedQuery dq) - { - return Exists(typeof(Blog), dq); - } - - public static Blog[] SlicedFindAll(int FirstResult, int MaxResult, IDetachedQuery dq) - { - return (Blog[])SlicedFindAll(typeof(Blog), FirstResult, MaxResult, dq); - } - - public static Blog[] FindByProperty(String property, object value) - { - return (Blog[])FindAllByProperty(typeof(Blog), property, value); - } - - public static Blog[] FindByProperty(String property, String orderByColumn, object value) - { - return (Blog[])FindAllByProperty(typeof(Blog), orderByColumn, property, value); - } - - /// - /// Lifecycle method invoked during Save of the entity - /// - protected override void OnSave() - { - onSaveCalled = true; - } - - /// - /// Lifecycle method invoked during Update of the entity - /// - protected override void OnUpdate() - { - onUpdateCalled = true; - } - - /// - /// Lifecycle method invoked during Delete of the entity - /// - protected override void OnDelete() - { - onDeleteCalled = true; - } - - /// - /// Lifecycle method invoked during Load of the entity - /// - protected override void OnLoad(object id) - { - onLoadCalled = true; - } - - public bool OnSaveCalled - { - get { return onSaveCalled; } - } - - public bool OnUpdateCalled - { - get { return onUpdateCalled; } - } - - public bool OnDeleteCalled - { - get { return onDeleteCalled; } - } - - public bool OnLoadCalled - { - get { return onLoadCalled; } - } - - public ISession CurrentSession - { - get - { - return (ISession) - ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(GrabSession), this); - } - } - - private static object GrabSession(ISession session, object instance) - { - return session; - } - - public void CustomAction() - { - ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(MyCustomMethod), this); - } - - private static object MyCustomMethod(ISession session, object blogInstance) - { - session.Delete(blogInstance); - session.Flush(); - - return null; - } - - internal static ISessionFactoryHolder Holder - { - get { return ActiveRecordMediator.GetSessionFactoryHolder(); } - } - } + using System; + using System.Collections; + using System.Collections.Generic; + + using Castle.ActiveRecord.Framework; + using NHibernate; + using NHibernate.Criterion; + + [ActiveRecord("BlogTable")] + public class Blog : ActiveRecordBase + { + private int _id; + private String _name; + private String _author; + private IList _posts; + private IList _publishedposts; + private IList _unpublishedposts; + private IList _recentposts; + private bool onSaveCalled, onUpdateCalled, onDeleteCalled, onLoadCalled; + + public Blog() + { + } + + public Blog(int _id) + { + this._id = _id; + } + + [PrimaryKey(PrimaryKeyType.Native)] + public int Id + { + get { return _id; } + set { _id = value; } + } + + [Property] + public String Name + { + get { return _name; } + set { _name = value; } + } + + [Property] + public String Author + { + get { return _author; } + set { _author = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid")] + public IList Posts + { + get { return _posts; } + set { _posts = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 1")] + public IList PublishedPosts + { + get { return _publishedposts; } + set { _publishedposts = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", Where = "published = 0")] + public IList UnPublishedPosts + { + get { return _unpublishedposts; } + set { _unpublishedposts = value; } + } + + [HasMany(typeof(Post), Table = "Posts", ColumnKey = "blogid", OrderBy = "created desc")] + public IList RecentPosts + { + get { return _recentposts; } + set { _recentposts = value; } + } + + [Property(Formula = "1 + 1")] + public int SomeFormula { get; set; } + + public static void DeleteAll() + { + ActiveRecordMediator.DeleteAll(typeof(Blog)); + } + + public static void DeleteAll(string where) + { + ActiveRecordMediator.DeleteAll(typeof(Blog), where); + } + + public static Blog[] FindAll() + { + return (Blog[])ActiveRecordMediator.FindAll(typeof(Blog)); + } + + public static Blog[] FindAll(IDetachedQuery dq) + { + return (Blog[])FindAll(typeof(Blog), dq); + } + + public static Blog Find(int id) + { + return (Blog)ActiveRecordMediator.FindByPrimaryKey(typeof(Blog), id); + } + + public static Blog FindOne(IDetachedQuery dq) + { + return (Blog)FindOne(typeof(Blog), dq); + } + + public static int FetchCount() + { + return Count(typeof(Blog)); + } + + public static int FetchCount(string filter, params object[] args) + { + return Count(typeof(Blog), filter, args); + } + + public static int FetchCount(params ICriterion[] criterias) + { + return Count(typeof(Blog), criterias); + } + + public static bool Exists() + { + return Exists(typeof(Blog)); + } + + public static bool Exists(string filter, params object[] args) + { + return Exists(typeof(Blog), filter, args); + } + + public static bool Exists(int id) + { + return Exists(typeof(Blog), id); + } + + public static bool Exists(params ICriterion[] criteria) + { + return Exists(typeof(Blog), criteria); + } + + public static bool Exists(IDetachedQuery dq) + { + return Exists(typeof(Blog), dq); + } + + public static Blog[] SlicedFindAll(int FirstResult, int MaxResult, IDetachedQuery dq) + { + return (Blog[])SlicedFindAll(typeof(Blog), FirstResult, MaxResult, dq); + } + + public static Blog[] FindByProperty(String property, object value) + { + return (Blog[])FindAllByProperty(typeof(Blog), property, value); + } + + public static Blog[] FindByProperty(String property, String orderByColumn, object value) + { + return (Blog[])FindAllByProperty(typeof(Blog), orderByColumn, property, value); + } + + /// + /// Lifecycle method invoked during Save of the entity + /// + protected override void OnSave() + { + onSaveCalled = true; + } + + /// + /// Lifecycle method invoked during Update of the entity + /// + protected override void OnUpdate() + { + onUpdateCalled = true; + } + + /// + /// Lifecycle method invoked during Delete of the entity + /// + protected override void OnDelete() + { + onDeleteCalled = true; + } + + /// + /// Lifecycle method invoked during Load of the entity + /// + protected override void OnLoad(object id) + { + onLoadCalled = true; + } + + public bool OnSaveCalled + { + get { return onSaveCalled; } + } + + public bool OnUpdateCalled + { + get { return onUpdateCalled; } + } + + public bool OnDeleteCalled + { + get { return onDeleteCalled; } + } + + public bool OnLoadCalled + { + get { return onLoadCalled; } + } + + public ISession CurrentSession + { + get + { + return (ISession) + ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(GrabSession), this); + } + } + + private static object GrabSession(ISession session, object instance) + { + return session; + } + + public void CustomAction() + { + ActiveRecordMediator.Execute(typeof(Blog), new NHibernateDelegate(MyCustomMethod), this); + } + + private static object MyCustomMethod(ISession session, object blogInstance) + { + session.Delete(blogInstance); + session.Flush(); + + return null; + } + + internal static ISessionFactoryHolder Holder + { + get { return ActiveRecordMediator.GetSessionFactoryHolder(); } + } + } } diff --git a/src/Castle.ActiveRecord.Tests/Model/Company.cs b/src/Castle.ActiveRecord.Tests/Model/Company.cs index 590e5c4..9c9a1af 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Company.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Company.cs @@ -18,7 +18,7 @@ namespace Castle.ActiveRecord.Tests.Model using System.Collections; - [ActiveRecord("Companies", DiscriminatorColumn="type", DiscriminatorType="String", DiscriminatorValue="company")] + [ActiveRecord("Companies", DiscriminatorColumn = "type", DiscriminatorType = "String", DiscriminatorValue = "company")] public class Company : ActiveRecordBase { private int id; @@ -56,8 +56,8 @@ public PostalAddress Address set { _address = value; } } - [HasAndBelongsToMany( typeof(Person), RelationType.Bag, - Table="PeopleCompanies", ColumnRef="person_id", ColumnKey="company_id" )] + [HasAndBelongsToMany(typeof(Person), RelationType.Bag, + Table = "PeopleCompanies", ColumnRef = "person_id", ColumnKey = "company_id")] public IList People { get { return _people; } @@ -66,17 +66,17 @@ public IList People public static void DeleteAll() { - ActiveRecordBase.DeleteAll( typeof(Company) ); + ActiveRecordBase.DeleteAll(typeof(Company)); } public static Company[] FindAll() { - return (Company[]) ActiveRecordBase.FindAll( typeof(Company) ); + return (Company[])ActiveRecordBase.FindAll(typeof(Company)); } public static Company Find(int id) { - return (Company) ActiveRecordBase.FindByPrimaryKey( typeof(Company), id ); + return (Company)ActiveRecordBase.FindByPrimaryKey(typeof(Company), id); } } @@ -111,7 +111,7 @@ public String Address public String City { get { return _city; } - set { _city = value;} + set { _city = value; } } [Property] diff --git a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs index dc417e3..15c9482 100644 --- a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs +++ b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Agent.cs @@ -28,7 +28,7 @@ public class Agent : ActiveRecordBase { private AgentKey _userKey; private Org _org; - private IList _groups; + private IList _groups; private int _version; public Agent() @@ -37,7 +37,8 @@ public Agent() _version = -1; } - public Agent(AgentKey key) : this() + public Agent(AgentKey key) + : this() { _userKey = key; } @@ -59,27 +60,27 @@ public String Name get { return _userKey.Name; } } - [Version(UnsavedValue="negative")] + [Version(UnsavedValue = "negative")] public int Version { - get{ return _version; } - set{ _version = value; } + get { return _version; } + set { _version = value; } } - [BelongsTo("OrgId", Insert=false, Update=false)] + [BelongsTo("OrgId", Insert = false, Update = false)] public Org Org { get { return _org; } set { _org = value; } } - [HasAndBelongsToMany(typeof (Group), + [HasAndBelongsToMany(typeof(Group), Table = "GroupAgents", ColumnRef = "GroupId", - CompositeKeyColumnKeys = new String[]{"OrgId","Name"}, + CompositeKeyColumnKeys = new String[] { "OrgId", "Name" }, Lazy = true, Cascade = ManyRelationCascadeEnum.SaveUpdate)] - public IList Groups + public IList Groups { get { return _groups; } set { _groups = value; } @@ -87,17 +88,17 @@ public IList Groups public static void DeleteAll() { - ActiveRecordBase.DeleteAll( typeof(Agent) ); + ActiveRecordBase.DeleteAll(typeof(Agent)); } public static Agent[] FindAll() { - return (Agent[]) ActiveRecordBase.FindAll( typeof(Agent) ); + return (Agent[])ActiveRecordBase.FindAll(typeof(Agent)); } public static Agent Find(object key) { - return (Agent) ActiveRecordBase.FindByPrimaryKey( typeof(Agent), key ); + return (Agent)ActiveRecordBase.FindByPrimaryKey(typeof(Agent), key); } /// @@ -117,7 +118,7 @@ private object MyCustomMethod(ISession session, object userInstance) { session.Delete(userInstance); session.Flush(); - + return null; } } diff --git a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs index 98acbf8..22894f2 100644 --- a/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs +++ b/src/Castle.ActiveRecord.Tests/Model/CompositeModel/Org.cs @@ -18,13 +18,13 @@ namespace Castle.ActiveRecord.Tests.Model.CompositeModel using System.Collections; using System.Collections.Generic; - [ActiveRecord("Orgs")] + [ActiveRecord("Orgs")] public class Org : ActiveRecordBase { private string _id; private String _description; private DateTime _created; - private IList _agents; + private IList _agents; private int _version; public Org() @@ -34,7 +34,8 @@ public Org() _version = -1; } - public Org(string id, String description) : this() + public Org(string id, String description) + : this() { _id = id; _description = description; @@ -47,14 +48,14 @@ public string Id set { _id = value; } } - [Version(UnsavedValue="negative")] + [Version(UnsavedValue = "negative")] public int Version { get { return _version; } set { _version = value; } } - [Property(ColumnType="StringClob")] + [Property(ColumnType = "StringClob")] public String Contents { get { return _description; } @@ -62,9 +63,9 @@ public String Contents } [HasMany(typeof(Agent), - Inverse=true, - Lazy=true)] - public IList Agents + Inverse = true, + Lazy = true)] + public IList Agents { get { return _agents; } set { _agents = value; } @@ -90,12 +91,12 @@ public static void DeleteAll() public static Org[] FindAll() { - return (Org[]) FindAll(typeof(Org)); + return (Org[])FindAll(typeof(Org)); } public static Org Find(string id) { - return (Org) FindByPrimaryKey(typeof(Org), id); + return (Org)FindByPrimaryKey(typeof(Org), id); } public static int FetchCount() diff --git a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs index d6720b0..f674531 100644 --- a/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs +++ b/src/Castle.ActiveRecord.Tests/Model/GenericModel/Person.cs @@ -18,12 +18,12 @@ namespace Castle.ActiveRecord.Tests.Model.GenericModel using System.Collections; using System.Collections.Generic; - [ActiveRecord("People")] + [ActiveRecord("People")] public class Person : ActiveRecordBase { private int _id; private String _name; - private IList _companies; + private IList _companies; public Person() { @@ -44,8 +44,8 @@ public string Name set { _name = value; } } - [HasAndBelongsToMany( typeof(Company), RelationType.Bag, Table="PeopleCompanies", ColumnRef="company_id", ColumnKey="person_id" )] - public IList Companies + [HasAndBelongsToMany(typeof(Company), RelationType.Bag, Table = "PeopleCompanies", ColumnRef = "company_id", ColumnKey = "person_id")] + public IList Companies { get { return _companies; } set { _companies = value; } diff --git a/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs b/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs index 7d17afe..fca7b63 100644 --- a/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs +++ b/src/Castle.ActiveRecord.Tests/Model/LazyModel/ProductLazy.cs @@ -24,7 +24,7 @@ namespace Castle.ActiveRecord.Tests.Model.LazyModel public class ProductLazy : ActiveRecordValidationBase { private int id; - private ISet categories = new HashSet(); + private ISet categories = new HashSet(); public ProductLazy() { @@ -37,8 +37,8 @@ public int Id set { id = value; } } - [HasMany( typeof(CategoryLazy), Lazy=true, Cascade=ManyRelationCascadeEnum.All )] - public ISet Categories + [HasMany(typeof(CategoryLazy), Lazy = true, Cascade = ManyRelationCascadeEnum.All)] + public ISet Categories { get { return categories; } set { categories = value; } @@ -46,17 +46,17 @@ public ISet Categories public static void DeleteAll() { - ActiveRecordBase.DeleteAll( typeof(ProductLazy) ); + ActiveRecordBase.DeleteAll(typeof(ProductLazy)); } public static ProductLazy[] FindAll() { - return (ProductLazy[]) ActiveRecordBase.FindAll( typeof(ProductLazy) ); + return (ProductLazy[])ActiveRecordBase.FindAll(typeof(ProductLazy)); } public static ProductLazy Find(int id) { - return (ProductLazy) ActiveRecordBase.FindByPrimaryKey( typeof(ProductLazy), id ); + return (ProductLazy)ActiveRecordBase.FindByPrimaryKey(typeof(ProductLazy), id); } } diff --git a/src/Castle.ActiveRecord.Tests/Model/Order.cs b/src/Castle.ActiveRecord.Tests/Model/Order.cs index 32f03c7..8d97d23 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Order.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Order.cs @@ -52,13 +52,13 @@ public Boolean IsShipped public static Order Find(int id) { - return ((Order) (ActiveRecordBase.FindByPrimaryKey(typeof (Order), id))); + return ((Order)(ActiveRecordBase.FindByPrimaryKey(typeof(Order), id))); } - [HasAndBelongsToMany(typeof (Product), RelationType.Set, - Table="line_item", - ColumnRef="product_id", ColumnKey="order_id")] - public ISet Products + [HasAndBelongsToMany(typeof(Product), RelationType.Set, + Table = "line_item", + ColumnRef = "product_id", ColumnKey = "order_id")] + public ISet Products { get { return _products; } set { _products = value; } @@ -66,7 +66,7 @@ public ISet Products public static void DeleteAll() { - ActiveRecordBase.DeleteAll(typeof (Order)); + ActiveRecordBase.DeleteAll(typeof(Order)); } } @@ -101,15 +101,15 @@ public Boolean IsShipped public static OrderWithIDBag Find(int id) { - return ((OrderWithIDBag) (ActiveRecordBase.FindByPrimaryKey(typeof (OrderWithIDBag), id))); + return ((OrderWithIDBag)(ActiveRecordBase.FindByPrimaryKey(typeof(OrderWithIDBag), id))); } - [HasAndBelongsToMany(typeof (ProductWithIDBag), RelationType.IdBag, - Table="line_item_non_ident", - ColumnRef="product_id", ColumnKey="order_id"), + [HasAndBelongsToMany(typeof(ProductWithIDBag), RelationType.IdBag, + Table = "line_item_non_ident", + ColumnRef = "product_id", ColumnKey = "order_id"), CollectionID(CollectionIDType.HiLo, "line_number", "Int32"), - Hilo(Table="testing_hilo", Column="sequence", MaxLo=150)] - public IList Products + Hilo(Table = "testing_hilo", Column = "sequence", MaxLo = 150)] + public IList Products { get { return _products; } set { _products = value; } @@ -117,7 +117,7 @@ public IList Products public static void DeleteAll() { - ActiveRecordBase.DeleteAll(typeof (OrderWithIDBag)); + ActiveRecordBase.DeleteAll(typeof(OrderWithIDBag)); } } } diff --git a/src/Castle.ActiveRecord.Tests/Model/Product.cs b/src/Castle.ActiveRecord.Tests/Model/Product.cs index 39cc65d..00f872f 100644 --- a/src/Castle.ActiveRecord.Tests/Model/Product.cs +++ b/src/Castle.ActiveRecord.Tests/Model/Product.cs @@ -1,4 +1,4 @@ - // Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ public class Product : ActiveRecordBase private string product_name; private float price; private string serial_number; - private ISet _orders; + private ISet _orders; [PrimaryKey(PrimaryKeyType.Native, "ProductID")] public int ID @@ -56,9 +56,9 @@ public float Price set { this.price = value; } } - [HasAndBelongsToMany(typeof (Order), RelationType.Set, - Table="line_item", - ColumnRef="order_id", ColumnKey="product_id", Inverse=true)] + [HasAndBelongsToMany(typeof(Order), RelationType.Set, + Table = "line_item", + ColumnRef = "order_id", ColumnKey = "product_id", Inverse = true)] public ISet Orders { get { return _orders; } @@ -67,12 +67,12 @@ public ISet Orders public static Product Find(int id) { - return ((Product) (ActiveRecordBase.FindByPrimaryKey(typeof (Product), id))); + return ((Product)(ActiveRecordBase.FindByPrimaryKey(typeof(Product), id))); } public static void DeleteAll() { - ActiveRecordBase.DeleteAll(typeof (Product)); + ActiveRecordBase.DeleteAll(typeof(Product)); } } @@ -113,11 +113,11 @@ public float Price set { this.price = value; } } - [HasAndBelongsToMany(typeof (OrderWithIDBag), RelationType.IdBag, - Table="line_item_non_ident", - ColumnRef="order_id", ColumnKey="product_id"), + [HasAndBelongsToMany(typeof(OrderWithIDBag), RelationType.IdBag, + Table = "line_item_non_ident", + ColumnRef = "order_id", ColumnKey = "product_id"), CollectionID(CollectionIDType.HiLo, "line_number", "Int32"), - Hilo(Table="testing_hilo", Column="sequence", MaxLo=150)] + Hilo(Table = "testing_hilo", Column = "sequence", MaxLo = 150)] public IList Orders { get { return _orders; } @@ -126,12 +126,12 @@ public IList Orders public static ProductWithIDBag Find(int id) { - return ((ProductWithIDBag) (ActiveRecordBase.FindByPrimaryKey(typeof (ProductWithIDBag), id))); + return ((ProductWithIDBag)(ActiveRecordBase.FindByPrimaryKey(typeof(ProductWithIDBag), id))); } public static void DeleteAll() { - ActiveRecordBase.DeleteAll(typeof (ProductWithIDBag)); + ActiveRecordBase.DeleteAll(typeof(ProductWithIDBag)); } } } diff --git a/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs b/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs index 5031fe3..8dec3d3 100644 --- a/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs +++ b/src/Castle.ActiveRecord.Tests/Model/StrictModel/Estrato.cs @@ -26,7 +26,7 @@ public enum EstratoType Survey } - [ActiveRecord(DiscriminatorColumn="type", DiscriminatorType="Int16", DiscriminatorValue="0")] + [ActiveRecord(DiscriminatorColumn = "type", DiscriminatorType = "Int16", DiscriminatorValue = "0")] public class Estrato : ActiveRecordValidationBase { private int id; @@ -47,7 +47,7 @@ public int Id set { id = value; } } - [Property("type", Insert=false, Update=false)] + [Property("type", Insert = false, Update = false)] public EstratoType EstratoType { get { return type; } @@ -61,21 +61,21 @@ public QuestionContainer Container set { container = value; } } - [HasAndBelongsToMany( typeof(Estrato), Table="EstratoRefEstrato", ColumnRef="ref_estrato_id", ColumnKey="estrato_id" )] + [HasAndBelongsToMany(typeof(Estrato), Table = "EstratoRefEstrato", ColumnRef = "ref_estrato_id", ColumnKey = "estrato_id")] public ISet ReferencedEstratos { get { return references; } set { references = value; } } - [BelongsTo("parent_id", Type=typeof(Estrato))] + [BelongsTo("parent_id", Type = typeof(Estrato))] public Estrato ParentEstrato { get { return parentEstrato; } set { parentEstrato = value; } } - [HasMany( typeof(Estrato), Inverse=true, Cascade=ManyRelationCascadeEnum.All)] + [HasMany(typeof(Estrato), Inverse = true, Cascade = ManyRelationCascadeEnum.All)] public ISet SubEstratos { get { return subestratos; } diff --git a/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs b/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs index 19154d6..155e7da 100644 --- a/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs +++ b/src/Castle.ActiveRecord.Tests/Model/StrictModel/QuestionContainer.cs @@ -26,12 +26,12 @@ public enum ContainerType Survey } - [ActiveRecord(DiscriminatorColumn="type", DiscriminatorType="Int16", DiscriminatorValue="0")] + [ActiveRecord(DiscriminatorColumn = "type", DiscriminatorType = "Int16", DiscriminatorValue = "0")] public class QuestionContainer : ActiveRecordValidationBase { private int id; private ContainerType type; - private ISet estratos = new HashSet(); + private ISet estratos = new HashSet(); public QuestionContainer() { @@ -44,15 +44,15 @@ public int Id set { id = value; } } - [Property("type", Insert=false, Update=false)] + [Property("type", Insert = false, Update = false)] public ContainerType Type { get { return type; } set { type = value; } } - [HasMany( typeof(Estrato), Inverse=true)] - public ISet Estratos + [HasMany(typeof(Estrato), Inverse = true)] + public ISet Estratos { get { return estratos; } set { estratos = value; } @@ -60,12 +60,12 @@ public ISet Estratos public static void DeleteAll() { - ActiveRecordBase.DeleteAll( typeof(QuestionContainer) ); + ActiveRecordBase.DeleteAll(typeof(QuestionContainer)); } public static QuestionContainer Find(int id) { - return (QuestionContainer) ActiveRecordBase.FindByPrimaryKey( typeof(QuestionContainer), id ); + return (QuestionContainer)ActiveRecordBase.FindByPrimaryKey(typeof(QuestionContainer), id); } public override bool Equals(object obj) diff --git a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs index 84eac0d..de30c8f 100644 --- a/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/StatelessSessionScopeTestCase.cs @@ -14,355 +14,355 @@ namespace Castle.ActiveRecord.Tests { - using System; - using Castle.ActiveRecord; - using Castle.ActiveRecord.Framework; - using Castle.ActiveRecord.Framework.Config; - using Castle.ActiveRecord.Framework.Scopes; - using Castle.ActiveRecord.Tests.Model; - using Castle.ActiveRecord.Tests.Model.LazyModel; - using NHibernate; - using NHibernate.Criterion; - using NUnit.Framework; - using System.Collections; - using System.Collections.Generic; - - using Castle.ActiveRecord.Queries; - - [TestFixture] - public class StatelessSessionScopeTestCase : AbstractActiveRecordTest - { - [Test] - public void SessionIsStateless() - { - Initialize(); - using (new StatelessSessionScope()) - { - Assert.IsAssignableFrom(typeof(StatelessSessionWrapper), Blog.Holder.CreateSession(typeof(Blog))); - } - } - - [Test] - public void Unsupported_actions_should_have_squattery_exceptions() - { - Initialize(); - using (new StatelessSessionScope()) - { - try - { - Blog.Holder.CreateSession(typeof(Blog)).Merge(null); - Assert.Fail(); - } - catch (NotImplementedException ex) - { - Assert.AreEqual(@"The called method is not supported. + using System; + using Castle.ActiveRecord; + using Castle.ActiveRecord.Framework; + using Castle.ActiveRecord.Framework.Config; + using Castle.ActiveRecord.Framework.Scopes; + using Castle.ActiveRecord.Tests.Model; + using Castle.ActiveRecord.Tests.Model.LazyModel; + using NHibernate; + using NHibernate.Criterion; + using NUnit.Framework; + using System.Collections; + using System.Collections.Generic; + + using Castle.ActiveRecord.Queries; + + [TestFixture] + public class StatelessSessionScopeTestCase : AbstractActiveRecordTest + { + [Test] + public void SessionIsStateless() + { + Initialize(); + using (new StatelessSessionScope()) + { + Assert.IsAssignableFrom(typeof(StatelessSessionWrapper), Blog.Holder.CreateSession(typeof(Blog))); + } + } + + [Test] + public void Unsupported_actions_should_have_squattery_exceptions() + { + Initialize(); + using (new StatelessSessionScope()) + { + try + { + Blog.Holder.CreateSession(typeof(Blog)).Merge(null); + Assert.Fail(); + } + catch (NotImplementedException ex) + { + Assert.AreEqual(@"The called method is not supported. ActiveRecord is currently running within a StatelessSessionScope. Stateless sessions are faster than normal sessions, but they do not support all methods and properties that a normal session allows. Please check the stacktrace and change your code accordingly.", ex.Message); - } - } - } - - [Test] - public void A_simple_object_can_be_created() - { - Initialize(); - using (new StatelessSessionScope()) - CreateBlog(); - - Blog[] blogs = Blog.FindAll(); - Assert.AreEqual(1, blogs.Length); - Assert.AreEqual("Mort", blogs[0].Author); - } - - [Test] - public void A_simple_object_can_be_read() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Ship)); - Recreate(); - - using (new SessionScope()) - ActiveRecordMediator.Create(new Ship { Name = "Andrea Doria" }); - - using (new StatelessSessionScope()) - { - Assert.IsTrue(ActiveRecordMediator.Exists(1)); - Assert.AreEqual("Andrea Doria", ActiveRecordMediator.FindByPrimaryKey(1).Name); - } - } - - [Test] - public void Get_with_lazy_classes_does_work() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(BlogLazy), typeof(PostLazy)); - Recreate(); - - using (new SessionScope()) - new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); - - using (new StatelessSessionScope()) - { - Assert.AreEqual("Mort", BlogLazy.Find(1).Author); - // The assert below cannot work, stateless sessions cannot serve proxies. - // Assert.AreEqual(0, BlogLazy.Find(1).Posts.Count); - } - } - - [Test] - public void Get_with_nonlazy_classes_does_not_work() - { - Initialize(); - - using (new SessionScope()) - new Blog { Author = "Mort", Name = "Hourglass" }.Create(); - - using (new StatelessSessionScope()) - { - try - { - Blog.Find(1); - Assert.Fail(); - } - catch (ActiveRecordException ex) - { - Assert.AreEqual(typeof(SessionException), ex.InnerException.GetType()); - Assert.AreEqual("collections cannot be fetched by a stateless session", ex.InnerException.Message); - } - } - } - - [Test] - public void Updating_stateless_fetched_entities_works() - { - InitializeLazy(); - - using (new SessionScope()) - { - CreateLazyBlog(); - } - - using (new StatelessSessionScope()) - { - var blog = BlogLazy.Find(1); - Assert.AreEqual("Hourglass", blog.Name); - blog.Name = "HOURGLASS"; - blog.Update(); - } - - Assert.AreEqual("HOURGLASS", BlogLazy.Find(1).Name); - } - - [Test] - public void Updating_detached_entities_works() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - Assert.AreEqual("Hourglass", blog.Name); - blog.Name = "HOURGLASS"; - blog.Update(); - } - - Assert.AreEqual("HOURGLASS", Blog.Find(1).Name); - } - - [Test] - public void Inversively_adding_to_a_detached_entitys_collections_works() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - for (int i = 0; i < 10; i++) - { - var post = new Post() { Blog = blog, Title = "Post" + i, Created = DateTime.Now }; - post.Create(); - } - } - - Assert.AreEqual(10, Blog.Find(1).Posts.Count); - } - - - [Test] - public void Updating_detached_entities_collections_does_not_work() - { - Initialize(); - Blog blog; - - using (new SessionScope()) - { - CreateBlog(); - blog = Blog.Find(1); - } - - using (new StatelessSessionScope()) - { - blog.Posts = new List(); - - for (int i = 0; i < 10; i++) - { - var post = new Post() { Title = "Post" + i, Created = DateTime.Now }; - post.Create(); - blog.Posts.Add(post); - } - - blog.Update(); - } - - Assert.AreEqual(0, Blog.Find(1).Posts.Count); - } - - [Test] - public void Transactions_are_supported() - { - Initialize(); - - using (new StatelessSessionScope()) - using (new TransactionScope()) - { - CreateBlog(); - } - - Assert.AreEqual("Mort", Blog.Find(1).Author); - } - - [Test] - public void Querying_works_with_HQL() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - Assert.AreEqual(1, query.Execute().Length); - - } - - [Test] - public void Enumerating_with_queries_doesnt_work() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - query.Enumerate(); - } - - [Test] - public void Can_delete_instances() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); - using (new StatelessSessionScope()) - { - foreach (var blog in query.Execute()) - blog.Delete(); - } - - Assert.AreEqual(0, BlogLazy.FindAll().Length); - } - - [Test] - public void Querying_works_with_Detached_Criteria() - { - InitializeLazy(); - using (new SessionScope()) - CreateLazyBlog(); - - var crit = DetachedCriteria.For().Add(Expression.Eq("Author", "Mort")); - using (new StatelessSessionScope()) - Assert.AreEqual(1, ActiveRecordMediator.FindAll(crit).Length); - - } - - [Test] - public void Collections_can_be_fetched_with_queries() - { - InitializeLazy(); - - var blog = new BlogLazy { Author = "Mort", Name = "Hourglass" }; - var post = new PostLazy { Blog = blog, Title = "...", Created = DateTime.Now }; - - blog.Save(); - post.Save(); - - var query = new SimpleQuery("from BlogLazy b join fetch b.Posts"); - - using (new StatelessSessionScope()) - { - var result = query.Execute(); - Assert.AreEqual(1, result.Length); - Assert.AreEqual(1, result[0].Posts.Count); - var queriedPost = result[0].Posts[0] as PostLazy; - Assert.AreEqual("...", queriedPost.Title); - } - } - - [Test] - public void Nonlazy_collections_can_be_fetched_with_queries() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(SimpleBlog), typeof(SimplePost)); - Recreate(); - - var blog = new SimpleBlog { Name = "Blog" }; - var post = new SimplePost { Blog = blog, Title = "Post" }; - blog.Save(); - post.Save(); - - var query = new SimpleQuery("from SimpleBlog b join fetch b.Posts"); - - using (new StatelessSessionScope()) - { - var result = query.Execute(); - Assert.AreEqual(1, result.Length); - Assert.AreEqual(1, result[0].Posts.Count); - Assert.AreEqual("Post", result[0].Posts[0].Title); - Assert.AreSame(result[0], result[0].Posts[0].Blog); - } - } - - private void Initialize() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog)); - Recreate(); - } - - private void InitializeLazy() - { - ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy)); - Recreate(); - } - - private void CreateBlog() - { - new Blog { Author = "Mort", Name = "Hourglass" }.Create(); - } - - - private void CreateLazyBlog() - { - new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); - } - } + } + } + } + + [Test] + public void A_simple_object_can_be_created() + { + Initialize(); + using (new StatelessSessionScope()) + CreateBlog(); + + Blog[] blogs = Blog.FindAll(); + Assert.AreEqual(1, blogs.Length); + Assert.AreEqual("Mort", blogs[0].Author); + } + + [Test] + public void A_simple_object_can_be_read() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Ship)); + Recreate(); + + using (new SessionScope()) + ActiveRecordMediator.Create(new Ship { Name = "Andrea Doria" }); + + using (new StatelessSessionScope()) + { + Assert.IsTrue(ActiveRecordMediator.Exists(1)); + Assert.AreEqual("Andrea Doria", ActiveRecordMediator.FindByPrimaryKey(1).Name); + } + } + + [Test] + public void Get_with_lazy_classes_does_work() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(BlogLazy), typeof(PostLazy)); + Recreate(); + + using (new SessionScope()) + new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); + + using (new StatelessSessionScope()) + { + Assert.AreEqual("Mort", BlogLazy.Find(1).Author); + // The assert below cannot work, stateless sessions cannot serve proxies. + // Assert.AreEqual(0, BlogLazy.Find(1).Posts.Count); + } + } + + [Test] + public void Get_with_nonlazy_classes_does_not_work() + { + Initialize(); + + using (new SessionScope()) + new Blog { Author = "Mort", Name = "Hourglass" }.Create(); + + using (new StatelessSessionScope()) + { + try + { + Blog.Find(1); + Assert.Fail(); + } + catch (ActiveRecordException ex) + { + Assert.AreEqual(typeof(SessionException), ex.InnerException.GetType()); + Assert.AreEqual("collections cannot be fetched by a stateless session", ex.InnerException.Message); + } + } + } + + [Test] + public void Updating_stateless_fetched_entities_works() + { + InitializeLazy(); + + using (new SessionScope()) + { + CreateLazyBlog(); + } + + using (new StatelessSessionScope()) + { + var blog = BlogLazy.Find(1); + Assert.AreEqual("Hourglass", blog.Name); + blog.Name = "HOURGLASS"; + blog.Update(); + } + + Assert.AreEqual("HOURGLASS", BlogLazy.Find(1).Name); + } + + [Test] + public void Updating_detached_entities_works() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + Assert.AreEqual("Hourglass", blog.Name); + blog.Name = "HOURGLASS"; + blog.Update(); + } + + Assert.AreEqual("HOURGLASS", Blog.Find(1).Name); + } + + [Test] + public void Inversively_adding_to_a_detached_entitys_collections_works() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + for (int i = 0; i < 10; i++) + { + var post = new Post() { Blog = blog, Title = "Post" + i, Created = DateTime.Now }; + post.Create(); + } + } + + Assert.AreEqual(10, Blog.Find(1).Posts.Count); + } + + + [Test] + public void Updating_detached_entities_collections_does_not_work() + { + Initialize(); + Blog blog; + + using (new SessionScope()) + { + CreateBlog(); + blog = Blog.Find(1); + } + + using (new StatelessSessionScope()) + { + blog.Posts = new List(); + + for (int i = 0; i < 10; i++) + { + var post = new Post() { Title = "Post" + i, Created = DateTime.Now }; + post.Create(); + blog.Posts.Add(post); + } + + blog.Update(); + } + + Assert.AreEqual(0, Blog.Find(1).Posts.Count); + } + + [Test] + public void Transactions_are_supported() + { + Initialize(); + + using (new StatelessSessionScope()) + using (new TransactionScope()) + { + CreateBlog(); + } + + Assert.AreEqual("Mort", Blog.Find(1).Author); + } + + [Test] + public void Querying_works_with_HQL() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + Assert.AreEqual(1, query.Execute().Length); + + } + + [Test] + public void Enumerating_with_queries_doesnt_work() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + query.Enumerate(); + } + + [Test] + public void Can_delete_instances() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var query = new SimpleQuery("from BlogLazy b where b.Author = ?", "Mort"); + using (new StatelessSessionScope()) + { + foreach (var blog in query.Execute()) + blog.Delete(); + } + + Assert.AreEqual(0, BlogLazy.FindAll().Length); + } + + [Test] + public void Querying_works_with_Detached_Criteria() + { + InitializeLazy(); + using (new SessionScope()) + CreateLazyBlog(); + + var crit = DetachedCriteria.For().Add(Expression.Eq("Author", "Mort")); + using (new StatelessSessionScope()) + Assert.AreEqual(1, ActiveRecordMediator.FindAll(crit).Length); + + } + + [Test] + public void Collections_can_be_fetched_with_queries() + { + InitializeLazy(); + + var blog = new BlogLazy { Author = "Mort", Name = "Hourglass" }; + var post = new PostLazy { Blog = blog, Title = "...", Created = DateTime.Now }; + + blog.Save(); + post.Save(); + + var query = new SimpleQuery("from BlogLazy b join fetch b.Posts"); + + using (new StatelessSessionScope()) + { + var result = query.Execute(); + Assert.AreEqual(1, result.Length); + Assert.AreEqual(1, result[0].Posts.Count); + var queriedPost = result[0].Posts[0] as PostLazy; + Assert.AreEqual("...", queriedPost.Title); + } + } + + [Test] + public void Nonlazy_collections_can_be_fetched_with_queries() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(SimpleBlog), typeof(SimplePost)); + Recreate(); + + var blog = new SimpleBlog { Name = "Blog" }; + var post = new SimplePost { Blog = blog, Title = "Post" }; + blog.Save(); + post.Save(); + + var query = new SimpleQuery("from SimpleBlog b join fetch b.Posts"); + + using (new StatelessSessionScope()) + { + var result = query.Execute(); + Assert.AreEqual(1, result.Length); + Assert.AreEqual(1, result[0].Posts.Count); + Assert.AreEqual("Post", result[0].Posts[0].Title); + Assert.AreSame(result[0], result[0].Posts[0].Blog); + } + } + + private void Initialize() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog)); + Recreate(); + } + + private void InitializeLazy() + { + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy)); + Recreate(); + } + + private void CreateBlog() + { + new Blog { Author = "Mort", Name = "Hourglass" }.Create(); + } + + + private void CreateLazyBlog() + { + new BlogLazy { Author = "Mort", Name = "Hourglass" }.Create(); + } + } } diff --git a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs index 6bc46f7..1655ac8 100644 --- a/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs +++ b/src/Castle.ActiveRecord.Tests/TableHierarchyTestCase.cs @@ -29,7 +29,7 @@ public class TableHierarchyTestCase : AbstractActiveRecordTest [Test] public void CompanyFirmAndClient() { - ActiveRecordStarter.Initialize( GetConfigSource(), + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Company), typeof(Client), typeof(Firm), typeof(Person), typeof(Blog), typeof(Post)); Recreate(); @@ -46,22 +46,22 @@ public void CompanyFirmAndClient() client.Save(); Client[] clients = Client.FindAll(); - Assert.AreEqual( 1, clients.Length ); + Assert.AreEqual(1, clients.Length); Firm[] firms = Firm.FindAll(); - Assert.AreEqual( 1, firms.Length ); + Assert.AreEqual(1, firms.Length); - Assert.AreEqual( firm.Id, firms[0].Id ); - Assert.AreEqual( client.Id, clients[0].Id ); + Assert.AreEqual(firm.Id, firms[0].Id); + Assert.AreEqual(client.Id, clients[0].Id); - Assert.IsNotNull( clients[0].Firm ); - Assert.AreEqual( firm.Id, clients[0].Firm.Id ); + Assert.IsNotNull(clients[0].Firm); + Assert.AreEqual(firm.Id, clients[0].Firm.Id); } [Test] public void ManyToMany() { - ActiveRecordStarter.Initialize( GetConfigSource(), + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Company), typeof(Client), typeof(Firm), typeof(Person), typeof(Blog), typeof(Post)); Recreate(); @@ -75,7 +75,7 @@ public void ManyToMany() Client client = new Client("castle", firm); Company company = new Company("vs"); - using(new SessionScope()) + using (new SessionScope()) { firm.Save(); client.Save(); @@ -84,32 +84,32 @@ public void ManyToMany() Person person = new Person(); person.Name = "hammett"; - person.Companies.Add( firm ); - person.Companies.Add( client ); - person.Companies.Add( company ); + person.Companies.Add(firm); + person.Companies.Add(client); + person.Companies.Add(company); person.Save(); } - company = Company.Find( company.Id ); - Assert.AreEqual(1, company.People.Count ); + company = Company.Find(company.Id); + Assert.AreEqual(1, company.People.Count); } - + [Test] public void ManyToManyUsingSet() { - ActiveRecordStarter.Initialize(GetConfigSource(), + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Order), typeof(Product)/*, typeof(LineItem)*/); Recreate(); - + Order.DeleteAll(); Product.DeleteAll(); - + Order myOrder = new Order(); myOrder.OrderedDate = DateTime.Parse("05/09/2004"); Product coolGadget = new Product(); coolGadget.Name = "PSP"; coolGadget.Price = 250.39f; - + using (new SessionScope()) { coolGadget.Save(); @@ -118,20 +118,20 @@ public void ManyToManyUsingSet() myOrder.Products = products; myOrder.Save(); } - + Order secondRef2Order = Order.Find(myOrder.ID); Assert.IsFalse(secondRef2Order.Products.Count == 0); - + Product secondRef2Product = Product.Find(coolGadget.ID); - Assert.AreEqual(1, secondRef2Product.Orders.Count); + Assert.AreEqual(1, secondRef2Product.Orders.Count); } [Test] [Ignore("Jira issue for NH team")] public void InvalidSessionCache() { - ActiveRecordStarter.Initialize( GetConfigSource(), - typeof(Company), typeof(Client), typeof(Firm), typeof(Person) ); + ActiveRecordStarter.Initialize(GetConfigSource(), + typeof(Company), typeof(Client), typeof(Firm), typeof(Person)); Recreate(); Company.DeleteAll(); @@ -143,27 +143,27 @@ public void InvalidSessionCache() Client client = new Client("castle", firm); Company company = new Company("vs"); - using(new SessionScope()) + using (new SessionScope()) { firm.Save(); client.Save(); company.Save(); } - using(new SessionScope()) + using (new SessionScope()) { try { - Client c = Client.Find( firm.Id ); + Client c = Client.Find(firm.Id); Assert.Fail("Exception was expected"); } - catch(Exception) + catch (Exception) { // Phew!! } - Firm firm2 = Firm.Find( firm.Id ); + Firm firm2 = Firm.Find(firm.Id); Assert.IsNotNull(firm2); } @@ -173,22 +173,22 @@ public void InvalidSessionCache() [Ignore("Create schema does not create all necessary tables for this test case")] public void ManyToManyUsingIDBag() { - ActiveRecordStarter.Initialize(GetConfigSource(), + ActiveRecordStarter.Initialize(GetConfigSource(), typeof(OrderWithIDBag), typeof(ProductWithIDBag)); Recreate(); - + OrderWithIDBag.DeleteAll(); ProductWithIDBag.DeleteAll(); - + OrderWithIDBag myOrder = new OrderWithIDBag(); myOrder.OrderedDate = new DateTime(2006, 12, 25); - ProductWithIDBag coolGadget = new ProductWithIDBag - { - Name = "Xbox 2", - Price = 330.23f - }; + ProductWithIDBag coolGadget = new ProductWithIDBag + { + Name = "Xbox 2", + Price = 330.23f + }; - using (new SessionScope()) + using (new SessionScope()) { coolGadget.Save(); var products = new List(); @@ -196,10 +196,10 @@ public void ManyToManyUsingIDBag() myOrder.Products = products; myOrder.Save(); } - + OrderWithIDBag secondRef2Order = OrderWithIDBag.Find(myOrder.ID); Assert.IsTrue(secondRef2Order.Products.Count > 0); - + ProductWithIDBag secondRef2Product = ProductWithIDBag.Find(coolGadget.ID); Assert.AreEqual(1, secondRef2Product.Orders.Count); } diff --git a/src/Castle.ActiveRecord/ByteCode/LazyInitializer.cs b/src/Castle.ActiveRecord/ByteCode/LazyInitializer.cs index 3f29530..21629e0 100644 --- a/src/Castle.ActiveRecord/ByteCode/LazyInitializer.cs +++ b/src/Castle.ActiveRecord/ByteCode/LazyInitializer.cs @@ -6,60 +6,60 @@ namespace Castle.ActiveRecord.ByteCode { - using System; - using System.Reflection; + using System; + using System.Reflection; - using NHibernate; - using NHibernate.Engine; - using NHibernate.Proxy; - using NHibernate.Type; + using NHibernate; + using NHibernate.Engine; + using NHibernate.Proxy; + using NHibernate.Type; - internal class LazyInitializer : DefaultLazyInitializer - { - public LazyInitializer(string entityName, - Type persistentClass, - object id, - MethodInfo getIdentifierMethod, - MethodInfo setIdentifierMethod, - IAbstractComponentType componentIdType, - ISessionImplementor session) - : base( - entityName, - persistentClass, - id, - getIdentifierMethod, - setIdentifierMethod, - componentIdType, - session) - { - } + internal class LazyInitializer : DefaultLazyInitializer + { + public LazyInitializer(string entityName, + Type persistentClass, + object id, + MethodInfo getIdentifierMethod, + MethodInfo setIdentifierMethod, + IAbstractComponentType componentIdType, + ISessionImplementor session) + : base( + entityName, + persistentClass, + id, + getIdentifierMethod, + setIdentifierMethod, + componentIdType, + session) + { + } - /// - /// Perform an ImmediateLoad of the actual object for the Proxy. - /// - public override void Initialize() - { - ISession newSession = null; - try - { - //If the session has been disconnected, reconnect before continuing with the initialization. - if (Session == null || !Session.IsOpen || !Session.IsConnected) - { - newSession = - ActiveRecordMediator.GetSessionFactoryHolder() - .CreateSession(PersistentClass); - Session = newSession.GetSessionImplementation(); - } + /// + /// Perform an ImmediateLoad of the actual object for the Proxy. + /// + public override void Initialize() + { + ISession newSession = null; + try + { + //If the session has been disconnected, reconnect before continuing with the initialization. + if (Session == null || !Session.IsOpen || !Session.IsConnected) + { + newSession = + ActiveRecordMediator.GetSessionFactoryHolder() + .CreateSession(PersistentClass); + Session = newSession.GetSessionImplementation(); + } - base.Initialize(); - } - finally - { - if (newSession != null) - { - ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(newSession); - } - } - } - } + base.Initialize(); + } + finally + { + if (newSession != null) + { + ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(newSession); + } + } + } + } } \ No newline at end of file diff --git a/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs b/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs index b9e5131..0087b3c 100644 --- a/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs +++ b/src/Castle.ActiveRecord/ByteCode/ProxyFactory.cs @@ -12,38 +12,38 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Castle.ActiveRecord.ByteCode +namespace Castle.ActiveRecord.ByteCode { using System; using NHibernate; - + using NHibernate.Engine; using NHibernate.Intercept; using NHibernate.Proxy; - internal class ProxyFactory : AbstractProxyFactory - { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ProxyFactory)); - private readonly NHibernate.Proxy.DynamicProxy.ProxyFactory factory = new NHibernate.Proxy.DynamicProxy.ProxyFactory(); + internal class ProxyFactory : AbstractProxyFactory + { + private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ProxyFactory)); + private readonly NHibernate.Proxy.DynamicProxy.ProxyFactory factory = new NHibernate.Proxy.DynamicProxy.ProxyFactory(); - /// + /// /// Build a proxy using the Castle.DynamicProxy library, that overrides the default - /// - /// The value for the Id. - /// The Session the proxy is in. - /// A fully built INHibernateProxy. - public override INHibernateProxy GetProxy(object id, ISessionImplementor session) - { - try - { - var defaultLazyInitializer = new LazyInitializer(this.EntityName, this.PersistentClass, id, this.GetIdentifierMethod, this.SetIdentifierMethod, this.ComponentIdType, session); - return this.IsClassProxy ? (INHibernateProxy)this.factory.CreateProxy(this.PersistentClass, defaultLazyInitializer, this.Interfaces) : (INHibernateProxy)this.factory.CreateProxy(this.Interfaces[0], defaultLazyInitializer, this.Interfaces); - } - catch (Exception ex) - { - log.Error((object)"Creating a proxy instance failed", ex); - throw new HibernateException("Creating a proxy instance failed", ex); - } - } - } + /// + /// The value for the Id. + /// The Session the proxy is in. + /// A fully built INHibernateProxy. + public override INHibernateProxy GetProxy(object id, ISessionImplementor session) + { + try + { + var defaultLazyInitializer = new LazyInitializer(this.EntityName, this.PersistentClass, id, this.GetIdentifierMethod, this.SetIdentifierMethod, this.ComponentIdType, session); + return this.IsClassProxy ? (INHibernateProxy)this.factory.CreateProxy(this.PersistentClass, defaultLazyInitializer, this.Interfaces) : (INHibernateProxy)this.factory.CreateProxy(this.Interfaces[0], defaultLazyInitializer, this.Interfaces); + } + catch (Exception ex) + { + log.Error((object)"Creating a proxy instance failed", ex); + throw new HibernateException("Creating a proxy instance failed", ex); + } + } + } } diff --git a/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs b/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs index e34816f..2531b35 100644 --- a/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs +++ b/src/Castle.ActiveRecord/ByteCode/ProxyFactoryFactory.cs @@ -12,36 +12,35 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Castle.ActiveRecord.ByteCode +namespace Castle.ActiveRecord.ByteCode { using NHibernate.Bytecode; using NHibernate.Proxy; - /// - /// The factory infrastructure used to build AR proxy objects. - /// Use this one if you want automatic session management durring proxy hydration. - /// - public class ProxyFactoryFactory : IProxyFactoryFactory - { + /// + /// The factory infrastructure used to build AR proxy objects. + /// Use this one if you want automatic session management durring proxy hydration. + /// + public class ProxyFactoryFactory : IProxyFactoryFactory + { + public IProxyValidator ProxyValidator + { + get { return new DynProxyTypeValidator(); } + } - public IProxyValidator ProxyValidator - { - get { return new DynProxyTypeValidator(); } - } + public IProxyFactory BuildProxyFactory() + { + return new ProxyFactory(); + } - public IProxyFactory BuildProxyFactory() - { - return new ProxyFactory(); - } - - public bool IsProxy(object entity) - { + public bool IsProxy(object entity) + { return entity is INHibernateProxy; - } + } - public bool IsInstrumented(System.Type entityClass) - { - return true; - } - } + public bool IsInstrumented(System.Type entityClass) + { + return true; + } + } } diff --git a/src/Castle.ActiveRecord/Framework/ActiveRecordStarter.cs b/src/Castle.ActiveRecord/Framework/ActiveRecordStarter.cs index 80bf946..e124b78 100644 --- a/src/Castle.ActiveRecord/Framework/ActiveRecordStarter.cs +++ b/src/Castle.ActiveRecord/Framework/ActiveRecordStarter.cs @@ -73,7 +73,7 @@ public static class ActiveRecordStarter private static bool isInitialized = false; private static readonly List extensions = new List(); - private static readonly HashSet registeredAssemblies = new HashSet(); + private static readonly HashSet registeredAssemblies = new HashSet(); private static IDictionary registeredTypes; /// @@ -152,7 +152,7 @@ public static class ActiveRecordStarter /// public static void Initialize(IConfigurationSource source, params Type[] types) { - lock(lockConfig) + lock (lockConfig) { if (isInitialized) { @@ -213,7 +213,7 @@ public static void Initialize(IConfigurationSource source, params Type[] types) /// public static void Initialize(Assembly assembly, IConfigurationSource source) { - Initialize(new Assembly[] {assembly}, source); + Initialize(new Assembly[] { assembly }, source); } /// @@ -224,7 +224,7 @@ public static void Initialize(Assembly[] assemblies, IConfigurationSource source { List list = new List(additionalTypes); - foreach(Assembly assembly in assemblies) + foreach (Assembly assembly in assemblies) { CollectValidActiveRecordTypesFromAssembly(assembly, list, source); } @@ -252,7 +252,7 @@ public static void RegisterAssemblies(params Assembly[] assemblies) { List types = new List(); - foreach(Assembly assembly in assemblies) + foreach (Assembly assembly in assemblies) { CollectValidActiveRecordTypesFromAssembly(assembly, types, configSource); } @@ -277,7 +277,7 @@ public static void CreateSchema() { CheckInitialized(); - foreach(Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) + foreach (Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) { SchemaExport export = CreateSchemaExport(config); @@ -285,7 +285,7 @@ public static void CreateSchema() { export.Create(false, true); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not create the schema", ex); } @@ -308,7 +308,7 @@ public static void CreateSchema(Type baseClass) { export.Create(false, true); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not create the schema", ex); } @@ -348,7 +348,7 @@ public static void DropSchema() { CheckInitialized(); - foreach(Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) + foreach (Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) { SchemaExport export = CreateSchemaExport(config); @@ -356,7 +356,7 @@ public static void DropSchema() { export.Drop(false, true); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not drop the schema", ex); } @@ -379,7 +379,7 @@ public static void DropSchema(Type baseClass) { export.Drop(false, true); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not drop the schema", ex); } @@ -394,7 +394,7 @@ public static IList UpdateSchema() CheckInitialized(); ArrayList exceptions = new ArrayList(); - foreach(Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) + foreach (Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) { SchemaUpdate updater = CreateSchemaUpdate(config); @@ -402,9 +402,9 @@ public static IList UpdateSchema() { updater.Execute(false, true); - exceptions.AddRange((IList) updater.Exceptions); + exceptions.AddRange((IList)updater.Exceptions); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not update the schema", ex); } @@ -429,12 +429,12 @@ public static IList UpdateSchema(Type baseClass) { updater.Execute(false, true); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not update the schema", ex); } - return (IList) updater.Exceptions; + return (IList)updater.Exceptions; } /// @@ -451,7 +451,7 @@ public static void GenerateDropScripts(String fileName) bool isFirstExport = true; int fileCount = 1; - foreach(Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) + foreach (Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) { SchemaExport export = CreateSchemaExport(config); @@ -460,7 +460,7 @@ public static void GenerateDropScripts(String fileName) export.SetOutputFile(isFirstExport ? fileName : CreateAnotherFile(fileName, fileCount++)); export.Drop(false, false); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not drop the schema", ex); } @@ -486,7 +486,7 @@ public static void GenerateDropScripts(Type baseType, String fileName) export.SetOutputFile(fileName); export.Drop(false, false); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not generate drop schema scripts", ex); } @@ -506,7 +506,7 @@ public static void GenerateCreationScripts(String fileName) bool isFirstExport = true; int fileCount = 1; - foreach(Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) + foreach (Configuration config in ActiveRecordBase.holder.GetAllConfigurations()) { SchemaExport export = CreateSchemaExport(config); @@ -515,7 +515,7 @@ public static void GenerateCreationScripts(String fileName) export.SetOutputFile(isFirstExport ? fileName : CreateAnotherFile(fileName, fileCount++)); export.Create(false, false); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not create the schema", ex); } @@ -541,7 +541,7 @@ public static void GenerateCreationScripts(Type baseType, String fileName) export.SetOutputFile(fileName); export.Create(false, false); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Could not create the schema scripts", ex); } @@ -612,8 +612,8 @@ public static void RegisterExtension(IModelBuilderExtension extension) } private static ActiveRecordModelCollection BuildModels(ISessionFactoryHolder holder, - IConfigurationSource source, - IEnumerable types, bool ignoreProblematicTypes) + IConfigurationSource source, + IEnumerable types, bool ignoreProblematicTypes) { ActiveRecordModelBuilder builder = new ActiveRecordModelBuilder(); @@ -621,7 +621,7 @@ private static ActiveRecordModelCollection BuildModels(ISessionFactoryHolder hol ActiveRecordModelCollection models = builder.Models; - foreach(Type type in types) + foreach (Type type in types) { if (ShouldIgnoreType(type)) { @@ -702,9 +702,9 @@ private static bool TypeDefinesADatabaseBoundary(Type type) private static bool ShouldIgnoreType(Type type) { return (registeredTypes.ContainsKey(type) || - type == typeof(ActiveRecordBase) || - type == typeof(ActiveRecordValidationBase) || - type == typeof(ActiveRecordHooksBase)); + type == typeof(ActiveRecordBase) || + type == typeof(ActiveRecordValidationBase) || + type == typeof(ActiveRecordHooksBase)); } private static bool IsTypeHierarchyBase(ICustomAttributeProvider type) @@ -718,7 +718,7 @@ private static bool IsTypeHierarchyBase(ICustomAttributeProvider type) if (attrs != null && attrs.Length > 0) { - ActiveRecordAttribute att = (ActiveRecordAttribute) attrs[0]; + ActiveRecordAttribute att = (ActiveRecordAttribute)attrs[0]; return att.DiscriminatorColumn != null; } @@ -730,8 +730,8 @@ private static void AddXmlToNHibernateCfg(ISessionFactoryHolder holder, ActiveRe { XmlGenerationVisitor xmlVisitor = new XmlGenerationVisitor(); AssemblyXmlGenerator assemblyXmlGenerator = new AssemblyXmlGenerator(); - - foreach(ActiveRecordModel model in models) + + foreach (ActiveRecordModel model in models) { Configuration config = holder.GetConfiguration(holder.GetRootType(model.Type)); @@ -764,7 +764,7 @@ private static void AddXmlString(Configuration config, string xml, ActiveRecordM { config.AddXmlString(xml); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException( "Error adding information from class " + model.Type.FullName + @@ -778,7 +778,7 @@ private static Type[] GetExportedTypesFromAssembly(Assembly assembly) { return assembly.GetExportedTypes(); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordInitializationException( "Error while loading the exported types from the assembly: " + assembly.FullName, ex); @@ -829,7 +829,7 @@ private static Configuration CreateConfiguration(IConfiguration config) Configuration cfg = new Configuration(); - foreach(IConfiguration childConfig in config.Children) + foreach (IConfiguration childConfig in config.Children) { cfg.Properties[childConfig.Name] = childConfig.Value; } @@ -853,12 +853,12 @@ private static void SetUpConfiguration(IConfigurationSource source, Type type, I { String message = String.Format("The specified type {0} does " + "not implement the interface INamingStrategy", - namingStrategyType.FullName); + namingStrategyType.FullName); throw new ActiveRecordException(message); } - nconf.SetNamingStrategy((INamingStrategy) Activator.CreateInstance(namingStrategyType)); + nconf.SetNamingStrategy((INamingStrategy)Activator.CreateInstance(namingStrategyType)); } AddContributorsToConfig(type, nconf); @@ -896,12 +896,12 @@ private static ISessionFactoryHolder CreateSessionFactoryHolderImplementation(IC { String message = String.Format("The specified type {0} does " + "not implement the interface ISessionFactoryHolder", - sessionFactoryHolderType.FullName); + sessionFactoryHolderType.FullName); throw new ActiveRecordException(message); } - return (ISessionFactoryHolder) Activator.CreateInstance(sessionFactoryHolderType); + return (ISessionFactoryHolder)Activator.CreateInstance(sessionFactoryHolderType); } else { @@ -910,9 +910,9 @@ private static ISessionFactoryHolder CreateSessionFactoryHolderImplementation(IC } private static void RegisterTypes(ISessionFactoryHolder holder, IConfigurationSource source, IEnumerable types, - bool ignoreProblematicTypes) + bool ignoreProblematicTypes) { - lock(lockConfig) + lock (lockConfig) { ActiveRecordModelCollection models = BuildModels(holder, source, types, ignoreProblematicTypes); @@ -939,7 +939,7 @@ private static void RegisterTypes(ISessionFactoryHolder holder, IConfigurationSo AddXmlToNHibernateFromAssmebliesAttributes(holder, models); SessionFactoryHolderDelegate registeredInConfigurationHandler = MappingRegisteredInConfiguration; - if(registeredInConfigurationHandler!=null) + if (registeredInConfigurationHandler != null) { registeredInConfigurationHandler(holder); } @@ -959,16 +959,16 @@ private static void RegisterEventListeners(IEnumerable types) var eventListenerAttributes = type.GetCustomAttributes(typeof(EventListenerAttribute), false); if (eventListenerAttributes.Length == 1) { - var attribute = (EventListenerAttribute) eventListenerAttributes[0]; + var attribute = (EventListenerAttribute)eventListenerAttributes[0]; var config = new EventListenerConfig(type) - { - ReplaceExisting = attribute.ReplaceExisting, - Ignore=attribute.Ignore, - SkipEvent=attribute.SkipEvent, + { + ReplaceExisting = attribute.ReplaceExisting, + Ignore = attribute.Ignore, + SkipEvent = attribute.SkipEvent, Singleton = attribute.Singleton, Include = attribute.Include, Exclude = attribute.Exclude - }; + }; contributor.Add(config); } @@ -984,8 +984,8 @@ private static void RegisterEventListeners(IEnumerable types) foreach (var assembly in registeredAssemblies) { addEventListenerAttributes.AddRange( - (AddEventListenerAttribute[]) assembly.GetCustomAttributes(typeof (AddEventListenerAttribute), false)); - ignoreEventListenerAttributes.AddRange((IgnoreEventListenerAttribute[]) assembly.GetCustomAttributes(typeof(IgnoreEventListenerAttribute), false)); + (AddEventListenerAttribute[])assembly.GetCustomAttributes(typeof(AddEventListenerAttribute), false)); + ignoreEventListenerAttributes.AddRange((IgnoreEventListenerAttribute[])assembly.GetCustomAttributes(typeof(IgnoreEventListenerAttribute), false)); } ProcessEventListenerAssemblyAttributes(contributor, ignoreEventListenerAttributes); @@ -1029,7 +1029,7 @@ private static void ConfigureEventListener(EventListenerAssemblyAttribute attrib else { config.Ignore = false; - var addAttribute = (AddEventListenerAttribute) attribute; + var addAttribute = (AddEventListenerAttribute)attribute; config.Exclude = addAttribute.Exclude; config.Include = addAttribute.Include; config.SkipEvent = addAttribute.ExcludeEvent; @@ -1051,13 +1051,13 @@ private static void AddXmlToNHibernateFromAssmebliesAttributes(ISessionFactoryHo foreach (ActiveRecordModel model in models) { - if (assembliesGeneratedXmlFor.Contains(model.Type.Assembly)) + if (assembliesGeneratedXmlFor.Contains(model.Type.Assembly)) continue; assembliesGeneratedXmlFor.Add(model.Type.Assembly); Configuration config = holder.GetConfiguration(holder.GetRootType(model.Type)); - + string[] configurations = assemblyXmlGenerator.CreateXmlConfigurations(model.Type.Assembly); foreach (string xml in configurations) @@ -1092,7 +1092,7 @@ private static void AddXmlToNHibernateFromAssmebliesAttributes(ISessionFactoryHo private static void VerifySchema(ActiveRecordModelCollection models) { - foreach(ActiveRecordModel model in models) + foreach (ActiveRecordModel model in models) { if (!model.Type.IsAbstract) { @@ -1100,7 +1100,7 @@ private static void VerifySchema(ActiveRecordModelCollection models) { ActiveRecordMediator.FindAll(model.Type, Expression.Sql("1=0")); } - catch(Exception ex) + catch (Exception ex) { throw new ActiveRecordException("Error verifying the schema for model " + model.Type.Name, ex); } @@ -1118,12 +1118,12 @@ private static IThreadScopeInfo CreateThreadScopeInfoImplementation(IConfigurati { String message = String.Format("The specified type {0} does " + "not implement the interface IThreadScopeInfo", - threadScopeType.FullName); + threadScopeType.FullName); throw new ActiveRecordInitializationException(message); } - return (IThreadScopeInfo) Activator.CreateInstance(threadScopeType); + return (IThreadScopeInfo)Activator.CreateInstance(threadScopeType); } else { @@ -1139,12 +1139,12 @@ private static IThreadScopeInfo CreateThreadScopeInfoImplementation(IConfigurati /// Array to store retrieved types in /// IConfigurationSource to inspect AR base declarations from private static void CollectValidActiveRecordTypesFromAssembly(Assembly assembly, ICollection list, - IConfigurationSource source) + IConfigurationSource source) { registeredAssemblies.Add(assembly); Type[] types = GetExportedTypesFromAssembly(assembly); - foreach(Type type in types) + foreach (Type type in types) { if (IsActiveRecordType(type) || IsEventListener(type) || source.GetConfiguration(type) != null) { @@ -1155,7 +1155,7 @@ private static void CollectValidActiveRecordTypesFromAssembly(Assembly assembly, private static bool IsEventListener(Type type) { - return type.IsDefined(typeof (EventListenerAttribute), false); + return type.IsDefined(typeof(EventListenerAttribute), false); } /// diff --git a/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs b/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs index 1c0449d..8144b0a 100644 --- a/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs +++ b/src/Castle.ActiveRecord/Framework/Config/DatabaseType.cs @@ -14,71 +14,71 @@ namespace Castle.ActiveRecord.Framework.Config { - /// - /// Enum for database types support for configuration construction. - /// Not to be confused by databases supported by ActiveRecord - /// - public enum DatabaseType - { - /// - /// Microsoft SQL Server 2000 - /// - MsSqlServer2000, - /// - /// Microsoft SQL Server 2005 - /// - MsSqlServer2005, - /// - /// Microsoft SQL Server 2008 - /// - MsSqlServer2008, - /// - /// Microsoft SQL Server 2012 - /// - MsSqlServer2012, - /// - /// SQLite - /// - SQLite, - /// - /// MySQL 3 or 4 - /// - MySql, - /// - /// MySQL 5 - /// - MySql5, - /// - /// Firebird - /// - Firebird, - /// - /// PostgreSQL - /// - PostgreSQL, - /// - /// PostgreSQL 8.1 - /// - PostgreSQL81, - /// - /// PostgreSQL 8.2 - /// - PostgreSQL82, - /// - /// Microsoft SQL Server 2005 Compact Edition - /// - MsSqlCe, - /// - /// Oracle - /// - Oracle8i, - /// - /// Oracle 9 - /// - Oracle9i, - /// - /// Oracle 10g - /// - Oracle10g - } + /// + /// Enum for database types support for configuration construction. + /// Not to be confused by databases supported by ActiveRecord + /// + public enum DatabaseType + { + /// + /// Microsoft SQL Server 2000 + /// + MsSqlServer2000, + /// + /// Microsoft SQL Server 2005 + /// + MsSqlServer2005, + /// + /// Microsoft SQL Server 2008 + /// + MsSqlServer2008, + /// + /// Microsoft SQL Server 2012 + /// + MsSqlServer2012, + /// + /// SQLite + /// + SQLite, + /// + /// MySQL 3 or 4 + /// + MySql, + /// + /// MySQL 5 + /// + MySql5, + /// + /// Firebird + /// + Firebird, + /// + /// PostgreSQL + /// + PostgreSQL, + /// + /// PostgreSQL 8.1 + /// + PostgreSQL81, + /// + /// PostgreSQL 8.2 + /// + PostgreSQL82, + /// + /// Microsoft SQL Server 2005 Compact Edition + /// + MsSqlCe, + /// + /// Oracle + /// + Oracle8i, + /// + /// Oracle 9 + /// + Oracle9i, + /// + /// Oracle 10g + /// + Oracle10g + } } diff --git a/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs b/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs index 43de4b8..f3fee31 100644 --- a/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs +++ b/src/Castle.ActiveRecord/Framework/Config/DefaultDatabaseConfiguration.cs @@ -18,7 +18,7 @@ namespace Castle.ActiveRecord.Framework.Config using System.Collections.Generic; using System.Data; - using Castle.ActiveRecord.ByteCode; + using Castle.ActiveRecord.ByteCode; using NHibernate.Connection; using NHibernate.Dialect; @@ -60,14 +60,16 @@ public IDictionary For(DatabaseType databaseType) return Configure(); case DatabaseType.MsSqlServer2008: return Configure(); - case DatabaseType.MsSqlServer2012: - return Configure(); + case DatabaseType.MsSqlServer2012: + return Configure(); case DatabaseType.SQLite: return Configure(SQLite()); case DatabaseType.MySql: return Configure(); case DatabaseType.MySql5: return Configure(); + case DatabaseType.Firebird: + return Configure(Firebird()); case DatabaseType.PostgreSQL: return Configure(); case DatabaseType.PostgreSQL81: diff --git a/src/Castle.ActiveRecord/Framework/Internal/EventListener/EventListenerContributor.cs b/src/Castle.ActiveRecord/Framework/Internal/EventListener/EventListenerContributor.cs index 3af46b1..5140998 100644 --- a/src/Castle.ActiveRecord/Framework/Internal/EventListener/EventListenerContributor.cs +++ b/src/Castle.ActiveRecord/Framework/Internal/EventListener/EventListenerContributor.cs @@ -16,8 +16,10 @@ namespace Castle.ActiveRecord.Framework.Internal.EventListener { using System; using System.Collections; - using Iesi.Collections.Generic; using System.Collections.Generic; + + using Iesi.Collections.Generic; + using NHibernate.Cfg; /// @@ -25,8 +27,8 @@ namespace Castle.ActiveRecord.Framework.Internal.EventListener /// public class EventListenerContributor : AbstractNHContributor { - private readonly Dictionary> listenersPerEvent = - new Dictionary>(); + private readonly Dictionary> listenersPerEvent = + new Dictionary>(); private readonly Dictionary listeners = new Dictionary(); @@ -103,7 +105,7 @@ The event listener contributor was asked to contribute to a NHibernate config wi foreach (var eventType in eventTypes) { - if (!listenersPerEvent.ContainsKey(eventType) || listenersPerEvent[eventType] == null) + if (!listenersPerEvent.ContainsKey(eventType) || listenersPerEvent[eventType] == null) continue; var currentListeners = CollectListeners(eventType); @@ -127,8 +129,8 @@ private EventListenerConfig[] CollectListeners(Type type) { var config = Get(listenerType); if (config.Ignore) continue; - if (config.SkipEvent != null && Array.Exists(config.SkipEvent,t => t.Equals(type))) continue; - if (config.Include != null && + if (config.SkipEvent != null && Array.Exists(config.SkipEvent, t => t.Equals(type))) continue; + if (config.Include != null && config.Include.Length > 0 && !Array.Exists(config.Include, t => t.Equals(currentActiveRecordConfig))) continue; @@ -173,7 +175,7 @@ public EventListenerContributor() return true; }; } - + internal static Type[] GetEventTypes(Type listenerType) { return Array.FindAll( diff --git a/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs b/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs index 3315661..f013c81 100644 --- a/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs +++ b/src/Castle.ActiveRecord/Framework/Internal/Model/ActiveRecordModel.cs @@ -14,566 +14,566 @@ namespace Castle.ActiveRecord.Framework.Internal { - using System; - using System.Collections; - using System.Collections.Generic; - using System.Reflection; - using Castle.Components.Validator; - - /// - /// This model of a full Active Record persistent class. - /// - [Serializable] - public class ActiveRecordModel : IVisitable - { - /// - /// The mapping between a type and a model - /// - protected internal static IDictionary type2Model = Hashtable.Synchronized(new Hashtable()); - - /// - /// Whatever Active Record will generate debug information or not - /// - protected internal static bool isDebug = false; - - /// - /// Whatever types that does not explicitly state that they are lazy should be lazy. - /// - protected internal static bool isLazyByDefault = false; - - /// - /// Whether the default inferred table name is plural - /// - protected internal static bool pluralizeTableNames = false; - - private readonly Type type; - - private bool isJoinedSubClassBase; - private bool isDiscriminatorBase; - private bool isDiscriminatorSubClass; - private bool isJoinedSubClass; - private bool isNestedType; - private bool isNestedCompositeType; - - private ActiveRecordAttribute arAtt; - private ActiveRecordModel parent; - private PrimaryKeyModel primaryKey; - private CompositeKeyModel compositeKey; - private KeyModel key; - private TimestampModel timestamp; - private VersionModel version; - private NestedModel parentNested; - - private readonly IList imports = new List(); - private readonly IList hasManyToAny = new List(); - private readonly IList anys = new List(); - private readonly IList properties = new List(); - private readonly IList fields = new List(); - private readonly IList componentParent = new List(); - private readonly IList classes = new List(); - private readonly IList joinedclasses = new List(); - private readonly IList joinedTables = new List(); - private readonly IList components = new List(); - private readonly IList belongsTo = new List(); - private readonly IList hasMany = new List(); - private readonly IList hasAndBelongsToMany = new List(); - private readonly IList oneToOne = new List(); - private readonly IList collectionIds = new List(); - private readonly IList hilos = new List(); - private readonly IList notMappedProperties = new List(); - private readonly IList compositeUserType = new List(); - private readonly IList validators = new List(); - - private readonly IDictionary extendedProperties = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary propertyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary belongsToDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasManyToAnyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasManyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private readonly IDictionary hasAndBelongsToManyDictionary = - new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - /// - /// Initializes a new instance of the class. - /// - /// The type. - public ActiveRecordModel(Type type) - { - this.type = type; - } - - /// - /// Gets or sets the parent model - /// - /// The parent. - public ActiveRecordModel Parent - { - get { return parent; } - set { parent = value; } - } - - /// - /// Gets the type for this model - /// - /// The type. - public Type Type - { - get { return type; } - } - - /// - /// Gets or sets a value indicating whether this instance is joined sub class base. - /// - /// - /// true if this instance is joined sub class base; otherwise, false. - /// - public bool IsJoinedSubClassBase - { - get { return isJoinedSubClassBase; } - set { isJoinedSubClassBase = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is discriminator base. - /// - /// - /// true if this instance is discriminator base; otherwise, false. - /// - public bool IsDiscriminatorBase - { - get { return isDiscriminatorBase; } - set { isDiscriminatorBase = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is discriminator sub class. - /// - /// - /// true if this instance is discriminator sub class; otherwise, false. - /// - public bool IsDiscriminatorSubClass - { - get { return isDiscriminatorSubClass; } - set { isDiscriminatorSubClass = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is joined sub class. - /// - /// - /// true if this instance is joined sub class; otherwise, false. - /// - public bool IsJoinedSubClass - { - get { return isJoinedSubClass; } - set { isJoinedSubClass = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is nested type. - /// - /// - /// true if this instance is nested type; otherwise, false. - /// - public bool IsNestedType - { - get { return isNestedType; } - set { isNestedType = value; } - } - - /// - /// Gets or sets the parent nested. - /// - /// The parent nested. - public NestedModel ParentNested - { - get { return parentNested; } - set { parentNested = value; } - } - - /// - /// Gets or sets a value indicating whether this instance is nested type. - /// - /// - /// true if this instance is nested type; otherwise, false. - /// - public bool IsNestedCompositeType - { - get { return isNestedCompositeType; } - set { isNestedCompositeType = value; } - } - - /// - /// Gets or sets the active record attribute - /// - /// The active record att. - public ActiveRecordAttribute ActiveRecordAtt - { - get { return arAtt; } - set { arAtt = value; } - } - - /// - /// Used only by joined subclasses - /// - public KeyModel Key - { - get { return key; } - set { key = value; } - } - - /// - /// Gets or sets the timestamp model - /// - /// The timestamp. - public TimestampModel Timestamp - { - get { return timestamp; } - set { timestamp = value; } - } - - /// - /// Gets or sets the version model - /// - /// The version. - public VersionModel Version - { - get { return version; } - set { version = value; } - } - - /// - /// Gets all the imports - /// - /// The imports. - public IList Imports - { - get { return imports; } - } - - /// - /// Gets all the properties - /// - /// The properties. - public IList Properties - { - get { return properties; } - } - - /// - /// Gets all the fields - /// - /// The fields. - public IList Fields - { - get { return fields; } - } - - /// - /// If the object is a component, will return the objects declared parent property. - /// There should only be one, but implemented as a list - /// - public IList ComponentParent - { - get { return componentParent; } - } - - /// - /// Gets the list of [has many to any] models - /// - /// The has many to any. - public IList HasManyToAny - { - get { return hasManyToAny; } - } - - /// - /// Gets the list of [any] model - /// - /// The anys. - public IList Anys - { - get { return anys; } - } - - /// - /// Gets the list of the derived classes - /// - /// The classes. - public IList Classes - { - get { return classes; } - } - - /// - /// Gets the list of derived joined classes. - /// - /// The joined classes. - public IList JoinedClasses - { - get { return joinedclasses; } - } - - /// - /// Gets the list of joined tables. - /// - /// The joined tables. - public IList JoinedTables - { - get { return joinedTables; } - } - - /// - /// Gets the list of components. - /// - /// The components. - public IList Components - { - get { return components; } - } - - /// - /// Gets the list of [belongs to] models - /// - /// The belongs to. - public IList BelongsTo - { - get { return belongsTo; } - } - - /// - /// Gets the list of [has many] models - /// - /// The has many. - public IList HasMany - { - get { return hasMany; } - } - - /// - /// Gets the list of [has and belongs to many] models - /// - /// The has and belongs to many. - public IList HasAndBelongsToMany - { - get { return hasAndBelongsToMany; } - } - - /// - /// Gets the list of [one to one] models - /// - /// The one to ones. - public IList OneToOnes - { - get { return oneToOne; } - } - - /// - /// Gets the list of [collection id] models - /// - /// The collection I ds. - public IList CollectionIDs - { - get { return collectionIds; } - } - - /// - /// For unique Primary keys - /// - public PrimaryKeyModel PrimaryKey - { - get { return primaryKey; } - set { primaryKey = value; } - } - - /// - /// For Composite Primary keys - /// - public CompositeKeyModel CompositeKey - { - get { return compositeKey; } - set { compositeKey = value; } - } - - /// - /// Gets the list of [hilo] models - /// - /// The hilos. - public IList Hilos - { - get { return hilos; } - } - - /// - /// Gets the list of properties not mapped . - /// - /// The not mapped properties. - public IList NotMappedProperties - { - get { return notMappedProperties; } - } - - /// - /// Gets the validators. - /// - /// The validators. - public IList Validators - { - get { return validators; } - } - - /// - /// Gets a value indicating whether to use auto import - /// - /// true if should use auto import; otherwise, false. - public bool UseAutoImport - { - get - { - if (arAtt != null) - { - return arAtt.UseAutoImport; - } - - return true; - } - } - - /// - /// Gets the composite user types properties. - /// - /// The type of the composite user. - public IList CompositeUserType - { - get { return compositeUserType; } - } - - /// - /// Gets the extended properties. Used to store/retrieve information collected by model builder extensions. - /// - /// - /// The extended properties. - public IDictionary ExtendedProperties - { - get { return extendedProperties; } - } - - /// - /// Gets the property dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The property dictionary. - public IDictionary PropertyDictionary - { - get { return propertyDictionary; } - } - - /// - /// Gets the belongs to dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The belongs to dictionary. - public IDictionary BelongsToDictionary - { - get { return belongsToDictionary; } - } - - /// - /// Gets the has many to any dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has many to any dictionary. - public IDictionary HasManyToAnyDictionary - { - get { return hasManyToAnyDictionary; } - } - - /// - /// Gets the has many dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has many dictionary. - public IDictionary HasManyDictionary - { - get { return hasManyDictionary; } - } - - /// - /// Gets the has and belongs to many dictionary. Used to provide fast access - /// to a based on the property name. - /// - /// The has and belongs to many dictionary. - public IDictionary HasAndBelongsToManyDictionary - { - get { return hasAndBelongsToManyDictionary; } - } - - /// - /// Used internally register an association between a type and its model - /// - /// - /// - internal static void Register(Type arType, ActiveRecordModel model) - { - type2Model[arType] = model; - } - - /// - /// Gets the for a given ActiveRecord class. - /// - public static ActiveRecordModel GetModel(Type arType) - { - arType = GetNonProxy(arType); - return (ActiveRecordModel)type2Model[arType]; - } - - /// - /// Gets an array containing the for every registered ActiveRecord class. - /// - public static ActiveRecordModel[] GetModels() - { - ActiveRecordModel[] modelArray = new ActiveRecordModel[type2Model.Values.Count]; - - type2Model.Values.CopyTo(modelArray, 0); - - return modelArray; - } - - /// - /// Get the base type is the object is lazy - /// - private static Type GetNonProxy(Type type) - { - //Dynamic Proxy 1.0 //Dynamic Proxy 2.0 - if (type.GetField("__interceptor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null - || type.GetField("__interceptors", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null) - { - type = type.BaseType; - } - - return type; - } - - #region IVisitable Members - - /// - /// Accepts the specified visitor and call the relevant IVisitor.Visit***() method - /// - /// The visitor. - public void Accept(IVisitor visitor) - { - visitor.VisitModel(this); - } - - #endregion - } + using System; + using System.Collections; + using System.Collections.Generic; + using System.Reflection; + using Castle.Components.Validator; + + /// + /// This model of a full Active Record persistent class. + /// + [Serializable] + public class ActiveRecordModel : IVisitable + { + /// + /// The mapping between a type and a model + /// + protected internal static IDictionary type2Model = Hashtable.Synchronized(new Hashtable()); + + /// + /// Whatever Active Record will generate debug information or not + /// + protected internal static bool isDebug = false; + + /// + /// Whatever types that does not explicitly state that they are lazy should be lazy. + /// + protected internal static bool isLazyByDefault = false; + + /// + /// Whether the default inferred table name is plural + /// + protected internal static bool pluralizeTableNames = false; + + private readonly Type type; + + private bool isJoinedSubClassBase; + private bool isDiscriminatorBase; + private bool isDiscriminatorSubClass; + private bool isJoinedSubClass; + private bool isNestedType; + private bool isNestedCompositeType; + + private ActiveRecordAttribute arAtt; + private ActiveRecordModel parent; + private PrimaryKeyModel primaryKey; + private CompositeKeyModel compositeKey; + private KeyModel key; + private TimestampModel timestamp; + private VersionModel version; + private NestedModel parentNested; + + private readonly IList imports = new List(); + private readonly IList hasManyToAny = new List(); + private readonly IList anys = new List(); + private readonly IList properties = new List(); + private readonly IList fields = new List(); + private readonly IList componentParent = new List(); + private readonly IList classes = new List(); + private readonly IList joinedclasses = new List(); + private readonly IList joinedTables = new List(); + private readonly IList components = new List(); + private readonly IList belongsTo = new List(); + private readonly IList hasMany = new List(); + private readonly IList hasAndBelongsToMany = new List(); + private readonly IList oneToOne = new List(); + private readonly IList collectionIds = new List(); + private readonly IList hilos = new List(); + private readonly IList notMappedProperties = new List(); + private readonly IList compositeUserType = new List(); + private readonly IList validators = new List(); + + private readonly IDictionary extendedProperties = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary propertyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary belongsToDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasManyToAnyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasManyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + private readonly IDictionary hasAndBelongsToManyDictionary = + new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public ActiveRecordModel(Type type) + { + this.type = type; + } + + /// + /// Gets or sets the parent model + /// + /// The parent. + public ActiveRecordModel Parent + { + get { return parent; } + set { parent = value; } + } + + /// + /// Gets the type for this model + /// + /// The type. + public Type Type + { + get { return type; } + } + + /// + /// Gets or sets a value indicating whether this instance is joined sub class base. + /// + /// + /// true if this instance is joined sub class base; otherwise, false. + /// + public bool IsJoinedSubClassBase + { + get { return isJoinedSubClassBase; } + set { isJoinedSubClassBase = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is discriminator base. + /// + /// + /// true if this instance is discriminator base; otherwise, false. + /// + public bool IsDiscriminatorBase + { + get { return isDiscriminatorBase; } + set { isDiscriminatorBase = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is discriminator sub class. + /// + /// + /// true if this instance is discriminator sub class; otherwise, false. + /// + public bool IsDiscriminatorSubClass + { + get { return isDiscriminatorSubClass; } + set { isDiscriminatorSubClass = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is joined sub class. + /// + /// + /// true if this instance is joined sub class; otherwise, false. + /// + public bool IsJoinedSubClass + { + get { return isJoinedSubClass; } + set { isJoinedSubClass = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is nested type. + /// + /// + /// true if this instance is nested type; otherwise, false. + /// + public bool IsNestedType + { + get { return isNestedType; } + set { isNestedType = value; } + } + + /// + /// Gets or sets the parent nested. + /// + /// The parent nested. + public NestedModel ParentNested + { + get { return parentNested; } + set { parentNested = value; } + } + + /// + /// Gets or sets a value indicating whether this instance is nested type. + /// + /// + /// true if this instance is nested type; otherwise, false. + /// + public bool IsNestedCompositeType + { + get { return isNestedCompositeType; } + set { isNestedCompositeType = value; } + } + + /// + /// Gets or sets the active record attribute + /// + /// The active record att. + public ActiveRecordAttribute ActiveRecordAtt + { + get { return arAtt; } + set { arAtt = value; } + } + + /// + /// Used only by joined subclasses + /// + public KeyModel Key + { + get { return key; } + set { key = value; } + } + + /// + /// Gets or sets the timestamp model + /// + /// The timestamp. + public TimestampModel Timestamp + { + get { return timestamp; } + set { timestamp = value; } + } + + /// + /// Gets or sets the version model + /// + /// The version. + public VersionModel Version + { + get { return version; } + set { version = value; } + } + + /// + /// Gets all the imports + /// + /// The imports. + public IList Imports + { + get { return imports; } + } + + /// + /// Gets all the properties + /// + /// The properties. + public IList Properties + { + get { return properties; } + } + + /// + /// Gets all the fields + /// + /// The fields. + public IList Fields + { + get { return fields; } + } + + /// + /// If the object is a component, will return the objects declared parent property. + /// There should only be one, but implemented as a list + /// + public IList ComponentParent + { + get { return componentParent; } + } + + /// + /// Gets the list of [has many to any] models + /// + /// The has many to any. + public IList HasManyToAny + { + get { return hasManyToAny; } + } + + /// + /// Gets the list of [any] model + /// + /// The anys. + public IList Anys + { + get { return anys; } + } + + /// + /// Gets the list of the derived classes + /// + /// The classes. + public IList Classes + { + get { return classes; } + } + + /// + /// Gets the list of derived joined classes. + /// + /// The joined classes. + public IList JoinedClasses + { + get { return joinedclasses; } + } + + /// + /// Gets the list of joined tables. + /// + /// The joined tables. + public IList JoinedTables + { + get { return joinedTables; } + } + + /// + /// Gets the list of components. + /// + /// The components. + public IList Components + { + get { return components; } + } + + /// + /// Gets the list of [belongs to] models + /// + /// The belongs to. + public IList BelongsTo + { + get { return belongsTo; } + } + + /// + /// Gets the list of [has many] models + /// + /// The has many. + public IList HasMany + { + get { return hasMany; } + } + + /// + /// Gets the list of [has and belongs to many] models + /// + /// The has and belongs to many. + public IList HasAndBelongsToMany + { + get { return hasAndBelongsToMany; } + } + + /// + /// Gets the list of [one to one] models + /// + /// The one to ones. + public IList OneToOnes + { + get { return oneToOne; } + } + + /// + /// Gets the list of [collection id] models + /// + /// The collection I ds. + public IList CollectionIDs + { + get { return collectionIds; } + } + + /// + /// For unique Primary keys + /// + public PrimaryKeyModel PrimaryKey + { + get { return primaryKey; } + set { primaryKey = value; } + } + + /// + /// For Composite Primary keys + /// + public CompositeKeyModel CompositeKey + { + get { return compositeKey; } + set { compositeKey = value; } + } + + /// + /// Gets the list of [hilo] models + /// + /// The hilos. + public IList Hilos + { + get { return hilos; } + } + + /// + /// Gets the list of properties not mapped . + /// + /// The not mapped properties. + public IList NotMappedProperties + { + get { return notMappedProperties; } + } + + /// + /// Gets the validators. + /// + /// The validators. + public IList Validators + { + get { return validators; } + } + + /// + /// Gets a value indicating whether to use auto import + /// + /// true if should use auto import; otherwise, false. + public bool UseAutoImport + { + get + { + if (arAtt != null) + { + return arAtt.UseAutoImport; + } + + return true; + } + } + + /// + /// Gets the composite user types properties. + /// + /// The type of the composite user. + public IList CompositeUserType + { + get { return compositeUserType; } + } + + /// + /// Gets the extended properties. Used to store/retrieve information collected by model builder extensions. + /// + /// + /// The extended properties. + public IDictionary ExtendedProperties + { + get { return extendedProperties; } + } + + /// + /// Gets the property dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The property dictionary. + public IDictionary PropertyDictionary + { + get { return propertyDictionary; } + } + + /// + /// Gets the belongs to dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The belongs to dictionary. + public IDictionary BelongsToDictionary + { + get { return belongsToDictionary; } + } + + /// + /// Gets the has many to any dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has many to any dictionary. + public IDictionary HasManyToAnyDictionary + { + get { return hasManyToAnyDictionary; } + } + + /// + /// Gets the has many dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has many dictionary. + public IDictionary HasManyDictionary + { + get { return hasManyDictionary; } + } + + /// + /// Gets the has and belongs to many dictionary. Used to provide fast access + /// to a based on the property name. + /// + /// The has and belongs to many dictionary. + public IDictionary HasAndBelongsToManyDictionary + { + get { return hasAndBelongsToManyDictionary; } + } + + /// + /// Used internally register an association between a type and its model + /// + /// + /// + internal static void Register(Type arType, ActiveRecordModel model) + { + type2Model[arType] = model; + } + + /// + /// Gets the for a given ActiveRecord class. + /// + public static ActiveRecordModel GetModel(Type arType) + { + arType = GetNonProxy(arType); + return (ActiveRecordModel)type2Model[arType]; + } + + /// + /// Gets an array containing the for every registered ActiveRecord class. + /// + public static ActiveRecordModel[] GetModels() + { + ActiveRecordModel[] modelArray = new ActiveRecordModel[type2Model.Values.Count]; + + type2Model.Values.CopyTo(modelArray, 0); + + return modelArray; + } + + /// + /// Get the base type is the object is lazy + /// + private static Type GetNonProxy(Type type) + { + //Dynamic Proxy 1.0 //Dynamic Proxy 2.0 + if (type.GetField("__interceptor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null + || type.GetField("__interceptors", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null) + { + type = type.BaseType; + } + + return type; + } + + #region IVisitable Members + + /// + /// Accepts the specified visitor and call the relevant IVisitor.Visit***() method + /// + /// The visitor. + public void Accept(IVisitor visitor) + { + visitor.VisitModel(this); + } + + #endregion + } } diff --git a/src/Castle.ActiveRecord/Framework/Internal/Visitors/SemanticVerifierVisitor.cs b/src/Castle.ActiveRecord/Framework/Internal/Visitors/SemanticVerifierVisitor.cs index 5338394..de55d33 100644 --- a/src/Castle.ActiveRecord/Framework/Internal/Visitors/SemanticVerifierVisitor.cs +++ b/src/Castle.ActiveRecord/Framework/Internal/Visitors/SemanticVerifierVisitor.cs @@ -76,8 +76,8 @@ public override void VisitModel(ActiveRecordModel model) if (model.Version != null && model.Timestamp != null) { throw new ActiveRecordException(String.Format( - "You can't specify a version and a timestamp properties, only one of them " + - "- check type {0}", model.Type.FullName)); + "You can't specify a version and a timestamp properties, only one of them " + + "- check type {0}", model.Type.FullName)); } if (model.IsDiscriminatorSubClass || model.IsJoinedSubClass) @@ -85,16 +85,16 @@ public override void VisitModel(ActiveRecordModel model) if (model.Version != null || model.Timestamp != null) { throw new ActiveRecordException(String.Format( - "A joined subclass or discriminator subclass can't specify a version or timestamp " + - "- check type {0}", model.Type.FullName)); + "A joined subclass or discriminator subclass can't specify a version or timestamp " + + "- check type {0}", model.Type.FullName)); } } if (model.IsJoinedSubClass && model.Key == null) { throw new ActiveRecordException(String.Format( - "A joined subclass must specify a key property. Use the JoinedKeyAttribute to denote the shared key. " + - "- check type {0}", model.Type.FullName)); + "A joined subclass must specify a key property. Use the JoinedKeyAttribute to denote the shared key. " + + "- check type {0}", model.Type.FullName)); } if (model.IsNestedType) @@ -102,18 +102,18 @@ public override void VisitModel(ActiveRecordModel model) if (model.Version != null || model.Timestamp != null) { throw new ActiveRecordException(String.Format( - "A nested type is not allowed to have version or timestamped fields " + - "- check type {0}", model.Type.FullName)); + "A nested type is not allowed to have version or timestamped fields " + + "- check type {0}", model.Type.FullName)); } } if (model.ActiveRecordAtt != null && model.ActiveRecordAtt.Persister != null) { - if (!typeof (IEntityPersister).IsAssignableFrom(model.ActiveRecordAtt.Persister)) + if (!typeof(IEntityPersister).IsAssignableFrom(model.ActiveRecordAtt.Persister)) { throw new ActiveRecordException(String.Format( - "The type assigned as a custom persister, does not implement IEntityPersister " + - "- check type {0}", model.Type.FullName)); + "The type assigned as a custom persister, does not implement IEntityPersister " + + "- check type {0}", model.Type.FullName)); } } @@ -171,12 +171,12 @@ public override void VisitPrimaryKey(PrimaryKeyModel model) if (model.PrimaryKeyAtt.CustomGenerator == null) { throw new ActiveRecordException(String.Format( - "A type defined that its primary key would use a custom generator, " + - "but apparently forgot to define the custom generator using PrimaryKeyAttribute.CustomGenerator property. " + - "Check type {0}", currentModel.Type.FullName)); + "A type defined that its primary key would use a custom generator, " + + "but apparently forgot to define the custom generator using PrimaryKeyAttribute.CustomGenerator property. " + + "Check type {0}", currentModel.Type.FullName)); } - if (!typeof (IIdentifierGenerator).IsAssignableFrom(model.PrimaryKeyAtt.CustomGenerator)) + if (!typeof(IIdentifierGenerator).IsAssignableFrom(model.PrimaryKeyAtt.CustomGenerator)) { throw new ActiveRecordException( "The custom generator associated with the PK for the type " + currentModel.Type.FullName + @@ -203,42 +203,42 @@ public override void VisitCompositePrimaryKey(CompositeKeyModel model) MethodInfo hc = null; new List(compositeKeyClassType.GetMethods(flags)).ForEach(delegate(MethodInfo method) - { - if (method.Name.Equals("Equals")) - { - ParameterInfo[] parameters = - method.GetParameters(); - - if ((parameters.Length == 1) && - (parameters[0].ParameterType == - typeof (object))) - { - eq = method; - } - } - else if (method.Name.Equals("GetHashCode")) - { - ParameterInfo[] parameters = - method.GetParameters(); - - if (parameters.Length == 0) - { - hc = method; - } - } - }); + { + if (method.Name.Equals("Equals")) + { + ParameterInfo[] parameters = + method.GetParameters(); + + if ((parameters.Length == 1) && + (parameters[0].ParameterType == + typeof(object))) + { + eq = method; + } + } + else if (method.Name.Equals("GetHashCode")) + { + ParameterInfo[] parameters = + method.GetParameters(); + + if (parameters.Length == 0) + { + hc = method; + } + } + }); if (eq == null || hc == null) { throw new ActiveRecordException(String.Format("To use type '{0}' as a composite id, " + - "you must implement Equals and GetHashCode.", - model.Property.PropertyType.Name)); + "you must implement Equals and GetHashCode.", + model.Property.PropertyType.Name)); } if (compositeKeyClassType.IsSerializable == false) { throw new ActiveRecordException(String.Format("To use type '{0}' as a composite id " + - "it must be marked as Serializable.", model.Property.PropertyType.Name)); + "it must be marked as Serializable.", model.Property.PropertyType.Name)); } int keyPropAttrCount = 0; @@ -247,7 +247,7 @@ public override void VisitCompositePrimaryKey(CompositeKeyModel model) foreach (PropertyInfo keyProp in compositeKeyProps) { - if (keyProp.GetCustomAttributes(typeof (KeyPropertyAttribute), false).Length > 0) + if (keyProp.GetCustomAttributes(typeof(KeyPropertyAttribute), false).Length > 0) { keyPropAttrCount++; } @@ -256,8 +256,8 @@ public override void VisitCompositePrimaryKey(CompositeKeyModel model) if (keyPropAttrCount < 2) { throw new ActiveRecordException(String.Format("To use type '{0}' as a composite " + - "id it must have two or more properties marked with the [KeyProperty] attribute.", - model.Property.PropertyType.Name)); + "id it must have two or more properties marked with the [KeyProperty] attribute.", + model.Property.PropertyType.Name)); } } @@ -283,15 +283,15 @@ public override void VisitProperty(PropertyModel model) Type propertyType = model.Property.PropertyType; if (NHibernateNullablesSupport.IsNHibernateNullableType(propertyType) && - (model.PropertyAtt.ColumnType == null || model.PropertyAtt.ColumnType.Length == 0)) + (model.PropertyAtt.ColumnType == null || model.PropertyAtt.ColumnType.Length == 0)) { model.PropertyAtt.NotNull = false; model.PropertyAtt.ColumnType = NHibernateNullablesSupport.GetITypeTypeNameForNHibernateNullable(propertyType); } if (propertyType.IsGenericType && - propertyType.GetGenericTypeDefinition() == typeof (Nullable<>) && - String.IsNullOrEmpty(model.PropertyAtt.ColumnType)) + propertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && + String.IsNullOrEmpty(model.PropertyAtt.ColumnType)) { model.PropertyAtt.NotNull = false; model.PropertyAtt.ColumnType = ObtainNullableTypeNameForCLRNullable(propertyType); @@ -300,8 +300,8 @@ public override void VisitProperty(PropertyModel model) if (ActiveRecordModel.GetModel(propertyType) != null) { throw new ActiveRecordException(String.Format( - "You can't use [Property] on {0}.{1} because {2} is an active record class, did you mean to use BelongTo?", - model.Property.DeclaringType.Name, model.Property.Name, propertyType.FullName)); + "You can't use [Property] on {0}.{1} because {2} is an active record class, did you mean to use BelongTo?", + model.Property.DeclaringType.Name, model.Property.Name, propertyType.FullName)); } JoinedTableModel joinedTable = ObtainJoinedTableIfPresent(model.Property, model.PropertyAtt); @@ -332,14 +332,14 @@ public override void VisitField(FieldModel model) Type fieldType = model.Field.FieldType; if (NHibernateNullablesSupport.IsNHibernateNullableType(fieldType) && - (model.FieldAtt.ColumnType == null || model.FieldAtt.ColumnType.Length == 0)) + (model.FieldAtt.ColumnType == null || model.FieldAtt.ColumnType.Length == 0)) { model.FieldAtt.NotNull = false; model.FieldAtt.ColumnType = NHibernateNullablesSupport.GetITypeTypeNameForNHibernateNullable(fieldType); } - if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof (Nullable<>) && - String.IsNullOrEmpty(model.FieldAtt.ColumnType)) + if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>) && + String.IsNullOrEmpty(model.FieldAtt.ColumnType)) { model.FieldAtt.NotNull = false; model.FieldAtt.ColumnType = ObtainNullableTypeNameForCLRNullable(fieldType); @@ -420,7 +420,7 @@ public override void VisitBelongsTo(BelongsToModel model) if (currentModel.ActiveRecordAtt != null) { if (currentModel.ActiveRecordAtt.Lazy || - (currentModel.ActiveRecordAtt.LazySpecified == false && ActiveRecordModel.isLazyByDefault)) + (currentModel.ActiveRecordAtt.LazySpecified == false && ActiveRecordModel.isLazyByDefault)) { //Assuming that a property must have at least a single accessor MethodInfo accessor = model.Property.GetAccessors(true)[0]; @@ -429,8 +429,8 @@ public override void VisitBelongsTo(BelongsToModel model) { throw new ActiveRecordException( String.Format("Property {0} must be virtual because " + - "class {1} support lazy loading [ActiveRecord(Lazy=true)]", - model.Property.Name, model.Property.DeclaringType.Name)); + "class {1} support lazy loading [ActiveRecord(Lazy=true)]", + model.Property.Name, model.Property.DeclaringType.Name)); } } } @@ -542,15 +542,15 @@ public override void VisitHasMany(HasManyModel model) if (model.HasManyAtt.RelationType == RelationType.IdBag) { throw new ActiveRecordException(String.Format( - "You can't use idbags in a many to one association (HasMany) {0}.{1} ", - model.Property.DeclaringType.Name, model.Property.Name)); + "You can't use idbags in a many to one association (HasMany) {0}.{1} ", + model.Property.DeclaringType.Name, model.Property.Name)); } if (model.HasManyAtt.RelationType == RelationType.Map && model.HasManyAtt.Index == null) { throw new ActiveRecordException(String.Format( - "A HasMany with type Map requires that you specify an 'Index', use the Index property {0}.{1} ", - model.Property.DeclaringType.Name, model.Property.Name)); + "A HasMany with type Map requires that you specify an 'Index', use the Index property {0}.{1} ", + model.Property.DeclaringType.Name, model.Property.Name)); } if (model.HasManyAtt.RelationType == RelationType.List && model.HasManyAtt.Index == null) @@ -562,7 +562,7 @@ public override void VisitHasMany(HasManyModel model) // try to guess an mapping if none of the mapping properties was set if (model.HasManyAtt.MapType.IsValueType && string.IsNullOrEmpty(model.HasManyAtt.Element) && - model.HasManyAtt.ElementType == null && string.IsNullOrEmpty(model.HasManyAtt.ColumnKey)) + model.HasManyAtt.ElementType == null && string.IsNullOrEmpty(model.HasManyAtt.ColumnKey)) { GuessElementMappingBasedOnEnum(model); } @@ -580,9 +580,9 @@ public override void VisitHasMany(HasManyModel model) if ((table == null || (keyColumn == null && compositeKeyColumnKeys == null)) && target == null) { throw new ActiveRecordException(String.Format( - "ActiveRecord tried to infer details about the relation {0}.{1} but " + - "it could not find information about the specified target type {2}. If you have mapped a Collection or Dictionary of value types, please make sure you have specified the Table property.", - model.Property.DeclaringType.Name, model.Property.Name, type)); + "ActiveRecord tried to infer details about the relation {0}.{1} but " + + "it could not find information about the specified target type {2}. If you have mapped a Collection or Dictionary of value types, please make sure you have specified the Table property.", + model.Property.DeclaringType.Name, model.Property.Name, type)); } BelongsToModel targetBtModel = null; @@ -593,9 +593,9 @@ public override void VisitHasMany(HasManyModel model) foreach (BelongsToModel btModel in tmpModel.BelongsTo) { if (btModel.BelongsToAtt.Type != model.Property.DeclaringType && - btModel.BelongsToAtt.Type != model.ContainingTypeModel.Type && - btModel.Property.PropertyType != model.Property.DeclaringType && - btModel.Property.PropertyType != model.ContainingTypeModel.Type) continue; + btModel.BelongsToAtt.Type != model.ContainingTypeModel.Type && + btModel.Property.PropertyType != model.Property.DeclaringType && + btModel.Property.PropertyType != model.ContainingTypeModel.Type) continue; targetBtModel = btModel; break; } @@ -606,9 +606,9 @@ public override void VisitHasMany(HasManyModel model) if ((table == null || (keyColumn == null && compositeKeyColumnKeys == null)) && targetBtModel == null) { throw new ActiveRecordException(String.Format( - "ActiveRecord tried to infer details about the relation {0}.{1} but " + - "it could not find a 'BelongsTo' mapped property in the target type {2}", - model.Property.DeclaringType.Name, model.Property.Name, type)); + "ActiveRecord tried to infer details about the relation {0}.{1} but " + + "it could not find a 'BelongsTo' mapped property in the target type {2}", + model.Property.DeclaringType.Name, model.Property.Name, type)); } if (target != null) @@ -681,76 +681,76 @@ public override void VisitHasAndBelongsToMany(HasAndBelongsToManyModel model) if (model.HasManyAtt.Table == null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) we need that you " + - "specify the association table - {0}.{1} ", - currentModel.Type.Name, model.Property.Name)); + "For a many to many association (HasAndBelongsToMany) we need that you " + + "specify the association table - {0}.{1} ", + currentModel.Type.Name, model.Property.Name)); } if (model.HasManyAtt.ColumnKey == null && model.HasManyAtt.CompositeKeyColumnKeys == null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) we need that you " + - "specify the ColumnKey or CompositeKeyColumnKeys - which is the column(s) that represents the type {0} " + - "on the association table - {0}.{1} ", - currentModel.Type.Name, model.Property.Name)); + "For a many to many association (HasAndBelongsToMany) we need that you " + + "specify the ColumnKey or CompositeKeyColumnKeys - which is the column(s) that represents the type {0} " + + "on the association table - {0}.{1} ", + currentModel.Type.Name, model.Property.Name)); } if (model.HasManyAtt.ColumnKey != null && model.HasManyAtt.CompositeKeyColumnKeys != null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) there should only be " + - "a ColumnKey or an array of CompositeKeyColumnKeys, not both.")); + "For a many to many association (HasAndBelongsToMany) there should only be " + + "a ColumnKey or an array of CompositeKeyColumnKeys, not both.")); } if (model.HasManyAtt.CompositeKeyColumnKeys != null && model.HasManyAtt.CompositeKeyColumnKeys.Length < 2) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) with a CompositeKey, " + - "there must be at least two CompositeKeyColumnKeys - which are the columns that represent the type {0} " + - "on the association table - {0}.{1} ", - currentModel.Type.Name, model.Property.Name)); + "For a many to many association (HasAndBelongsToMany) with a CompositeKey, " + + "there must be at least two CompositeKeyColumnKeys - which are the columns that represent the type {0} " + + "on the association table - {0}.{1} ", + currentModel.Type.Name, model.Property.Name)); } if (model.HasManyAtt.RelationType != RelationType.IdBag && - model.HasManyAtt.ColumnRef == null && model.HasManyAtt.CompositeKeyColumnRefs == null) + model.HasManyAtt.ColumnRef == null && model.HasManyAtt.CompositeKeyColumnRefs == null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) we need that you " + - "specify the ColumnRef or CompositeKeyColumnRefs - which is the column(s) that represents the other end '{2}' " + - "on the association table - {0}.{1} ", - currentModel.Type.Name, model.Property.Name, otherend.Name)); + "For a many to many association (HasAndBelongsToMany) we need that you " + + "specify the ColumnRef or CompositeKeyColumnRefs - which is the column(s) that represents the other end '{2}' " + + "on the association table - {0}.{1} ", + currentModel.Type.Name, model.Property.Name, otherend.Name)); } if (model.HasManyAtt.ColumnRef != null && model.HasManyAtt.CompositeKeyColumnRefs != null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) there should only be " + - "a ColumnRef or an array of CompositeKeyColumnRefs, not both.")); + "For a many to many association (HasAndBelongsToMany) there should only be " + + "a ColumnRef or an array of CompositeKeyColumnRefs, not both.")); } if (model.HasManyAtt.CompositeKeyColumnRefs != null && model.HasManyAtt.CompositeKeyColumnRefs.Length < 2) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) with a CompositeKey, " + - "there must be at least two CompositeKeyColumnRefs - which are the columns that represent the other end '{2}' " + - "on the association table - {0}.{1} ", - currentModel.Type.Name, model.Property.Name, otherend.Name)); + "For a many to many association (HasAndBelongsToMany) with a CompositeKey, " + + "there must be at least two CompositeKeyColumnRefs - which are the columns that represent the other end '{2}' " + + "on the association table - {0}.{1} ", + currentModel.Type.Name, model.Property.Name, otherend.Name)); } if (model.HasManyAtt.RelationType == RelationType.IdBag && model.CollectionID == null) { throw new ActiveRecordException(String.Format( - "For a many to many association (HasAndBelongsToMany) using IDBag, you need " + - "to specify a CollectionIDAttribute giving us more details. " + - "{0}.{1} ", - currentModel.Type.Name, model.Property.Name)); + "For a many to many association (HasAndBelongsToMany) using IDBag, you need " + + "to specify a CollectionIDAttribute giving us more details. " + + "{0}.{1} ", + currentModel.Type.Name, model.Property.Name)); } if (model.HasManyAtt.RelationType == RelationType.Map && model.HasManyAtt.Index == null) { throw new ActiveRecordException(String.Format( - "A HasAndBelongsToMany with type Map requires that you specify an 'Index', use the Index property {0}.{1} ", - model.Property.DeclaringType.Name, model.Property.Name)); + "A HasAndBelongsToMany with type Map requires that you specify an 'Index', use the Index property {0}.{1} ", + model.Property.DeclaringType.Name, model.Property.Name)); } if (model.HasManyAtt.RelationType == RelationType.List && model.HasManyAtt.Index == null) @@ -859,39 +859,39 @@ private static RelationType GuessRelation(PropertyInfo property, RelationType ty if (!propertyType.IsInterface) { throw new ActiveRecordException(String.Format( - "Type of property {0}.{1} must be an interface (IList, ISet, IDictionary or their generic counter parts). You cannot use ArrayList or List as the property type.", - property.DeclaringType.Name, property.Name)); + "Type of property {0}.{1} must be an interface (IList, ISet, IDictionary or their generic counter parts). You cannot use ArrayList or List as the property type.", + property.DeclaringType.Name, property.Name)); } - if (propertyType == typeof (IList)) + if (propertyType == typeof(IList)) { return RelationType.Bag; } - else if (propertyType == typeof (IDictionary)) + else if (propertyType == typeof(IDictionary)) { return RelationType.Map; } else if (propertyType.IsGenericType) { Type genericTypeDefinition = propertyType.GetGenericTypeDefinition(); - if (genericTypeDefinition == typeof (IList<>) || - genericTypeDefinition == typeof (ICollection<>)) + if (genericTypeDefinition == typeof(IList<>) || + genericTypeDefinition == typeof(ICollection<>)) { return RelationType.Bag; } - else if (genericTypeDefinition == typeof (ISet<>)) + else if (genericTypeDefinition == typeof(ISet<>)) { return RelationType.Set; } - else if (genericTypeDefinition == typeof (IDictionary<,>)) + else if (genericTypeDefinition == typeof(IDictionary<,>)) { return RelationType.Map; } } throw new ActiveRecordException(String.Format( - "Could not guess relation type for property {0}.{1} ", - property.DeclaringType.Name, property.Name)); + "Could not guess relation type for property {0}.{1} ", + property.DeclaringType.Name, property.Name)); } private static void AssertHasValidKey(ActiveRecordModel model) @@ -920,12 +920,12 @@ private static void AssertHasValidKey(ActiveRecordModel model) if (tmpModel == null || tmpModel.PrimaryKey == null && tmpModel.CompositeKey == null) { throw new ActiveRecordException(String.Format( - "A type must declare a primary key. Check type {0}", model.Type.FullName)); + "A type must declare a primary key. Check type {0}", model.Type.FullName)); } } private JoinedTableModel ObtainJoinedTableIfPresent(MemberInfo propertyOrField, - WithAccessOptionalTableAttribute access) + WithAccessOptionalTableAttribute access) { String tableName = access.Table; @@ -936,7 +936,7 @@ private JoinedTableModel ObtainJoinedTableIfPresent(MemberInfo propertyOrField, { throw new ActiveRecordException( String.Format("{0} {1} references table \"{2}\" which is not allowed on nested types.", - propertyOrField is PropertyInfo ? "Property" : "Field", propertyOrField.Name, tableName)); + propertyOrField is PropertyInfo ? "Property" : "Field", propertyOrField.Name, tableName)); } if (tableName == String.Empty || tableName == currentModel.ActiveRecordAtt.Table) @@ -960,7 +960,7 @@ private JoinedTableModel ObtainJoinedTableIfPresent(MemberInfo propertyOrField, { throw new ActiveRecordException( String.Format("{0} {1} references table \"{2}\", which does not have a corresponding [JoinedTable] on the class.", - propertyOrField is PropertyInfo ? "Property" : "Field", propertyOrField.Name, tableName)); + propertyOrField is PropertyInfo ? "Property" : "Field", propertyOrField.Name, tableName)); } return joinedTable; @@ -985,7 +985,7 @@ public static Type GetIndexTypeFromDictionary(Type propertyType) if (propertyType.IsGenericType == false) throw new ArgumentException("The specified propertyType {0} is not generic", propertyType.Name); - if (typeof (IDictionary<,>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()) == false) + if (typeof(IDictionary<,>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()) == false) { throw new ArgumentException( "ActiveRecord tried to infer details about the mapped property {0} but this isn't of the expected IDictionary<,> type.", @@ -1009,7 +1009,7 @@ public static Type GetMapTypeFromDictionary(Type propertyType) if (propertyType.IsGenericType == false) throw new ArgumentException("The specified propertyType {0} is not generic", propertyType.Name); - if (typeof (IDictionary<,>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()) == false) + if (typeof(IDictionary<,>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()) == false) { throw new ArgumentException( "ActiveRecord tried to infer details about the mapped property {0} but this isn't of the expected IDictionary<,> type.", diff --git a/src/Castle.ActiveRecord/Framework/Queries/LinqQuery.cs b/src/Castle.ActiveRecord/Framework/Queries/LinqQuery.cs index f32d1a0..66d13b1 100644 --- a/src/Castle.ActiveRecord/Framework/Queries/LinqQuery.cs +++ b/src/Castle.ActiveRecord/Framework/Queries/LinqQuery.cs @@ -15,60 +15,60 @@ namespace Castle.ActiveRecord.Linq { - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq.Expressions; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq.Expressions; - using NHibernate; - using NHibernate.Engine; - using NHibernate.Linq; + using NHibernate; + using NHibernate.Engine; + using NHibernate.Linq; - /// - /// Linq Active Record Query - /// - public class LinqQuery : IActiveRecordQuery - { - private readonly Expression expression; - private readonly Type rootType; + /// + /// Linq Active Record Query + /// + public class LinqQuery : IActiveRecordQuery + { + private readonly Expression expression; + private readonly Type rootType; - /// - /// ctor - /// - /// - /// - public LinqQuery(Expression expression, Type rootType) - { - //this.options = options; - this.expression = expression; - this.rootType = rootType; - } + /// + /// ctor + /// + /// + /// + public LinqQuery(Expression expression, Type rootType) + { + //this.options = options; + this.expression = expression; + this.rootType = rootType; + } - /// - public Type RootType - { - get { return rootType; } - } + /// + public Type RootType + { + get { return rootType; } + } - /// - public List Result { get; private set; } + /// + public List Result { get; private set; } - /// - public object Execute(ISession session) - { - var result = new DefaultQueryProvider((ISessionImplementor)session).Execute(expression); - if (result is IEnumerable) - { - Result = new List(result as IEnumerable); - } + /// + public object Execute(ISession session) + { + var result = new DefaultQueryProvider((ISessionImplementor)session).Execute(expression); + if (result is IEnumerable) + { + Result = new List(result as IEnumerable); + } - return result; - } + return result; + } - /// - public IEnumerable Enumerate(ISession session) - { - return (IEnumerable)Execute(session); - } - } + /// + public IEnumerable Enumerate(ISession session) + { + return (IEnumerable)Execute(session); + } + } } diff --git a/src/Castle.ActiveRecord/Framework/SessionFactoryHolder.cs b/src/Castle.ActiveRecord/Framework/SessionFactoryHolder.cs index 10040d7..a0bd7d9 100644 --- a/src/Castle.ActiveRecord/Framework/SessionFactoryHolder.cs +++ b/src/Castle.ActiveRecord/Framework/SessionFactoryHolder.cs @@ -14,21 +14,21 @@ namespace Castle.ActiveRecord.Framework { - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Runtime.CompilerServices; - using System.Threading; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading; - using Castle.ActiveRecord.Framework.Scopes; + using Castle.ActiveRecord.Framework.Scopes; - using Iesi.Collections; + using Iesi.Collections; - using NHibernate; - using NHibernate.Cfg; + using NHibernate; + using NHibernate.Cfg; - /// + /// /// Default implementation of /// /// @@ -74,7 +74,7 @@ public Configuration GetConfiguration(Type type) /// public Configuration[] GetAllConfigurations() { - ISet set = new HashSet(type2Conf.Values.Cast()); + ISet set = new HashSet(type2Conf.Values.Cast()); Configuration[] confs = new Configuration[set.Count]; @@ -91,7 +91,7 @@ public ISessionFactory[] GetSessionFactories() { List factories = new List(); - foreach(ISessionFactory factory in type2SessFactory.Values) + foreach (ISessionFactory factory in type2SessFactory.Values) { factories.Add(factory); } @@ -165,11 +165,11 @@ public void RegisterSessionFactory(ISessionFactory sessionFactory, Type baseType { readerWriterLock.AcquireWriterLock(-1); - try + try { type2SessFactory[baseType] = sessionFactory; } - finally + finally { readerWriterLock.ReleaseWriterLock(); } @@ -200,7 +200,7 @@ public ISession CreateSession(Type type) /// public Type GetRootType(Type type) { - while(type != typeof(object)) + while (type != typeof(object)) { if (type2Conf.ContainsKey(type)) { @@ -236,7 +236,7 @@ public Type GetRootType(Type type) private static ISession OpenSession(ISessionFactory sessionFactory) { - lock(sessionFactory) + lock (sessionFactory) { return sessionFactory.OpenSession(InterceptorFactory.Create()); } @@ -244,7 +244,7 @@ private static ISession OpenSession(ISessionFactory sessionFactory) internal static ISession OpenSessionWithScope(ISessionScope scope, ISessionFactory sessionFactory) { - lock(sessionFactory) + lock (sessionFactory) { return scope.OpenSession(sessionFactory, InterceptorFactory.Create()); } diff --git a/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs b/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs index 522fe1e..8f8984f 100644 --- a/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs +++ b/src/Castle.ActiveRecord/Framework/StatelessSessionWrapper.cs @@ -37,12 +37,12 @@ public class StatelessSessionWrapper : ISession public StatelessSessionWrapper(IStatelessSession statelessSession) { this.statelessSession = statelessSession; - this.statelessSession.SetBatchSize(1); + this.statelessSession.SetBatchSize(1); } #pragma warning disable 1591 - public System.Data.IDbConnection Connection + public System.Data.IDbConnection Connection { get { return statelessSession.Connection; } } @@ -73,7 +73,7 @@ public System.Data.IDbConnection Close() statelessSession.Close(); return null; } - + public ICriteria CreateCriteria(string entityName, string alias) { return statelessSession.CreateCriteria(entityName, alias); @@ -116,31 +116,31 @@ public IQueryOver QueryOver(System.Linq.Expressions.Expression> return statelessSession.QueryOver(alias); } - /// - /// Creates a new IQueryOver{T}; for the entity class. - /// - /// The entity classThe name of the entity to Query - /// - /// An IQueryOver{T} object - /// - public IQueryOver QueryOver(string entityName) where T : class - { - throw new NotImplementedException(); - } - - /// - /// Creates a new IQueryOver{T} for the entity class. - /// - /// The entity classThe name of the entity to QueryThe alias of the entity - /// - /// An IQueryOver{T} object - /// - public IQueryOver QueryOver(string entityName, Expression> alias) where T : class - { - throw new NotImplementedException(); - } - - public IQuery CreateQuery(string queryString) + /// + /// Creates a new IQueryOver{T}; for the entity class. + /// + /// The entity classThe name of the entity to Query + /// + /// An IQueryOver{T} object + /// + public IQueryOver QueryOver(string entityName) where T : class + { + throw new NotImplementedException(); + } + + /// + /// Creates a new IQueryOver{T} for the entity class. + /// + /// The entity classThe name of the entity to QueryThe alias of the entity + /// + /// An IQueryOver{T} object + /// + public IQueryOver QueryOver(string entityName, Expression> alias) where T : class + { + throw new NotImplementedException(); + } + + public IQuery CreateQuery(string queryString) { return statelessSession.CreateQuery(queryString); } @@ -177,7 +177,7 @@ public T Get(object id, LockMode lockMode) public T Get(object id) { - return (T)statelessSession.Get(typeof(T).FullName,id); + return (T)statelessSession.Get(typeof(T).FullName, id); } public object Get(string entityName, object id) @@ -235,20 +235,20 @@ public object Save(string entityName, object obj) return statelessSession.Insert(entityName, obj); } - /// - /// Persist the given transient instance, using the given identifier. - /// - /// The Entity name.a transient instance of a persistent class An unused valid identifier - /// - /// This operation cascades to associated instances if the - /// association is mapped with cascade="save-update". - /// - public void Save(string entityName, object obj, object id) - { - statelessSession.Update(entityName, obj); - } + /// + /// Persist the given transient instance, using the given identifier. + /// + /// The Entity name.a transient instance of a persistent class An unused valid identifier + /// + /// This operation cascades to associated instances if the + /// association is mapped with cascade="save-update". + /// + public void Save(string entityName, object obj, object id) + { + statelessSession.Update(entityName, obj); + } - public object Save(object obj) + public object Save(object obj) { return statelessSession.Insert(obj); } @@ -258,40 +258,40 @@ public void Update(string entityName, object obj) statelessSession.Update(entityName, obj); } - /// - /// Update the persistent instance associated with the given identifier. - /// - /// The Entity name.a detached instance containing updated state Identifier of persistent instance - /// - /// If there is a persistent instance with the same identifier, - /// an exception is thrown. This operation cascades to associated instances - /// if the association is mapped with cascade="save-update". - /// - public void Update(string entityName, object obj, object id) - { - statelessSession.Update(entityName, obj); - } - - /// - /// Either Save() or Update() the given instance, depending upon the value of - /// its identifier property. - /// - /// - /// By default the instance is always saved. This behaviour may be adjusted by specifying - /// an unsaved-value attribute of the identifier property mapping - /// - /// The name of the entityA transient instance containing new or updated stateIdentifier of persistent instance - public void SaveOrUpdate(string entityName, object obj, object id) - { - statelessSession.Update(entityName, obj); - } - - public void Update(object obj) + /// + /// Update the persistent instance associated with the given identifier. + /// + /// The Entity name.a detached instance containing updated state Identifier of persistent instance + /// + /// If there is a persistent instance with the same identifier, + /// an exception is thrown. This operation cascades to associated instances + /// if the association is mapped with cascade="save-update". + /// + public void Update(string entityName, object obj, object id) + { + statelessSession.Update(entityName, obj); + } + + /// + /// Either Save() or Update() the given instance, depending upon the value of + /// its identifier property. + /// + /// + /// By default the instance is always saved. This behaviour may be adjusted by specifying + /// an unsaved-value attribute of the identifier property mapping + /// + /// The name of the entityA transient instance containing new or updated stateIdentifier of persistent instance + public void SaveOrUpdate(string entityName, object obj, object id) + { + statelessSession.Update(entityName, obj); + } + + public void Update(object obj) { statelessSession.Update(obj); } - public EntityMode ActiveEntityMode + public EntityMode ActiveEntityMode { get { throw new NotWrappedException(); } } @@ -435,7 +435,7 @@ public System.Collections.IList Find(string query) public void Flush() { - throw new NotWrappedException(); + throw new NotWrappedException(); } public FlushMode FlushMode @@ -515,46 +515,46 @@ public object Merge(string entityName, object obj) throw new NotWrappedException(); } - /// - /// Copy the state of the given object onto the persistent object with the same - /// identifier. If there is no persistent instance currently associated with - /// the session, it will be loaded. Return the persistent instance. If the - /// given instance is unsaved, save a copy of and return it as a newly persistent - /// instance. The given instance does not become associated with the session. - /// This operation cascades to associated instances if the association is mapped - /// with cascade="merge".
- /// The semantics of this method are defined by JSR-220. - ///
- /// a detached instance with state to be copied - /// - /// an updated persistent instance - /// - public T Merge(T entity) where T : class - { - throw new NotWrappedException(); - } - - /// - /// Copy the state of the given object onto the persistent object with the same - /// identifier. If there is no persistent instance currently associated with - /// the session, it will be loaded. Return the persistent instance. If the - /// given instance is unsaved, save a copy of and return it as a newly persistent - /// instance. The given instance does not become associated with the session. - /// This operation cascades to associated instances if the association is mapped - /// with cascade="merge".
- /// The semantics of this method are defined by JSR-220. - /// Name of the entity.a detached instance with state to be copied - /// - /// an updated persistent instance - /// - ///
- /// - public T Merge(string entityName, T entity) where T : class - { - return null; - } - - public object Merge(object obj) + /// + /// Copy the state of the given object onto the persistent object with the same + /// identifier. If there is no persistent instance currently associated with + /// the session, it will be loaded. Return the persistent instance. If the + /// given instance is unsaved, save a copy of and return it as a newly persistent + /// instance. The given instance does not become associated with the session. + /// This operation cascades to associated instances if the association is mapped + /// with cascade="merge".
+ /// The semantics of this method are defined by JSR-220. + ///
+ /// a detached instance with state to be copied + /// + /// an updated persistent instance + /// + public T Merge(T entity) where T : class + { + throw new NotWrappedException(); + } + + /// + /// Copy the state of the given object onto the persistent object with the same + /// identifier. If there is no persistent instance currently associated with + /// the session, it will be loaded. Return the persistent instance. If the + /// given instance is unsaved, save a copy of and return it as a newly persistent + /// instance. The given instance does not become associated with the session. + /// This operation cascades to associated instances if the association is mapped + /// with cascade="merge".
+ /// The semantics of this method are defined by JSR-220. + /// Name of the entity.a detached instance with state to be copied + /// + /// an updated persistent instance + /// + ///
+ /// + public T Merge(string entityName, T entity) where T : class + { + return null; + } + + public object Merge(object obj) { throw new NotWrappedException(); } @@ -631,7 +631,7 @@ public ISessionFactory SessionFactory public ISession SetBatchSize(int batchSize) { - throw new NotWrappedException(); + throw new NotWrappedException(); } public NHibernate.Stat.ISessionStatistics Statistics @@ -656,7 +656,7 @@ public IQueryOver QueryOver() where T : class throw new NotWrappedException(); } - public void Dispose() + public void Dispose() { statelessSession.Dispose(); } diff --git a/src/Castle.ActiveRecord/Framework/SupportingUtils.cs b/src/Castle.ActiveRecord/Framework/SupportingUtils.cs index 47ef6f6..cbc0936 100644 --- a/src/Castle.ActiveRecord/Framework/SupportingUtils.cs +++ b/src/Castle.ActiveRecord/Framework/SupportingUtils.cs @@ -1,16 +1,10 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright(C)2013 -// -// -// -------------------------------------------------------------------------------------------------------------------- namespace Castle.ActiveRecord.Framework { - using System; - using System.Collections; - using System.Collections.Generic; + using System; + using System.Collections; + using System.Collections.Generic; - /// + /// /// Contains utility methods for dealing with ActiveRecord objects /// and collections. /// Useful for external frameworks. @@ -60,7 +54,7 @@ public static Array BuildArray(Type targetType, IList list) return array; } - + /// /// Converts the results stored in an to an @@ -95,15 +89,15 @@ public static Array BuildArray(Type type, IEnumerable list, int entityIndex, boo // entityIndex was specified, or if distinct was chosen. if (distinct || entityIndex != -1) { - ISet set = distinct ? new HashSet() : null; + ISet set = distinct ? new HashSet() : null; ICollection collection = list as ICollection; IList newList = collection != null ? new ArrayList(collection.Count) : new ArrayList(); - foreach(object item in list) + foreach (object item in list) { - object el = entityIndex == -1 ? item : ((object[]) item)[entityIndex]; + object el = entityIndex == -1 ? item : ((object[])item)[entityIndex]; if (set == null || set.Add(el)) { @@ -120,7 +114,7 @@ public static Array BuildArray(Type type, IEnumerable list, int entityIndex, boo { ArrayList newList = new ArrayList(); - foreach(object item in list) + foreach (object item in list) { newList.Add(item); } @@ -155,14 +149,14 @@ public static Array BuildObjectArray(Type type, IEnumerable list, bool distinct) { // we only need to perform an additional processing if // distinct was chosen. - ISet set = distinct ? new HashSet() : null; + ISet set = distinct ? new HashSet() : null; ICollection coll = list as ICollection; IList newList = coll != null ? new ArrayList(coll.Count) : new ArrayList(); - foreach(object item in list) + foreach (object item in list) { - object[] p = item is object[] ? (object[]) item : new[] {item}; + object[] p = item is object[] ? (object[])item : new[] { item }; object el = Activator.CreateInstance(type, p); if (set == null || set.Add(el)) @@ -190,7 +184,7 @@ public static Array BuildObjectArray(Type type, IEnumerable list, bool distinct) /// The strongly-typed array public static T[] BuildObjectArray(IEnumerable list, bool distinct) { - return (T[]) BuildObjectArray(typeof(T), list, distinct); + return (T[])BuildObjectArray(typeof(T), list, distinct); } #endregion @@ -212,7 +206,7 @@ public static T[] BuildObjectArray(IEnumerable list, bool distinct) /// A good alternative is to use the new public static T[] BuildArray(IEnumerable list, bool distinct) { - return (T[]) BuildArray(typeof(T), list, distinct); + return (T[])BuildArray(typeof(T), list, distinct); } /// @@ -229,10 +223,10 @@ public static T[] BuildArray(IEnumerable list, bool distinct) /// /// If true, only distinct results will be inserted in the array /// The strongly-typed array - + public static T[] BuildArray(IEnumerable list, int? entityIndex, bool distinct) { - return (T[]) BuildArray(typeof(T), list, entityIndex ?? -1, distinct); + return (T[])BuildArray(typeof(T), list, entityIndex ?? -1, distinct); } #endregion