diff --git a/.gitignore b/.gitignore index 6fe6ac4255e..8b005b7869f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ current-test-configuration # to satisfy later build steps. But it should not be committed. NHibernate.dll TestResult.xml +/src/packages +*.lock.json diff --git a/Tools/.gitignore b/Tools/.gitignore index 8ebf927cc77..86eae47e70a 100644 --- a/Tools/.gitignore +++ b/Tools/.gitignore @@ -1,2 +1,3 @@ nuget.exe NUnit.* +vswhere.* diff --git a/Tools/msbuild.cmd b/Tools/msbuild.cmd new file mode 100644 index 00000000000..abdbb860dde --- /dev/null +++ b/Tools/msbuild.cmd @@ -0,0 +1,15 @@ +@echo off +set MSBuildSDKsPath="C:\Program Files\dotnet\sdk\1.0.1\Sdks" + +set pre=Microsoft.VisualStudio.Product. +set ids=%pre%Community %pre%Professional %pre%Enterprise %pre%BuildTools + +for /f "usebackq tokens=1* delims=: " %%i in (`%~dp0\vswhere.1.0.58\tools\vswhere.exe -latest -products %ids% -requires Microsoft.Component.MSBuild`) do ( + if /i "%%i"=="installationPath" set InstallDir=%%j +) + +if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( + "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" %* +) else ( + exit /b -1 +) diff --git a/Tools/packages.config b/Tools/packages.config index 49fb637eba4..eef69aeea20 100644 --- a/Tools/packages.config +++ b/Tools/packages.config @@ -7,4 +7,5 @@ - \ No newline at end of file + + diff --git a/build-common/common-project.xml b/build-common/common-project.xml index e51353f4233..e352fd79a48 100644 --- a/build-common/common-project.xml +++ b/build-common/common-project.xml @@ -64,9 +64,7 @@ - - - + diff --git a/src/NHibernate.DomainModel/Compat/NonSerializedAttribute.cs b/src/NHibernate.DomainModel/Compat/NonSerializedAttribute.cs new file mode 100644 index 00000000000..05107a66013 --- /dev/null +++ b/src/NHibernate.DomainModel/Compat/NonSerializedAttribute.cs @@ -0,0 +1,10 @@ +#if !FEATURE_SERIALIZATION && NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System +{ + [AttributeUsage(AttributeTargets.Field, Inherited = false)] + internal sealed class NonSerializedAttribute : Attribute + { + } +} +#endif diff --git a/src/NHibernate.DomainModel/Compat/SerializableAttribute.cs b/src/NHibernate.DomainModel/Compat/SerializableAttribute.cs new file mode 100644 index 00000000000..e12a812f14f --- /dev/null +++ b/src/NHibernate.DomainModel/Compat/SerializableAttribute.cs @@ -0,0 +1,10 @@ +#if !FEATURE_SERIALIZATION && NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] + internal sealed class SerializableAttribute : Attribute + { + } +} +#endif diff --git a/src/NHibernate.DomainModel/Foo.cs b/src/NHibernate.DomainModel/Foo.cs index f82739b89a1..d1d9fef1689 100644 --- a/src/NHibernate.DomainModel/Foo.cs +++ b/src/NHibernate.DomainModel/Foo.cs @@ -368,7 +368,11 @@ public LifecycleVeto OnSave(ISession s) _component.Glarch = new Glarch(); _dependent = new Fee(); _dependent.Fi = "belongs to foo # " + Key; +#if !NETSTANDARD _locale = Thread.CurrentThread.CurrentCulture; +#else + _locale = CultureInfo.CurrentCulture; +#endif return LifecycleVeto.NoVeto; } diff --git a/src/NHibernate.DomainModel/Master.cs b/src/NHibernate.DomainModel/Master.cs index 1a57ca765cc..307582133ba 100644 --- a/src/NHibernate.DomainModel/Master.cs +++ b/src/NHibernate.DomainModel/Master.cs @@ -45,7 +45,9 @@ public ISet Details get { return _details; } set { +#if !NETSTANDARD Trace.WriteLine("Details assigned"); +#endif _details = value; } } diff --git a/src/NHibernate.DomainModel/NHSpecific/NullableInt32.cs b/src/NHibernate.DomainModel/NHSpecific/NullableInt32.cs index b0e0eea2a93..eb468360265 100644 --- a/src/NHibernate.DomainModel/NHSpecific/NullableInt32.cs +++ b/src/NHibernate.DomainModel/NHSpecific/NullableInt32.cs @@ -6,7 +6,10 @@ namespace NHibernate.DomainModel.NHSpecific /// /// A nullable type that wraps an value. /// - [TypeConverter(typeof(NullableInt32Converter)), Serializable()] +#if !NETSTANDARD + [TypeConverter(typeof(NullableInt32Converter))] +#endif + [Serializable] public struct NullableInt32 : IFormattable, IComparable { public static readonly NullableInt32 Default = new NullableInt32(); diff --git a/src/NHibernate.DomainModel/NHSpecific/NullableInt32Converter.cs b/src/NHibernate.DomainModel/NHSpecific/NullableInt32Converter.cs index 4075faa8416..fd8c2424a19 100644 --- a/src/NHibernate.DomainModel/NHSpecific/NullableInt32Converter.cs +++ b/src/NHibernate.DomainModel/NHSpecific/NullableInt32Converter.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD using System; using System.Collections; using System.ComponentModel; @@ -96,4 +97,5 @@ public override bool GetPropertiesSupported(ITypeDescriptorContext context) return true; } } -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/src/NHibernate.DomainModel/NHibernate.DomainModel.csproj b/src/NHibernate.DomainModel/NHibernate.DomainModel.csproj index 6cf42823c26..9029ea60eaa 100644 --- a/src/NHibernate.DomainModel/NHibernate.DomainModel.csproj +++ b/src/NHibernate.DomainModel/NHibernate.DomainModel.csproj @@ -1,316 +1,67 @@ - - + + - Debug - AnyCPU - 9.0.30729 - 2.0 - {5C649B55-1B3F-4C38-9998-1B043E94A244} - Library - Properties - NHibernate.DomainModel + net461;netstandard1.6 NHibernate.DomainModel - - - 3.5 - - - v4.6.1 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - + NHibernate.DomainModel + $(PackageTargetFallback);dnxcore50;portable-net45+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1;portable-net45+wpa81+wp80+win + 1.6.1 + $(PackageTargetFallback);portable-net45+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1;portable-net45+wpa81+wp80+win + false + false + false + false + false - - true - full - false - bin\Debug-2.0\ - obj\ - obj\Debug-2.0\ - TRACE;DEBUG;NET,NET_2_0 - prompt - 4 - AllRules.ruleset - false + + + $(DefineConstants);NETSTANDARD;FEATURE_DATA_GETCOLUMNSCHEMA;FEATURE_INTERNALIZE_IESI;FEATURE_NETCORE_ICLONEABLE_API;FEATURE_NETCORE_REFLECTION_API - - pdbonly - true - bin\Release-2.0\ - obj\ - obj\Release-2.0\ - TRACE - prompt - 4 - AllRules.ruleset - false + + + $(DefineConstants);NET_4_0;FEATURE_ADONET_SQLCOMMANDSET;FEATURE_APPDOMAIN;FEATURE_ASSEMBLYBUILDER_SAVE;FEATURE_BINDINGLIST;FEATURE_CODEDOM;FEATURE_DATA_CLOSE;FEATURE_DATA_GETSCHEMATABLE;FEATURE_DBPROVIDERFACTORIES;FEATURE_ODBC_OLEDB;FEATURE_REFLECTEDTYPE;FEATURE_REMOTING;FEATURE_SECURITY_PERMISSIONS;FEATURE_SERIALIZATION;FEATURE_STRING_INTERN;FEATURE_SYSTEM_CONFIGURATION;FEATURE_SYSTEM_SERVICEMODEL;FEATURE_SYSTEM_TRANSACTIONS;FEATURE_WEB_SESSION_CONTEXT;FEATURE_XML_SCHEMAS;FEATURE_XML_VALIDATIONEVENTHANDLER + - - ..\packages\Iesi.Collections.4.0.1.4000\lib\net40\Iesi.Collections.dll - True - - - - 3.5 - - - - - - - SharedAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - {5909BFE7-93CF-4E5F-BE22-6293368AF01D} - NHibernate - + - - - - - - - - - + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + - + - - - \ No newline at end of file + + diff --git a/src/NHibernate.Everything.sln b/src/NHibernate.Everything.sln index efa754ea293..c63018d33bc 100644 --- a/src/NHibernate.Everything.sln +++ b/src/NHibernate.Everything.sln @@ -1,7 +1,7 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26114.2 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Support", "Support", "{9BDB5C84-14EC-4384-B423-9E319675B3CA}" ProjectSection(FolderStartupServices) = postProject @@ -97,6 +97,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AssemblyInfo", "AssemblyInf SharedAssemblyInfo.cs = SharedAssemblyInfo.cs EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NHibernate", "NHibernate", "{A894DB23-2F62-454A-8A98-E95856EE44D2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "backup", "NHibernate\backup\backup.csproj", "{916E69DF-190C-4D84-A249-93803E04387B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|.NET = Debug|.NET @@ -105,6 +109,10 @@ Global Release|.NET = Release|.NET Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5909BFE7-93CF-4E5F-BE22-6293368AF01D}.Debug|.NET.ActiveCfg = Debug|Any CPU @@ -166,6 +174,18 @@ Global {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Release|Any CPU.Build.0 = Release|Any CPU {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|x64.ActiveCfg = Debug|x64 + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|x64.Build.0 = Debug|x64 + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|x86.ActiveCfg = Debug|x86 + {916E69DF-190C-4D84-A249-93803E04387B}.Debug|x86.Build.0 = Debug|x86 + {916E69DF-190C-4D84-A249-93803E04387B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {916E69DF-190C-4D84-A249-93803E04387B}.Release|Any CPU.Build.0 = Release|Any CPU + {916E69DF-190C-4D84-A249-93803E04387B}.Release|x64.ActiveCfg = Release|x64 + {916E69DF-190C-4D84-A249-93803E04387B}.Release|x64.Build.0 = Release|x64 + {916E69DF-190C-4D84-A249-93803E04387B}.Release|x86.ActiveCfg = Release|x86 + {916E69DF-190C-4D84-A249-93803E04387B}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -173,15 +193,12 @@ Global GlobalSection(NestedProjects) = preSolution {094F74CD-2DD7-496F-BC48-A6D357BF33FD} = {28EA2C84-8295-49ED-BC67-803B7778513E} {92509065-DAEA-4457-8300-C7B64CD0E9F4} = {28EA2C84-8295-49ED-BC67-803B7778513E} - {4CE16C2F-EFF6-48A4-99BC-8984DCC143FA} = {9BDB5C84-14EC-4384-B423-9E319675B3CA} - {1631B0BA-59AC-4F0D-B300-3F64CC7579C9} = {9BDB5C84-14EC-4384-B423-9E319675B3CA} - {936E50BD-4027-4864-ADE9-423C3FBF7FFB} = {9BDB5C84-14EC-4384-B423-9E319675B3CA} {5909BFE7-93CF-4E5F-BE22-6293368AF01D} = {094F74CD-2DD7-496F-BC48-A6D357BF33FD} {5C649B55-1B3F-4C38-9998-1B043E94A244} = {094F74CD-2DD7-496F-BC48-A6D357BF33FD} {7AEE5B37-C552-4E59-9B6F-88755BCB5070} = {094F74CD-2DD7-496F-BC48-A6D357BF33FD} {446E148D-A9D5-4D7D-A706-BEDD45B2BC7D} = {92509065-DAEA-4457-8300-C7B64CD0E9F4} {7C2EF610-BCA0-4D1F-898A-DE9908E4970C} = {094F74CD-2DD7-496F-BC48-A6D357BF33FD} - {00C03FBC-6720-4917-A203-DEA12FF3C7BF} = {9BDB5C84-14EC-4384-B423-9E319675B3CA} + {916E69DF-190C-4D84-A249-93803E04387B} = {A894DB23-2F62-454A-8A98-E95856EE44D2} EndGlobalSection GlobalSection(TextTemplating) = postSolution TextTemplating = 1 diff --git a/src/NHibernate.Test.VisualBasic/AssemblyInfo.vb b/src/NHibernate.Test.VisualBasic/AssemblyInfo.vb deleted file mode 100644 index 590f5a4f87c..00000000000 --- a/src/NHibernate.Test.VisualBasic/AssemblyInfo.vb +++ /dev/null @@ -1,3 +0,0 @@ -Imports NUnit.Framework - - \ No newline at end of file diff --git a/src/NHibernate.Test.VisualBasic/My Project/AssemblyInfo.vb b/src/NHibernate.Test.VisualBasic/My Project/AssemblyInfo.vb index a847091c921..faa706016f3 100644 --- a/src/NHibernate.Test.VisualBasic/My Project/AssemblyInfo.vb +++ b/src/NHibernate.Test.VisualBasic/My Project/AssemblyInfo.vb @@ -1,34 +1,36 @@ Imports System Imports System.Reflection Imports System.Runtime.InteropServices +Imports NUnit.Framework -' General Information about an assembly is controlled through the following +' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes - - - - - - + + + + + + 'The following GUID is for the ID of the typelib if this project is exposed to COM - + ' Version information for an assembly consists of the following four values: ' ' Major Version -' Minor Version +' Minor Version ' Build Number ' Revision ' -' You can specify all the values or you can default the Build and Revision Numbers +' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: -' +' + \ No newline at end of file diff --git a/src/NHibernate.Test.VisualBasic/My Project/Settings.Designer.vb b/src/NHibernate.Test.VisualBasic/My Project/Settings.Designer.vb index 2886e192c3b..79773042b6d 100644 --- a/src/NHibernate.Test.VisualBasic/My Project/Settings.Designer.vb +++ b/src/NHibernate.Test.VisualBasic/My Project/Settings.Designer.vb @@ -15,7 +15,7 @@ Option Explicit On Namespace My _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase @@ -29,7 +29,7 @@ Namespace My Private Shared addedHandlerLockObject As New Object _ - Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If diff --git a/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj b/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj index f7deb7d8f33..10b866510ce 100644 --- a/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj +++ b/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj @@ -1,23 +1,16 @@  - + + Debug AnyCPU - - - - - {7C2EF610-BCA0-4D1F-898A-DE9908E4970C} + {F43B3253-9011-4DAE-8777-BA0D8DA850A6} Library NHibernate.Test.VisualBasic NHibernate.Test.VisualBasic 512 Windows v4.6.1 - - Program - $(MSBuildProjectDirectory)\..\..\Tools\nunit\nunit-x86.exe - NHibernate.Test.VisualBasic.dll true @@ -27,7 +20,6 @@ bin\Debug\ NHibernate.Test.VisualBasic.xml 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - false pdbonly @@ -37,7 +29,6 @@ bin\Release\ NHibernate.Test.VisualBasic.xml 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - false On @@ -52,9 +43,8 @@ On - - ..\packages\NUnit.3.6.0\lib\net45\nunit.framework.dll - True + + ..\packages\NUnit.3.6.1\lib\net45\nunit.framework.dll @@ -77,19 +67,18 @@ SharedAssemblyInfo.vb - - - - - - - + - - + + + + + + + True @@ -115,10 +104,6 @@ - - App.config - Designer - MyApplicationCodeGenerator Application.Designer.vb @@ -130,32 +115,21 @@ + + + + + + - {7AEE5B37-C552-4E59-9B6F-88755BCB5070} + {1b7e9512-5b0f-45be-82ad-5ebda404bde3} NHibernate.Test - {5909BFE7-93CF-4E5F-BE22-6293368AF01D} + {d39e4139-6011-4db2-837e-20c9be221b9c} NHibernate - - - - - - - - - - - \ No newline at end of file diff --git a/src/NHibernate.Test.VisualBasic/packages.config b/src/NHibernate.Test.VisualBasic/packages.config index 1261b7bcffd..4b26cc06617 100644 --- a/src/NHibernate.Test.VisualBasic/packages.config +++ b/src/NHibernate.Test.VisualBasic/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/NHibernate.Test/Any/AnyTypeTest.cs b/src/NHibernate.Test/Any/AnyTypeTest.cs index d40544ab5e3..bd79668424a 100644 --- a/src/NHibernate.Test/Any/AnyTypeTest.cs +++ b/src/NHibernate.Test/Any/AnyTypeTest.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System.Collections; using NUnit.Framework; @@ -50,4 +52,6 @@ public void FlushProcessing() session.Close(); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/CfgTest/ConfigurationSerializationTests.cs b/src/NHibernate.Test/CfgTest/ConfigurationSerializationTests.cs index 7374d70f3c2..b86d82ecf2b 100644 --- a/src/NHibernate.Test/CfgTest/ConfigurationSerializationTests.cs +++ b/src/NHibernate.Test/CfgTest/ConfigurationSerializationTests.cs @@ -1,4 +1,6 @@ -using System.IO; +#if FEATURE_SERIALIZATION + +using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Cfg; @@ -20,7 +22,7 @@ public void Configuration_should_be_serializable() [Test] public void Basic_CRUD_should_work() { - Assembly assembly = Assembly.Load("NHibernate.DomainModel"); + Assembly assembly = Assembly.Load(new AssemblyName("NHibernate.DomainModel")); var cfg = new Configuration(); if (TestConfigurationHelper.hibernateConfigFile != null) { @@ -86,4 +88,6 @@ public void Basic_CRUD_should_work() export.Drop(true, true); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/CfgTest/MappingDocumentAggregatorTests.cs b/src/NHibernate.Test/CfgTest/MappingDocumentAggregatorTests.cs index b10c75e31a5..12a4eb534f4 100644 --- a/src/NHibernate.Test/CfgTest/MappingDocumentAggregatorTests.cs +++ b/src/NHibernate.Test/CfgTest/MappingDocumentAggregatorTests.cs @@ -3,12 +3,15 @@ using System.Diagnostics; using System.IO; using System.Reflection; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Cfg.MappingSchema; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.CfgTest { [TestFixture] @@ -25,6 +28,7 @@ public void CanAddDomainModelAssembly() Assert.IsTrue(results.Count > 0); // 54 } +#if FEATURE_SERIALIZATION [Test] public void CanSerializeAndDeserializeDomainModelAssembly() { @@ -104,5 +108,6 @@ public void CompareDeserializationTimes() Console.WriteLine(); } } +#endif } } diff --git a/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs b/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs index 1fb7735f136..2239bf8f3ab 100644 --- a/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs +++ b/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs @@ -43,6 +43,7 @@ protected override void Done() // Some additional tests specifically for the aggressive-Release functionality... +#if FEATURE_SERIALIZATION [Test] public void SerializationOnAfterStatementAggressiveRelease() { @@ -103,6 +104,7 @@ public void SerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources Release(s); Done(); } +#endif [Test] public void QueryIteration() @@ -245,4 +247,4 @@ public void ConnectionMaintanenceDuringFlush() Done(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs b/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs index 22aeefc4d76..aecc6690561 100644 --- a/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs +++ b/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs @@ -452,6 +452,7 @@ public void CloningCriteria_AddCount_RemoveOrdering() s.Close(); } +#if FEATURE_SERIALIZATION [Test] public void DetachedCriteriaTest() { @@ -489,6 +490,7 @@ public void DetachedCriteriaTest() t.Commit(); session.Close(); } +#endif [Test] public void SubqueryPaginationOnlyWithFirst() @@ -3006,4 +3008,4 @@ public void CanSetLockModeOnDetachedCriteria() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs b/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs index e41eba37c1b..2b9875b9ad9 100644 --- a/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs +++ b/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.Collections; using NHibernate.Criterion; @@ -421,4 +423,6 @@ public void ExecutableCriteria() SerializeAndList(dc); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs b/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs index 6471c480301..1194d2ccce6 100644 --- a/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs +++ b/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs @@ -285,8 +285,8 @@ public void FunctionExtensions() .Add(Restrictions.Eq(Projections.SqlFunction("bit_length", NHibernateUtil.String, Projections.Property("Name")), 32)) .Add(Restrictions.Eq(Projections.SqlFunction("substring", NHibernateUtil.String, Projections.Property("Name"), Projections.Constant(1), Projections.Constant(2)), "te")) .Add(Restrictions.Eq(Projections.SqlFunction("locate", NHibernateUtil.String, Projections.Constant("e"), Projections.Property("Name"), Projections.Constant(1)), 2)) - .Add(Restrictions.Eq(Projections.SqlFunction("coalesce", NHibernateUtil.Object, Projections.Property("Name"), Projections.Constant("not-null-val")), "test")) - .Add(Restrictions.Eq(Projections.SqlFunction("coalesce", NHibernateUtil.Object, Projections.Property("NullableIsParent"), Projections.Constant(true)), true)) + .Add(Restrictions.Eq(Projections.SqlFunction("coalesce", new Type.CoalesceType(), Projections.Property("Name"), Projections.Constant("not-null-val")), "test")) + .Add(Restrictions.Eq(Projections.SqlFunction("coalesce", new Type.CoalesceType(), Projections.Property("NullableIsParent"), Projections.Constant(true)), true)) .Add(Restrictions.Eq(Projections.SqlFunction("concat", NHibernateUtil.String, Projections.Property("Name"), Projections.Constant(", "), Projections.Property("Name")), "test, test")) .Add(Restrictions.Eq(Projections.SqlFunction("mod", NHibernateUtil.Int32, Projections.Property("Height"), Projections.Constant(10)), 0)); @@ -339,4 +339,4 @@ public void FunctionExtensionsProperty() AssertCriteriaAreEqual(expected, actual); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/DialectTest/SchemaTests/ColumnMetaDataFixture.cs b/src/NHibernate.Test/DialectTest/SchemaTests/ColumnMetaDataFixture.cs index a8f9d8efa2b..5aea8b70926 100644 --- a/src/NHibernate.Test/DialectTest/SchemaTests/ColumnMetaDataFixture.cs +++ b/src/NHibernate.Test/DialectTest/SchemaTests/ColumnMetaDataFixture.cs @@ -12,7 +12,7 @@ public class ColumnMetaDataFixture private class TestableColumnMetaData : AbstractColumnMetaData { public TestableColumnMetaData(DataRow rs, object columnSizeValue, object numericalPrecisionValue) - : base(rs) + : base() { SetColumnSize(columnSizeValue); SetNumericalPrecision(numericalPrecisionValue); diff --git a/src/NHibernate.Test/DynamicProxyTests/InterfaceProxySerializationTests/ProxyFixture.cs b/src/NHibernate.Test/DynamicProxyTests/InterfaceProxySerializationTests/ProxyFixture.cs index d9b5badd6d9..4a95bec1ad5 100644 --- a/src/NHibernate.Test/DynamicProxyTests/InterfaceProxySerializationTests/ProxyFixture.cs +++ b/src/NHibernate.Test/DynamicProxyTests/InterfaceProxySerializationTests/ProxyFixture.cs @@ -1,9 +1,12 @@ using System; using System.Collections; using System.IO; +using NUnit.Framework; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; -using NUnit.Framework; +#endif namespace NHibernate.Test.DynamicProxyTests.InterfaceProxySerializationTests { @@ -20,6 +23,7 @@ protected override string MappingsAssembly get { return "NHibernate.Test"; } } +#if FEATURE_SERIALIZATION private void SerializeAndDeserialize(ref ISession s) { // Serialize the session @@ -36,6 +40,7 @@ private void SerializeAndDeserialize(ref ISession s) s = (ISession) formatter.Deserialize(stream); } } +#endif [Test] public void ExceptionStackTrace() @@ -92,6 +97,7 @@ public void Proxy() s.Close(); } +#if FEATURE_SERIALIZATION [Test] public void ProxySerialize() { @@ -138,5 +144,6 @@ public void SerializeNotFoundProxy() Assert.IsNotNull(s.Load(typeof (MyProxyImpl), 5), "should be proxy - even though it doesn't exists in db"); s.Close(); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs b/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs index 70d020796af..5cecfb1f531 100644 --- a/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs +++ b/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs @@ -26,6 +26,9 @@ public void LazyFieldInterceptorMarkedAsSerializable() Assert.That(typeof(DefaultDynamicLazyFieldInterceptor), Has.Attribute()); } +#if !FEATURE_SERIALIZATION + [Ignore("Requires serializable proxy")] +#endif [Test] public void LazyFieldInterceptorIsBinarySerializable() { diff --git a/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs b/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs index d247f4ac75f..e55bd8df991 100644 --- a/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs +++ b/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs @@ -121,10 +121,10 @@ public SavingProxyAssemblyBuilder(string assemblyName) this.assemblyName = assemblyName; } - public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) + public AssemblyBuilder DefineDynamicAssembly(AssemblyName name) { AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; - return appDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), access, TestContext.CurrentContext.TestDirectory); + return AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), access, TestContext.CurrentContext.TestDirectory); } public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName) diff --git a/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs b/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs index c9e46da1add..fa7aa62a37f 100644 --- a/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs +++ b/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs @@ -4,6 +4,9 @@ namespace NHibernate.Test.Extralazy { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Serializable type")] +#endif [TestFixture] public class ExtraLazyFixture : TestCase { @@ -296,4 +299,4 @@ public void SQLQuery() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Legacy/FooBarTest.cs b/src/NHibernate.Test/Legacy/FooBarTest.cs index 5ade062814e..d429c1202cd 100644 --- a/src/NHibernate.Test/Legacy/FooBarTest.cs +++ b/src/NHibernate.Test/Legacy/FooBarTest.cs @@ -6,8 +6,6 @@ using System.Diagnostics; using System.Globalization; using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; using System.Text; using Iesi.Collections.Generic; using NHibernate.Connection; @@ -19,8 +17,16 @@ using NHibernate.Util; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.Legacy { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class FooBarTest : TestCase { @@ -2821,16 +2827,19 @@ public void PersistCollections() txn.Commit(); s.Disconnect(); +#if FEATURE_SERIALIZATION // serialize and then deserialize the session. - Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); - formatter.Serialize(stream, s); + using (Stream stream = new MemoryStream()) + { + formatter.Serialize(stream, s); - s.Close(); + s.Close(); - stream.Position = 0; - s = (ISession) formatter.Deserialize(stream); - stream.Close(); + stream.Position = 0; + s = (ISession) formatter.Deserialize(stream); + } +#endif s.Reconnect(); txn = s.BeginTransaction(); @@ -2869,15 +2878,18 @@ public void PersistCollections() txn.Commit(); s.Disconnect(); +#if FEATURE_SERIALIZATION // serialize and then deserialize the session. - stream = new MemoryStream(); - formatter.Serialize(stream, s); + using (MemoryStream stream = new MemoryStream()) + { + formatter.Serialize(stream, s); - s.Close(); + s.Close(); - stream.Position = 0; - s = (ISession) formatter.Deserialize(stream); - stream.Close(); + stream.Position = 0; + s = (ISession) formatter.Deserialize(stream); + } +#endif Qux nonexistentQux = (Qux) s.Load(typeof(Qux), (long) 666); //nonexistent Assert.IsNotNull(nonexistentQux, "even though it doesn't exists should still get a proxy - no db hit."); @@ -4675,18 +4687,21 @@ public void ProxyArray() s.Flush(); s.Disconnect(); +#if FEATURE_SERIALIZATION // serialize the session. - Stream stream = new MemoryStream(); - IFormatter formatter = new BinaryFormatter(); - formatter.Serialize(stream, s); + using (Stream stream = new MemoryStream()) + { + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(stream, s); - // close the original session - s.Close(); + // close the original session + s.Close(); - // deserialize the session - stream.Position = 0; - s = (ISession) formatter.Deserialize(stream); - stream.Close(); + // deserialize the session + stream.Position = 0; + s = (ISession) formatter.Deserialize(stream); + } +#endif s.Close(); } @@ -5432,7 +5447,7 @@ public void PSCache() } } - #region NHibernate specific tests +#region NHibernate specific tests [Test] public void Formula() @@ -5539,6 +5554,6 @@ public void ParameterInOrderByClause() } } - #endregion +#endregion } } diff --git a/src/NHibernate.Test/Legacy/FumTest.cs b/src/NHibernate.Test/Legacy/FumTest.cs index 1ba7c5efef1..319b980f191 100644 --- a/src/NHibernate.Test/Legacy/FumTest.cs +++ b/src/NHibernate.Test/Legacy/FumTest.cs @@ -2,17 +2,23 @@ using System.Collections; using System.Collections.Generic; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.DomainModel; using NHibernate.Criterion; using NHibernate.Type; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.Legacy { /// /// FumTest handles testing Composite Ids. /// +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class FumTest : TestCase { @@ -706,6 +712,7 @@ public void UnflushedSessionSerialization() private ISession SpoofSerialization(ISession session) { +#if FEATURE_SERIALIZATION BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, session); @@ -713,6 +720,9 @@ private ISession SpoofSerialization(ISession session) stream.Position = 0; return (ISession) formatter.Deserialize(stream); +#else + return session; +#endif } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Legacy/MasterDetailTest.cs b/src/NHibernate.Test/Legacy/MasterDetailTest.cs index 003be74765e..9e5bf8f576f 100644 --- a/src/NHibernate.Test/Legacy/MasterDetailTest.cs +++ b/src/NHibernate.Test/Legacy/MasterDetailTest.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Dialect; using NHibernate.DomainModel; using NHibernate.Engine; @@ -11,6 +10,10 @@ using NUnit.Framework; using Single=NHibernate.DomainModel.Single; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.Legacy { /// @@ -636,6 +639,7 @@ public void NamedQuery() s.Close(); } +#if FEATURE_SERIALIZATION [Test] public void Serialization() { @@ -658,14 +662,15 @@ public void Serialization() } s.Flush(); s.Disconnect(); - MemoryStream stream = new MemoryStream(); BinaryFormatter f = new BinaryFormatter(); - f.Serialize(stream, s); - stream.Position = 0; - Console.WriteLine(stream.Length); + using (MemoryStream stream = new MemoryStream()) + { + f.Serialize(stream, s); + stream.Position = 0; + Console.WriteLine(stream.Length); - s = (ISession) f.Deserialize(stream); - stream.Close(); + s = (ISession) f.Deserialize(stream); + } s.Reconnect(); Master m2 = (Master) s.Load(typeof(Master), mid); @@ -692,12 +697,13 @@ public void Serialization() object mid2 = s.Save(new Master()); s.Flush(); s.Disconnect(); - stream = new MemoryStream(); - f.Serialize(stream, s); - stream.Position = 0; + using (MemoryStream stream = new MemoryStream()) + { + f.Serialize(stream, s); + stream.Position = 0; - s = (ISession) f.Deserialize(stream); - stream.Close(); + s = (ISession) f.Deserialize(stream); + } s.Reconnect(); s.Delete(s.Load(typeof(Master), mid)); @@ -707,23 +713,22 @@ public void Serialization() s = OpenSession(); string db = s.Connection.Database; //force session to grab a connection - try + using (MemoryStream stream = new MemoryStream()) { - stream = new MemoryStream(); - f.Serialize(stream, s); - } - catch (Exception e) - { - Assert.IsTrue(e is InvalidOperationException, "illegal state"); + try + { + f.Serialize(stream, s); + } + catch (Exception e) + { + Assert.IsTrue(e is InvalidOperationException, "illegal state"); s.Close(); - return; - } - finally - { - stream.Close(); + return; + } } Assert.IsTrue(false, "serialization should have failed"); } +#endif [Test] public void UpdateLazyCollections() diff --git a/src/NHibernate.Test/Legacy/ParentChildTest.cs b/src/NHibernate.Test/Legacy/ParentChildTest.cs index fd9b12140ba..343336a69cc 100644 --- a/src/NHibernate.Test/Legacy/ParentChildTest.cs +++ b/src/NHibernate.Test/Legacy/ParentChildTest.cs @@ -10,6 +10,9 @@ namespace NHibernate.Test.Legacy /// /// Summary description for ParentChildTest. /// +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class ParentChildTest : TestCase { diff --git a/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs b/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs index 290744e664a..f6d286b85c1 100644 --- a/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs +++ b/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs @@ -12,6 +12,9 @@ namespace NHibernate.Test.Legacy /// /// Summary description for SQLFunctionsTest. /// +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Serializable type")] +#endif [TestFixture] public class SQLFunctionsTest : TestCase { diff --git a/src/NHibernate.Test/Linq/LinqReadonlyTestsContext.cs b/src/NHibernate.Test/Linq/LinqReadonlyTestsContext.cs index 9b53d141e6b..df0cfa597a8 100644 --- a/src/NHibernate.Test/Linq/LinqReadonlyTestsContext.cs +++ b/src/NHibernate.Test/Linq/LinqReadonlyTestsContext.cs @@ -114,7 +114,7 @@ private Configuration Configure() configuration.SetProperty(Environment.ConnectionProvider, typeof (DriverConnectionProvider).AssemblyQualifiedName); - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); foreach (string file in Mappings.Select(mf => MappingsAssembly + "." + mf)) { @@ -143,4 +143,4 @@ private void CreateTestData(ISessionFactory sessionFactory) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/BasicObjectFixture.cs b/src/NHibernate.Test/NHSpecificTest/BasicObjectFixture.cs index cc6fa666dfb..90b89681955 100644 --- a/src/NHibernate.Test/NHSpecificTest/BasicObjectFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/BasicObjectFixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.Collections; using NHibernate.DomainModel.NHSpecific; @@ -68,4 +70,6 @@ public void TestCRUD() s.Close(); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/BasicSerializableFixture.cs b/src/NHibernate.Test/NHSpecificTest/BasicSerializableFixture.cs index af564197f7a..9a88a328b90 100644 --- a/src/NHibernate.Test/NHSpecificTest/BasicSerializableFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/BasicSerializableFixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.Collections; using NHibernate.DomainModel.NHSpecific; @@ -79,4 +81,6 @@ public void TestCRUD() s.Close(); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs index 1efc88a1127..9e878dbe263 100644 --- a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs @@ -2,12 +2,15 @@ using System.Collections; using System.Data; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using NHibernate.Driver; using NHibernate.Type; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.NHSpecificTest.Dates { [TestFixture] @@ -112,6 +115,7 @@ public void DefaultValueDoesNotThrowException() Assert.That(() => type.DefaultValue, Throws.Nothing); } +#if FEATURE_SERIALIZATION [Test(Description = "NH-3842")] public void CanBinarySerialize() { @@ -121,6 +125,7 @@ public void CanBinarySerialize() Assert.That(() => formatter.Serialize(Stream.Null, type), Throws.Nothing); } +#endif [Test(Description = "NH-3842")] public void CanXmlSerialize() diff --git a/src/NHibernate.Test/NHSpecificTest/DtcFailures/DtcFailuresFixture.cs b/src/NHibernate.Test/NHSpecificTest/DtcFailures/DtcFailuresFixture.cs index 5f47d850261..06d5bb122fe 100644 --- a/src/NHibernate.Test/NHSpecificTest/DtcFailures/DtcFailuresFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/DtcFailures/DtcFailuresFixture.cs @@ -45,7 +45,7 @@ protected override void CreateSchema() config.BeforeBindMapping += BeforeBindMapping; // Copied from AddMappings methods. - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); foreach (string file in Mappings) config.AddResource(MappingsAssembly + "." + file, assembly); @@ -353,4 +353,4 @@ public void InDoubt(Enlistment enlistment) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1274ExportExclude/NH1274ExportExcludeFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1274ExportExclude/NH1274ExportExcludeFixture.cs index c2f969618de..14a78b0712d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1274ExportExclude/NH1274ExportExcludeFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1274ExportExclude/NH1274ExportExcludeFixture.cs @@ -98,7 +98,7 @@ private Configuration GetConfiguration() if (TestConfigurationHelper.hibernateConfigFile != null) cfg.Configure(TestConfigurationHelper.hibernateConfigFile); - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); foreach (string file in Mappings) { @@ -133,4 +133,4 @@ protected IList Mappings } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1403/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1403/Fixture.cs index a051bca44ea..44ca2002fea 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1403/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1403/Fixture.cs @@ -2,6 +2,9 @@ namespace NHibernate.Test.NHSpecificTest.NH1403 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class Fixture : BugTestCase { @@ -37,4 +40,4 @@ public void Bug() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs index 0814975954f..71576744d9e 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs @@ -28,6 +28,9 @@ public void WhenParameterListIsEmptyGenericCollectionUsingQueryThenDoesNotTrowsN } } +#if !FEATURE_SERIALIZATION + [Ignore("Uses Serializable type")] +#endif [Test] public void WhenParameterListIsEmptyCollectionUsingQueryThenTrowsArgumentException() { @@ -60,4 +63,4 @@ public void WhenParameterListIsEmptyUsingQueryThenDoesNotTrowsNullReferenceExcep } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1985/SampleTest.cs b/src/NHibernate.Test/NHSpecificTest/NH1985/SampleTest.cs index 18c66fd6dcb..00df7ceaca5 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1985/SampleTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1985/SampleTest.cs @@ -14,7 +14,7 @@ protected override void OnSetUp() if (0 == ExecuteStatement("INSERT INTO DomainClass (Id, Label) VALUES (1, 'TEST record');")) { - throw new ApplicationException("Insertion of test record failed."); + Assert.Fail("Insertion of test record failed."); } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH2297/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2297/Fixture.cs index 87a37b2a10c..627248d8489 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2297/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2297/Fixture.cs @@ -24,7 +24,7 @@ public void InvalidCustomCompositeUserTypeThrowsMeaningfulException( const string mappingsAssembly = "NHibernate.Test"; - Assembly assembly = Assembly.Load(mappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(mappingsAssembly)); string ns = GetType().Namespace; string bugNumber = ns.Substring(ns.LastIndexOf('.') + 1); diff --git a/src/NHibernate.Test/NHSpecificTest/NH2328/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2328/Fixture.cs index a0dcb58b148..53a4fda6dea 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2328/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2328/Fixture.cs @@ -4,6 +4,9 @@ namespace NHibernate.Test.NHSpecificTest.NH2328 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class Fixture : BugTestCase { @@ -98,4 +101,4 @@ public void AnyIs_HqlWorksWithClassNameInTheLeft() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs index b14b6ba04b9..a98dab1da6c 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.Drawing; using System.Reflection; @@ -18,7 +20,7 @@ protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect) [Test] public void TestPersistenceOfClassWithUnknownSerializableType() { - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg"); var image = Bitmap.FromStream(stream); @@ -50,7 +52,7 @@ public void TestPersistenceOfClassWithUnknownSerializableType() [Test] public void TestPersistenceOfClassWithSerializableType() { - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg"); var image = Bitmap.FromStream(stream); @@ -79,4 +81,6 @@ public void TestPersistenceOfClassWithSerializableType() stream.Dispose(); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH2484/Model.cs b/src/NHibernate.Test/NHSpecificTest/NH2484/Model.cs index 80b7a1caeb5..aacbc1e9b7e 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2484/Model.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2484/Model.cs @@ -1,5 +1,7 @@ using System; +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Test.NHSpecificTest.NH2484 { @@ -12,6 +14,8 @@ public class ClassWithImage public class ClassWithSerializableType { public virtual int Id { get; set; } +#if FEATURE_SERIALIZATION public virtual ISerializable Image { get; set; } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH2773/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2773/Fixture.cs index ecabe34dde7..1a90d0d14c6 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2773/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2773/Fixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -69,4 +71,6 @@ public void DeserializedSession_ProxyType_ShouldBeEqualToOriginalProxyType() { Assert.AreEqual(originalProxyType, deserializedProxyType); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH2880/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2880/Fixture.cs index e94a53f9bdd..21a0680d75f 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2880/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2880/Fixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -97,4 +99,6 @@ protected override void OnTearDown() } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCache.cs b/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCache.cs index bdb364c5621..c424be9961d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCache.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCache.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -77,4 +79,6 @@ public string RegionName get { return _regionName; } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCacheProvider.cs b/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCacheProvider.cs index 6c9f8357124..c446da9209f 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCacheProvider.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2898/BinaryFormatterCacheProvider.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System.Collections.Generic; using NHibernate.Cache; @@ -27,4 +29,6 @@ public void Stop() #endregion } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH2898/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2898/Fixture.cs index 8f448b5c75e..9c974afe6f9 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2898/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2898/Fixture.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Engine; @@ -117,4 +119,6 @@ public void SecondLevelCacheWithHqlQueries() } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH3119/FixtureByCode.cs b/src/NHibernate.Test/NHSpecificTest/NH3119/FixtureByCode.cs index 3c03929806a..0017e6fdb84 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3119/FixtureByCode.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3119/FixtureByCode.cs @@ -1,12 +1,15 @@ using System.IO; using System.Linq; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; using NHibernate.Linq; using NHibernate.Mapping.ByCode; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.NHSpecificTest.NH3119 { /// @@ -79,6 +82,7 @@ public void PocoComponentTuplizer_Instantiate_UsesReflectonOptimizer() } } +#if FEATURE_SERIALIZATION [Test] public void PocoComponentTuplizerOfDeserializedConfiguration_Instantiate_UsesReflectonOptimizer() { @@ -101,5 +105,6 @@ public void PocoComponentTuplizerOfDeserializedConfiguration_Instantiate_UsesRef StringAssert.Contains("NHibernate.Bytecode.Lightweight.ReflectionOptimizer.CreateInstance", stackTrace); } } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs index 16bb4da24f3..af778462f00 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs @@ -8,6 +8,9 @@ namespace NHibernate.Test.NHSpecificTest.NH3121 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Serializable type")] +#endif [TestFixture] public class Fixture : BugTestCase { @@ -50,7 +53,7 @@ public void ShouldThrowWhenByteArrayTooLong() [Test] public void ShouldThrowWhenImageTooLarge() { - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg"); var image = Bitmap.FromStream(stream); @@ -65,10 +68,11 @@ public void ShouldThrowWhenImageTooLarge() } +#if FEATURE_SERIALIZATION [Test] public void ShouldThrowWhenImageAsISerializableTooLarge() { - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg"); var image = Bitmap.FromStream(stream); @@ -81,7 +85,7 @@ public void ShouldThrowWhenImageAsISerializableTooLarge() Assert.That(ex.InnerException.Message, Is.EqualTo("The length of the byte[] value exceeds the length configured in the mapping/parameter.")); } - +#endif private void PersistReport(Report report) { diff --git a/src/NHibernate.Test/NHSpecificTest/NH3121/Report.cs b/src/NHibernate.Test/NHSpecificTest/NH3121/Report.cs index 821a352e0a1..966a1db2d3e 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3121/Report.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3121/Report.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Runtime.Serialization; using System.Text; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Test.NHSpecificTest.NH3121 { public class Report @@ -12,6 +15,8 @@ public class Report public virtual Byte[] UnsizedArray { get; set; } public virtual System.Drawing.Image Image { get; set; } +#if FEATURE_SERIALIZATION public virtual ISerializable SerializableImage { get; set; } +#endif } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH317/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH317/Fixture.cs index 2313dec63d0..ad20ade841f 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH317/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH317/Fixture.cs @@ -1,3 +1,4 @@ +#if FEATURE_SERIALIZATION using System; using System.Collections; using System.IO; @@ -44,13 +45,15 @@ public void ProxySerialization() // Serialize IFormatter formatter = new BinaryFormatter(); - MemoryStream ms = new MemoryStream(); - formatter.Serialize(ms, nodeProxy); + Node deserializedNodeProxy; + using (MemoryStream ms = new MemoryStream()) + { + formatter.Serialize(ms, nodeProxy); - // Deserialize - ms.Seek(0, SeekOrigin.Begin); - Node deserializedNodeProxy = (Node) formatter.Deserialize(ms); - ms.Close(); + // Deserialize + ms.Seek(0, SeekOrigin.Begin); + deserializedNodeProxy = (Node) formatter.Deserialize(ms); + } // Deserialized proxy should implement the INHibernateProxy interface. Assert.IsTrue(deserializedNodeProxy is INHibernateProxy); @@ -61,4 +64,5 @@ public void ProxySerialization() s.Close(); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs b/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs index fe2595816ef..bab85f060a5 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs @@ -1,4 +1,6 @@ -using System; +#if FEATURE_SERIALIZATION + +using System; using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; @@ -160,4 +162,6 @@ public void DeserializeAndAssert(MemoryStream configMemoryStream) } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH3487/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3487/Fixture.cs index d9ba75df001..041863a3464 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3487/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3487/Fixture.cs @@ -1,4 +1,6 @@ -using System.IO; +#if FEATURE_SERIALIZATION + +using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; @@ -80,4 +82,6 @@ public void CanDeserializeSessionWithEntityHashCollision() } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH3614/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3614/Fixture.cs index e93a46c0213..a8046782077 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3614/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3614/Fixture.cs @@ -7,6 +7,9 @@ namespace NHibernate.Test.NHSpecificTest.NH3614 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Serializable type")] +#endif [TestFixture] public class Fixture : BugTestCase { diff --git a/src/NHibernate.Test/NHSpecificTest/NH3731/FixtureByCode.cs b/src/NHibernate.Test/NHSpecificTest/NH3731/FixtureByCode.cs index e87deb65286..3ed08c4c3b0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3731/FixtureByCode.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3731/FixtureByCode.cs @@ -1,4 +1,6 @@ -using System.IO; +#if FEATURE_SERIALIZATION + +using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Cfg.MappingSchema; @@ -142,4 +144,6 @@ public void Serializing_Session_After_Changing_Key_ChildrenMap_Should_Work() } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH3795/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3795/Fixture.cs index 17f559d6c13..fe6b4dbfd09 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3795/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3795/Fixture.cs @@ -7,6 +7,9 @@ namespace NHibernate.Test.NHSpecificTest.NH3795 /// /// Tests in this class only failed when the code was build with the Roslyn compiler which is included in Visual Studio 2015 /// +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class Fixture : TestCase { diff --git a/src/NHibernate.Test/NHSpecificTest/NH719/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH719/Fixture.cs index 430ac9ff691..ca96eaeb554 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH719/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH719/Fixture.cs @@ -2,6 +2,9 @@ namespace NHibernate.Test.NHSpecificTest.NH719 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class Fixture : BugTestCase { @@ -67,4 +70,4 @@ public void CacheLoadTest() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH732/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH732/Fixture.cs index 1c88666e8b3..134739b5595 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH732/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH732/Fixture.cs @@ -70,12 +70,12 @@ public System.Type ReturnedType public new bool Equals(object x, object y) { - return StringComparer.InvariantCultureIgnoreCase.Equals((string)x, (string)y); + return StringComparer.OrdinalIgnoreCase.Equals((string)x, (string)y); } public int GetHashCode(object x) { - return StringComparer.InvariantCultureIgnoreCase.GetHashCode((string)x); + return StringComparer.OrdinalIgnoreCase.GetHashCode((string)x); } public object NullSafeGet(DbDataReader rs, string[] names, object owner) diff --git a/src/NHibernate.Test/NHSpecificTest/NH958/NH958Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH958/NH958Fixture.cs index 095e5957e3a..bd9fc650e19 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH958/NH958Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH958/NH958Fixture.cs @@ -5,6 +5,9 @@ namespace NHibernate.Test.NHSpecificTest.NH958 { +#if !FEATURE_SERIALIZATION + [Ignore("Mapping Document has Any type")] +#endif [TestFixture] public class NH958Fixture : BugTestCase { diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index 8fae8736b23..13e8f307ea5 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -1,109 +1,64 @@  - + + Debug AnyCPU - 9.0.30729 - 2.0 - {7AEE5B37-C552-4E59-9B6F-88755BCB5070} + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3} Library Properties - NHibernate.Test - NHibernate.Test - - - 3.5 - - + NHibernate.Test2 + NHibernate.Test2 v4.6.1 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - Program - $(MSBuildProjectDirectory)\..\..\Tools\nunit\nunit-x86.exe - NHibernate.Test.dll - + 512 true full false - bin\Debug-2.0\ - obj\ - obj\Debug-2.0\ - NET,NET_2_0 + bin\Debug\ + DEBUG;TRACE prompt 4 - false - 3001%3b3002%3b3003%3b3004%3b3005 - AllRules.ruleset - AnyCPU - false pdbonly true - bin\Release-2.0\ - obj\ - obj\Release-2.0\ - TRACE;NET,NET_2_0 + bin\Release\ + TRACE prompt 4 - false - 3001%3b3002%3b3003%3b3004%3b3005 - AllRules.ruleset - false - + ..\packages\Antlr3.Runtime.3.5.1\lib\net40-client\Antlr3.Runtime.dll - True ..\packages\Iesi.Collections.4.0.1.4000\lib\net40\Iesi.Collections.dll - True - - ..\packages\log4net.2.0.7\lib\net45-full\log4net.dll - True + + ..\packages\log4net.2.0.8\lib\net45-full\log4net.dll - - ..\packages\NUnit.3.6.0\lib\net45\nunit.framework.dll - True + + ..\packages\NUnit.3.6.1\lib\net45\nunit.framework.dll - - ..\packages\Remotion.Linq.1.13.183.0\lib\net35\Remotion.Linq.dll - True + + ..\packages\Remotion.Linq.1.15.15.0\lib\portable-net45+wp80+wpa81+win\Remotion.Linq.dll - - - 3.5 - - + + ..\packages\System.Linq.Dynamic.1.0.7\lib\net40\System.Linq.Dynamic.dll - True - + + + - - 3.5 - + + @@ -1365,6 +1320,7 @@ + @@ -3798,14 +3754,5 @@ - - - - + \ No newline at end of file diff --git a/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs b/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs index f156778901d..add486fd1b4 100644 --- a/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs +++ b/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs @@ -425,6 +425,7 @@ public void ResultTransformer() } } +#if FEATURE_SERIALIZATION [Test] public void Serializable() { @@ -439,6 +440,7 @@ public void Serializable() dqs.GetExecutableQuery(s).List(); } } +#endif [Test, Explicit] public void PerformanceDiffSimplyQuery() diff --git a/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs b/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs index 04a9b314a7b..38eb02c857e 100644 --- a/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs +++ b/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs @@ -1049,7 +1049,8 @@ public void Subselect() t.Commit(); } } - + +#if FEATURE_SERIALIZATION [Test] public void DetachedCriteria() { @@ -1103,6 +1104,7 @@ public void DetachedCriteria() t.Commit(); } } +#endif [Test] public void TwoAliasesCache() diff --git a/src/NHibernate/Util/SerializationHelper.cs b/src/NHibernate.Test/SerializationHelper.cs similarity index 90% rename from src/NHibernate/Util/SerializationHelper.cs rename to src/NHibernate.Test/SerializationHelper.cs index 5051d0693c9..e4e956e12bf 100644 --- a/src/NHibernate/Util/SerializationHelper.cs +++ b/src/NHibernate.Test/SerializationHelper.cs @@ -1,8 +1,9 @@ -using System; +#if FEATURE_SERIALIZATION + using System.IO; using System.Runtime.Serialization.Formatters.Binary; -namespace NHibernate.Util +namespace NHibernate.Test { public class SerializationHelper { @@ -29,4 +30,6 @@ public static object Deserialize(byte[] data) } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate.Test/TestCase.cs b/src/NHibernate.Test/TestCase.cs index 0d7c4742556..8920abab3de 100644 --- a/src/NHibernate.Test/TestCase.cs +++ b/src/NHibernate.Test/TestCase.cs @@ -231,7 +231,7 @@ private void Configure() protected virtual void AddMappings(Configuration configuration) { - Assembly assembly = Assembly.Load(MappingsAssembly); + Assembly assembly = Assembly.Load(new AssemblyName(MappingsAssembly)); foreach (string file in Mappings) { diff --git a/src/NHibernate.Test/TypeParameters/TypeParameterTest.cs b/src/NHibernate.Test/TypeParameters/TypeParameterTest.cs index a64abc914e1..63fd54aa4f0 100644 --- a/src/NHibernate.Test/TypeParameters/TypeParameterTest.cs +++ b/src/NHibernate.Test/TypeParameters/TypeParameterTest.cs @@ -64,18 +64,18 @@ public void Save() statement.Connection = connection; t.Enlist(statement); statement.Parameters[0].Value = id; - var reader = statement.ExecuteReader(); - - Assert.IsTrue(reader.Read(), "A row should have been returned"); - Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_ONE")) == DBNull.Value, - "Default value should have been mapped to null"); - Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_TWO")) == DBNull.Value, - "Default value should have been mapped to null"); - Assert.AreEqual(Convert.ToInt32(reader.GetValue(reader.GetOrdinal("VALUE_THREE"))), 5, - "Non-Default value should not be changed"); - Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_FOUR")) == DBNull.Value, - "Default value should have been mapped to null"); - reader.Close(); + using (DbDataReader reader = statement.ExecuteReader()) + { + Assert.IsTrue(reader.Read(), "A row should have been returned"); + Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_ONE")) == DBNull.Value, + "Default value should have been mapped to null"); + Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_TWO")) == DBNull.Value, + "Default value should have been mapped to null"); + Assert.AreEqual(Convert.ToInt32(reader.GetValue(reader.GetOrdinal("VALUE_THREE"))), 5, + "Non-Default value should not be changed"); + Assert.IsTrue(reader.GetValue(reader.GetOrdinal("VALUE_FOUR")) == DBNull.Value, + "Default value should have been mapped to null"); + } t.Commit(); s.Close(); @@ -145,4 +145,4 @@ private void DeleteData() s.Close(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs b/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs index e0ec802bee1..b31c413d99f 100644 --- a/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs @@ -1,11 +1,14 @@ using System; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using System.Text; using NHibernate.Dialect; using NHibernate.Type; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.TypesTest { /// @@ -152,10 +155,14 @@ private BinaryClass Create(int id) private byte[] GetByteArray(int value) { +#if FEATURE_SERIALIZATION BinaryFormatter bf = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); bf.Serialize(stream, value); return stream.ToArray(); +#else + return BitConverter.GetBytes(value); +#endif } } } diff --git a/src/NHibernate.Test/TypesTest/TypeFactoryFixture.cs b/src/NHibernate.Test/TypesTest/TypeFactoryFixture.cs index f4dcaffa09e..93e0ac958d5 100644 --- a/src/NHibernate.Test/TypesTest/TypeFactoryFixture.cs +++ b/src/NHibernate.Test/TypesTest/TypeFactoryFixture.cs @@ -93,11 +93,13 @@ public void MultiThreadAccess() TypeFactory.GetBinaryType(rnd.Next(1, 50)); totalCall++; }, +#if FEATURE_SERIALIZATION delegate(object o) { TypeFactory.GetSerializableType(rnd.Next(1, 50)); totalCall++; }, +#endif delegate(object o) { TypeFactory.GetTypeType(rnd.Next(1, 20)); diff --git a/src/NHibernate.Test/UtilityTest/LinkedHashMapFixture.cs b/src/NHibernate.Test/UtilityTest/LinkedHashMapFixture.cs index 875b5fa6ab3..2bf8d74b3cd 100644 --- a/src/NHibernate.Test/UtilityTest/LinkedHashMapFixture.cs +++ b/src/NHibernate.Test/UtilityTest/LinkedHashMapFixture.cs @@ -1,10 +1,13 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Util; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.UtilityTest { [TestFixture] @@ -230,19 +233,22 @@ public void Values() } } +#if FEATURE_SERIALIZATION [Test] public void Serialization() { IDictionary lhm = new LinkedHashMap(); Fill(lhm); - MemoryStream stream = new MemoryStream(); - BinaryFormatter f = new BinaryFormatter(); - f.Serialize(stream, lhm); - stream.Position = 0; + LinkedHashMap dlhm; + using (MemoryStream stream = new MemoryStream()) + { + BinaryFormatter f = new BinaryFormatter(); + f.Serialize(stream, lhm); + stream.Position = 0; - LinkedHashMap dlhm = (LinkedHashMap)f.Deserialize(stream); - stream.Close(); + dlhm = (LinkedHashMap) f.Deserialize(stream); + } Assert.AreEqual(6, dlhm.Count); int index = 0; @@ -255,7 +261,7 @@ public void Serialization() Assert.AreEqual(6, index); } - +#endif [Test, Explicit] public void ShowDiff() diff --git a/src/NHibernate.Test/UtilityTest/SequencedHashMapFixture.cs b/src/NHibernate.Test/UtilityTest/SequencedHashMapFixture.cs index 7519f403ffd..96c426f9836 100644 --- a/src/NHibernate.Test/UtilityTest/SequencedHashMapFixture.cs +++ b/src/NHibernate.Test/UtilityTest/SequencedHashMapFixture.cs @@ -2,10 +2,13 @@ using System.Collections; using System.Collections.Specialized; using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Util; using NUnit.Framework; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization.Formatters.Binary; +#endif + namespace NHibernate.Test.UtilityTest { /// @@ -419,16 +422,19 @@ public void Performance() } } +#if FEATURE_SERIALIZATION [Test] public void Serialize() { - MemoryStream stream = new MemoryStream(); - BinaryFormatter f = new BinaryFormatter(); - f.Serialize(stream, _shm); - stream.Position = 0; + SequencedHashMap shm; + using (MemoryStream stream = new MemoryStream()) + { + BinaryFormatter f = new BinaryFormatter(); + f.Serialize(stream, _shm); + stream.Position = 0; - SequencedHashMap shm = (SequencedHashMap) f.Deserialize(stream); - stream.Close(); + shm = (SequencedHashMap) f.Deserialize(stream); + } Assert.AreEqual(3, shm.Count); int index = 0; @@ -441,5 +447,6 @@ public void Serialize() Assert.AreEqual(3, index); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/UtilityTest/WeakHashtableFixture.cs b/src/NHibernate.Test/UtilityTest/WeakHashtableFixture.cs index ba8bbc42c41..c3ea753728b 100644 --- a/src/NHibernate.Test/UtilityTest/WeakHashtableFixture.cs +++ b/src/NHibernate.Test/UtilityTest/WeakHashtableFixture.cs @@ -1,7 +1,5 @@ using System; using System.Collections; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Util; using NUnit.Framework; @@ -114,4 +112,4 @@ public void IsSerializable() NHAssert.IsSerializable(weakHashtable); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/packages.config b/src/NHibernate.Test/packages.config index 4c41501a08e..2dcd37c290f 100644 --- a/src/NHibernate.Test/packages.config +++ b/src/NHibernate.Test/packages.config @@ -2,8 +2,8 @@ - - - + + + \ No newline at end of file diff --git a/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj b/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj index 118e1b4ac07..aec4512f38f 100644 --- a/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj +++ b/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj @@ -1,5 +1,6 @@  - + + Debug AnyCPU @@ -103,11 +104,4 @@ - \ No newline at end of file diff --git a/src/NHibernate.sln b/src/NHibernate.sln index 626bc6a7489..ca58958c7e3 100644 --- a/src/NHibernate.sln +++ b/src/NHibernate.sln @@ -1,7 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25123.0 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.9 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{593DCEA7-C933-46F3-939F-D8172399AB05}" ProjectSection(SolutionItems) = preProject @@ -10,42 +9,112 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ..\teamcity.build = ..\teamcity.build EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate", "NHibernate\NHibernate.csproj", "{5909BFE7-93CF-4E5F-BE22-6293368AF01D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.TestDatabaseSetup", "NHibernate.TestDatabaseSetup\NHibernate.TestDatabaseSetup.csproj", "{BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.DomainModel", "NHibernate.DomainModel\NHibernate.DomainModel.csproj", "{5C649B55-1B3F-4C38-9998-1B043E94A244}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate", "NHibernate\NHibernate.csproj", "{D39E4139-6011-4DB2-837E-20C9BE221B9C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.Test", "NHibernate.Test\NHibernate.Test.csproj", "{7AEE5B37-C552-4E59-9B6F-88755BCB5070}" +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "NHibernate.Test.VisualBasic", "NHibernate.Test.VisualBasic\NHibernate.Test.VisualBasic.vbproj", "{F43B3253-9011-4DAE-8777-BA0D8DA850A6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.TestDatabaseSetup", "NHibernate.TestDatabaseSetup\NHibernate.TestDatabaseSetup.csproj", "{BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.DomainModel", "NHibernate.DomainModel\NHibernate.DomainModel.csproj", "{7ABB1237-3251-41E3-92D0-9937D3734E40}" EndProject -Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "NHibernate.Test.VisualBasic", "NHibernate.Test.VisualBasic\NHibernate.Test.VisualBasic.vbproj", "{7C2EF610-BCA0-4D1F-898A-DE9908E4970C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.Test", "NHibernate.Test\NHibernate.Test.csproj", "{1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Debug-nofeatures|Any CPU = Debug-nofeatures|Any CPU + Debug-nofeatures|x64 = Debug-nofeatures|x64 + Debug-nofeatures|x86 = Debug-nofeatures|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5909BFE7-93CF-4E5F-BE22-6293368AF01D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5909BFE7-93CF-4E5F-BE22-6293368AF01D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5909BFE7-93CF-4E5F-BE22-6293368AF01D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5909BFE7-93CF-4E5F-BE22-6293368AF01D}.Release|Any CPU.Build.0 = Release|Any CPU - {5C649B55-1B3F-4C38-9998-1B043E94A244}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5C649B55-1B3F-4C38-9998-1B043E94A244}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5C649B55-1B3F-4C38-9998-1B043E94A244}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5C649B55-1B3F-4C38-9998-1B043E94A244}.Release|Any CPU.Build.0 = Release|Any CPU - {7AEE5B37-C552-4E59-9B6F-88755BCB5070}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7AEE5B37-C552-4E59-9B6F-88755BCB5070}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7AEE5B37-C552-4E59-9B6F-88755BCB5070}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7AEE5B37-C552-4E59-9B6F-88755BCB5070}.Release|Any CPU.Build.0 = Release|Any CPU {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug|x64.ActiveCfg = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug|x86.ActiveCfg = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug-nofeatures|Any CPU.ActiveCfg = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug-nofeatures|Any CPU.Build.0 = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug-nofeatures|x64.ActiveCfg = Debug|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Debug-nofeatures|x86.ActiveCfg = Debug|Any CPU {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Release|Any CPU.ActiveCfg = Release|Any CPU {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Release|Any CPU.Build.0 = Release|Any CPU - {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7C2EF610-BCA0-4D1F-898A-DE9908E4970C}.Release|Any CPU.Build.0 = Release|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Release|x64.ActiveCfg = Release|Any CPU + {BEEC1564-6FB6-49F7-BBE5-8EBD2F0F6E8A}.Release|x86.ActiveCfg = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|x64.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|x64.Build.0 = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|x86.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug|x86.Build.0 = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug-nofeatures|Any CPU.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug-nofeatures|x64.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug-nofeatures|x64.Build.0 = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug-nofeatures|x86.ActiveCfg = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Debug-nofeatures|x86.Build.0 = Debug|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|Any CPU.Build.0 = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|x64.ActiveCfg = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|x64.Build.0 = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|x86.ActiveCfg = Release|Any CPU + {D39E4139-6011-4DB2-837E-20C9BE221B9C}.Release|x86.Build.0 = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|x64.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|x64.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|x86.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug|x86.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|Any CPU.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|Any CPU.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|x64.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|x64.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|x86.ActiveCfg = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Debug-nofeatures|x86.Build.0 = Debug|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|Any CPU.Build.0 = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|x64.ActiveCfg = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|x64.Build.0 = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|x86.ActiveCfg = Release|Any CPU + {F43B3253-9011-4DAE-8777-BA0D8DA850A6}.Release|x86.Build.0 = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|x64.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|x64.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|x86.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug|x86.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|Any CPU.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|Any CPU.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|x64.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|x64.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|x86.ActiveCfg = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Debug-nofeatures|x86.Build.0 = Debug|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|Any CPU.Build.0 = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|x64.ActiveCfg = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|x64.Build.0 = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|x86.ActiveCfg = Release|Any CPU + {7ABB1237-3251-41E3-92D0-9937D3734E40}.Release|x86.Build.0 = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|x64.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|x64.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|x86.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug|x86.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|Any CPU.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|Any CPU.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|x64.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|x64.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|x86.ActiveCfg = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Debug-nofeatures|x86.Build.0 = Debug|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|Any CPU.Build.0 = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|x64.ActiveCfg = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|x64.Build.0 = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|x86.ActiveCfg = Release|Any CPU + {1B7E9512-5B0F-45BE-82AD-5EBDA404BDE3}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/NHibernate/ADOException.cs b/src/NHibernate/ADOException.cs index f8cfe3b7331..c5cde1f9337 100644 --- a/src/NHibernate/ADOException.cs +++ b/src/NHibernate/ADOException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -41,6 +43,7 @@ public ADOException(string message, Exception innerException, string sql) this.sql = sql; } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class. /// @@ -62,6 +65,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont base.GetObjectData(info, context); info.AddValue("sql", sql); } +#endif public string SqlString { diff --git a/src/NHibernate/Action/CollectionAction.cs b/src/NHibernate/Action/CollectionAction.cs index cfdedcb23e0..9c0c2b00efa 100644 --- a/src/NHibernate/Action/CollectionAction.cs +++ b/src/NHibernate/Action/CollectionAction.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.Serialization; using NHibernate.Cache; using NHibernate.Cache.Access; using NHibernate.Collection; @@ -8,13 +7,21 @@ using NHibernate.Persister.Collection; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Action { /// /// Any action relating to insert/update/delete of a collection /// [Serializable] - public abstract class CollectionAction : IExecutable, IComparable, IDeserializationCallback + public abstract class CollectionAction + : IExecutable, IComparable +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { private readonly object key; private object finalKey; @@ -174,6 +181,7 @@ public override string ToString() return StringHelper.Unqualify(GetType().FullName) + MessageHelper.InfoString(collectionRole, key); } +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) @@ -182,5 +190,6 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif } } diff --git a/src/NHibernate/Action/EntityAction.cs b/src/NHibernate/Action/EntityAction.cs index 7ec15006c81..de433c6c3c9 100644 --- a/src/NHibernate/Action/EntityAction.cs +++ b/src/NHibernate/Action/EntityAction.cs @@ -1,11 +1,14 @@ using System; using System.IO; -using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.Persister.Entity; using NHibernate.Util; using NHibernate.Impl; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Action { /// @@ -13,7 +16,11 @@ namespace NHibernate.Action /// instance. /// [Serializable] - public abstract class EntityAction : IExecutable, IComparable, IDeserializationCallback + public abstract class EntityAction + : IExecutable, IComparable +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { private readonly string entityName; private readonly object id; @@ -160,6 +167,7 @@ public virtual int CompareTo(EntityAction other) #endregion +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) @@ -175,6 +183,7 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif public override string ToString() { diff --git a/src/NHibernate/AdoNet/ConnectionManager.cs b/src/NHibernate/AdoNet/ConnectionManager.cs index 5ace6b15a2f..673605e5887 100644 --- a/src/NHibernate/AdoNet/ConnectionManager.cs +++ b/src/NHibernate/AdoNet/ConnectionManager.cs @@ -1,12 +1,14 @@ using System; using System.Data; using System.Data.Common; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using NHibernate.Engine; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Security; +#endif + namespace NHibernate.AdoNet { /// @@ -17,7 +19,10 @@ namespace NHibernate.AdoNet /// combined. /// [Serializable] - public class ConnectionManager : ISerializable, IDeserializationCallback + public class ConnectionManager +#if FEATURE_SERIALIZATION + : ISerializable, IDeserializationCallback +#endif { private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ConnectionManager)); @@ -70,7 +75,11 @@ public bool IsInActiveTransaction { if (transaction != null && transaction.IsActive) return true; +#if FEATURE_SYSTEM_TRANSACTIONS return Factory.TransactionFactory.IsInDistributedActiveTransaction(session); +#else + return false; +#endif } } @@ -272,6 +281,7 @@ public void FlushEnding() AfterStatement(); } +#if FEATURE_SERIALIZATION #region Serialization private ConnectionManager(SerializationInfo info, StreamingContext context) @@ -302,6 +312,7 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif public ITransaction BeginTransaction(IsolationLevel isolationLevel) { diff --git a/src/NHibernate/AdoNet/MySqlClientSqlCommandSet.cs b/src/NHibernate/AdoNet/MySqlClientSqlCommandSet.cs index af87b6aae5c..d2c539e97a3 100644 --- a/src/NHibernate/AdoNet/MySqlClientSqlCommandSet.cs +++ b/src/NHibernate/AdoNet/MySqlClientSqlCommandSet.cs @@ -20,7 +20,7 @@ public class MySqlClientSqlCommandSet : IDisposable static MySqlClientSqlCommandSet() { - var sysData = Assembly.Load("MySql.Data"); + var sysData = Assembly.Load(new AssemblyName("MySql.Data")); adapterType = sysData.GetType("MySql.Data.MySqlClient.MySqlDataAdapter"); Debug.Assert(adapterType != null, "Could not find MySqlDataAdapter!"); @@ -71,4 +71,4 @@ public int CountOfCommands get { return countOfCommands; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs b/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs index 0398dcb08cd..6f89533dc6f 100644 --- a/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Data.Common; +using System.Reflection; using System.Text; using NHibernate.AdoNet.Util; using NHibernate.Exceptions; @@ -167,4 +168,4 @@ public override int BatchSize set { _batchSize = value; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/ResultSetWrapper.cs b/src/NHibernate/AdoNet/ResultSetWrapper.cs index 75e03a3ef5e..a890f497124 100644 --- a/src/NHibernate/AdoNet/ResultSetWrapper.cs +++ b/src/NHibernate/AdoNet/ResultSetWrapper.cs @@ -27,15 +27,19 @@ internal DbDataReader Target get { return rs; } } +#if FEATURE_DATA_CLOSE || NET_4_0 public override void Close() { rs.Close(); } +#endif +#if FEATURE_DATA_GETSCHEMATABLE || NET_4_0 public override DataTable GetSchemaTable() { return rs.GetSchemaTable(); } +#endif public override bool NextResult() { @@ -76,9 +80,9 @@ protected override void Dispose(bool disposing) if (disposing && rs != null) { - rs.Dispose(); + rs.Dispose(); rs = null; - } + } disposed = true; } diff --git a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs index 2fbff365c61..b492eee824d 100644 --- a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs @@ -1,3 +1,5 @@ +#if FEATURE_ADONET_SQLCOMMANDSET + using System; using System.Data.Common; using System.Text; @@ -118,4 +120,6 @@ private SqlClientSqlCommandSet CreateConfiguredBatch() return result; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs b/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs index 61304f1241e..8cd8e8f0d89 100644 --- a/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs +++ b/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs @@ -1,3 +1,5 @@ +#if FEATURE_ADONET_SQLCOMMANDSET + using NHibernate.Engine; namespace NHibernate.AdoNet @@ -9,4 +11,6 @@ public virtual IBatcher CreateBatcher(ConnectionManager connectionManager, IInte return new SqlClientBatchingBatcher(connectionManager, interceptor); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs b/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs index 9a36255c77c..da1a18d3f23 100644 --- a/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs +++ b/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs @@ -1,3 +1,5 @@ +#if FEATURE_ADONET_SQLCOMMANDSET + using System; using System.Data.SqlClient; using System.Diagnostics; @@ -32,7 +34,7 @@ public class SqlClientSqlCommandSet : IDisposable static SqlClientSqlCommandSet() { - var sysData = Assembly.Load("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); + var sysData = Assembly.Load(new AssemblyName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); sqlCmdSetType = sysData.GetType("System.Data.SqlClient.SqlCommandSet"); Debug.Assert(sqlCmdSetType != null, "Could not find SqlCommandSet!"); @@ -135,3 +137,5 @@ public void Dispose() } } } + +#endif diff --git a/src/NHibernate/AdoNet/TooManyRowsAffectedException.cs b/src/NHibernate/AdoNet/TooManyRowsAffectedException.cs index bcf54ff1e63..c3e9ddae8df 100644 --- a/src/NHibernate/AdoNet/TooManyRowsAffectedException.cs +++ b/src/NHibernate/AdoNet/TooManyRowsAffectedException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate.AdoNet { @@ -18,6 +20,7 @@ public TooManyRowsAffectedException(String message, int expectedRowCount, int ac this.actualRowCount = actualRowCount; } +#if FEATURE_SERIALIZATION protected TooManyRowsAffectedException(SerializationInfo info, StreamingContext context) : base(info, context) { @@ -32,6 +35,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont info.AddValue("expectedRowCount", expectedRowCount); info.AddValue("actualRowCount", actualRowCount); } +#endif public int ExpectedRowCount { diff --git a/src/NHibernate/AssemblyInfo.cs b/src/NHibernate/AssemblyInfo.cs index 4fd3d6bd0e6..de5db6cca54 100644 --- a/src/NHibernate/AssemblyInfo.cs +++ b/src/NHibernate/AssemblyInfo.cs @@ -9,6 +9,8 @@ [assembly: AssemblyProductAttribute("NHibernate")] [assembly: AssemblyCopyrightAttribute("Licensed under LGPL.")] [assembly: AssemblyDelaySignAttribute(false)] +#if FEATURE_SECURITY_PERMISSIONS [assembly: AllowPartiallyTrustedCallersAttribute()] [assembly: SecurityRulesAttribute(SecurityRuleSet.Level1)] +#endif diff --git a/src/NHibernate/AssertionFailure.cs b/src/NHibernate/AssertionFailure.cs index b2436bce519..1917af70ff4 100644 --- a/src/NHibernate/AssertionFailure.cs +++ b/src/NHibernate/AssertionFailure.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate @@ -8,7 +11,7 @@ namespace NHibernate /// Indicates failure of an assertion: a possible bug in NHibernate /// [Serializable] - public class AssertionFailure : ApplicationException + public class AssertionFailure : Exception { private const string DefaultMessage = "An AssertionFailure occurred - this may indicate a bug in NHibernate or in your custom types."; @@ -43,6 +46,7 @@ public AssertionFailure(string message, Exception innerException) : base(message LoggerProvider.LoggerFor(typeof(AssertionFailure)).Error(DefaultMessage, innerException); } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class. /// @@ -56,5 +60,6 @@ public AssertionFailure(string message, Exception innerException) : base(message protected AssertionFailure(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } } diff --git a/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs b/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs index 16c7fcd6468..330583ab629 100644 --- a/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs +++ b/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using NHibernate.Properties; using NHibernate.Util; @@ -75,7 +76,7 @@ public virtual void SetProxyFactoryFactory(string typeName) throw new UnableToLoadProxyFactoryFactoryException(typeName, he); } - if (typeof(IProxyFactoryFactory).IsAssignableFrom(pffc) == false) + if (typeof(IProxyFactoryFactory).GetTypeInfo().IsAssignableFrom(pffc) == false) { var he = new HibernateByteCodeException(pffc.FullName + " does not implement " + typeof(IProxyFactoryFactory).FullName); throw he; @@ -116,4 +117,4 @@ public void SetCollectionTypeFactoryClass(System.Type type) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs b/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs index 617c218af14..7884c9e83fd 100644 --- a/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs +++ b/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs @@ -1,3 +1,5 @@ +#if FEATURE_CODEDOM + using System; using System.CodeDom.Compiler; using System.Reflection; @@ -19,7 +21,7 @@ public class BytecodeProviderImpl : AbstractBytecodeProvider public override IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) { - if (clazz.IsValueType) + if (clazz.GetTypeInfo().IsValueType) { // Cannot create optimizer for value types - the setter method will not work. log.Info("Disabling reflection optimizer for value type " + clazz.FullName); @@ -220,7 +222,7 @@ private string GenerateCode() { System.Type type = getters[i].ReturnType; - if (type.IsValueType) + if (type.GetTypeInfo().IsValueType) { sb.AppendFormat(" t.{0} = values[{2}] == null ? new {1}() : ({1})values[{2}];\n", setter.PropertyName, type.FullName.Replace('+', '.'), i); @@ -261,4 +263,6 @@ private string GenerateCode() #endregion } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Bytecode/EmitUtil.cs b/src/NHibernate/Bytecode/EmitUtil.cs index 4a73a594ba5..49e78a336ab 100644 --- a/src/NHibernate/Bytecode/EmitUtil.cs +++ b/src/NHibernate/Bytecode/EmitUtil.cs @@ -62,7 +62,7 @@ public static void EmitFastInt(ILGenerator il, int value) public static void EmitBoxIfNeeded(ILGenerator il, System.Type type) { - if (type.IsValueType) + if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, type); } @@ -103,7 +103,7 @@ static EmitUtil() public static void PreparePropertyForSet(ILGenerator il, System.Type propertyType) { // If this is a value type, we need to unbox it - if (propertyType.IsValueType) + if (propertyType.GetTypeInfo().IsValueType) { // if (object[i] == null), create a new instance Label notNullLabel = il.DefineLabel(); @@ -179,7 +179,7 @@ public static System.Type DefineDelegateType( methodBuilder.SetImplementationFlags( MethodImplAttributes.Runtime | MethodImplAttributes.Managed); - return delegateBuilder.CreateType(); + return delegateBuilder.CreateTypeInfo().AsType(); } public static void EmitLoadType(ILGenerator il, System.Type type) @@ -201,8 +201,11 @@ public static void EmitLoadMethodInfo(ILGenerator il, MethodInfo methodInfo) public static void EmitCreateDelegateInstance(ILGenerator il, System.Type delegateType, MethodInfo methodInfo) { MethodInfo createDelegate = typeof(Delegate).GetMethod( - "CreateDelegate", BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, null, - new System.Type[] {typeof(System.Type), typeof(MethodInfo)}, null); + "CreateDelegate", BindingFlags.Static | BindingFlags.Public +#if !NETSTANDARD + | BindingFlags.ExactBinding +#endif + , null, new System.Type[] {typeof(System.Type), typeof(MethodInfo)}, null); EmitLoadType(il, delegateType); EmitLoadMethodInfo(il, methodInfo); @@ -210,4 +213,4 @@ public static void EmitCreateDelegateInstance(ILGenerator il, System.Type delega il.Emit(OpCodes.Castclass, delegateType); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Bytecode/HibernateByteCodeException.cs b/src/NHibernate/Bytecode/HibernateByteCodeException.cs index 803765f88a7..8b9d5b89599 100644 --- a/src/NHibernate/Bytecode/HibernateByteCodeException.cs +++ b/src/NHibernate/Bytecode/HibernateByteCodeException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Bytecode { @@ -10,6 +13,8 @@ public HibernateByteCodeException() {} public HibernateByteCodeException(string message) : base(message) {} public HibernateByteCodeException(string message, Exception inner) : base(message, inner) {} +#if FEATURE_SERIALIZATION protected HibernateByteCodeException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs b/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs index c50a63fc71e..19e18ed2dea 100644 --- a/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs +++ b/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs @@ -1,10 +1,13 @@ using System.Reflection; using System.Reflection.Emit; using System.Security; -using System.Security.Permissions; using NHibernate.Properties; using NHibernate.Util; +#if FEATURE_SECURITY_PERMISSIONS +using System.Security.Permissions; +#endif + namespace NHibernate.Bytecode.Lightweight { public class ReflectionOptimizer : IReflectionOptimizer, IInstantiationOptimizer @@ -36,7 +39,7 @@ public ReflectionOptimizer(System.Type mappedType, IGetter[] getters, ISetter[] { // save off references this.mappedType = mappedType; - typeOfThis = mappedType.IsValueType ? mappedType.MakeByRefType() : mappedType; + typeOfThis = mappedType.GetTypeInfo().IsValueType ? mappedType.MakeByRefType() : mappedType; //this.getters = getters; //this.setters = setters; @@ -54,7 +57,7 @@ public ReflectionOptimizer(System.Type mappedType, IGetter[] getters, ISetter[] /// protected virtual CreateInstanceInvoker CreateCreateInstanceMethod(System.Type type) { - if (type.IsInterface || type.IsAbstract) + if (type.GetTypeInfo().IsInterface || type.GetTypeInfo().IsAbstract) { return null; } @@ -63,7 +66,7 @@ protected virtual CreateInstanceInvoker CreateCreateInstanceMethod(System.Type t ILGenerator il = method.GetILGenerator(); - if (type.IsValueType) + if (type.GetTypeInfo().IsValueType) { LocalBuilder tmpLocal = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca, tmpLocal); @@ -99,16 +102,20 @@ protected virtual void ThrowExceptionForNoDefaultCtor(System.Type type) protected DynamicMethod CreateDynamicMethod(System.Type returnType, System.Type[] argumentTypes) { - System.Type owner = mappedType.IsInterface ? typeof (object) : mappedType; + System.Type owner = mappedType.GetTypeInfo().IsInterface ? typeof (object) : mappedType; +#if FEATURE_SECURITY_PERMISSIONS #pragma warning disable 618 bool canSkipChecks = SecurityManager.IsGranted(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); #pragma warning restore 618 +#else + bool canSkipChecks = false; +#endif return new DynamicMethod(string.Empty, returnType, argumentTypes, owner, canSkipChecks); } private static void EmitCastToReference(ILGenerator il, System.Type type) { - if (type.IsValueType) + if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox, type); } diff --git a/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs b/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs index d432c6310b2..f6e2bd1f3a9 100644 --- a/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs +++ b/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Bytecode { @@ -13,8 +16,11 @@ public UnableToLoadProxyFactoryFactoryException(string typeName, Exception inner this.typeName = typeName; } +#if FEATURE_SERIALIZATION protected UnableToLoadProxyFactoryFactoryException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif + public override string Message { get @@ -34,4 +40,4 @@ public override string Message } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/CacheException.cs b/src/NHibernate/Cache/CacheException.cs index bb36a8bf039..153893b7a96 100644 --- a/src/NHibernate/Cache/CacheException.cs +++ b/src/NHibernate/Cache/CacheException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Cache { @@ -49,6 +52,7 @@ public CacheException(string message, Exception innerException) : base(message, { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -63,5 +67,6 @@ public CacheException(string message, Exception innerException) : base(message, protected CacheException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/UpdateTimestampsCache.cs b/src/NHibernate/Cache/UpdateTimestampsCache.cs index 2cd954a0b7f..406d00638ed 100644 --- a/src/NHibernate/Cache/UpdateTimestampsCache.cs +++ b/src/NHibernate/Cache/UpdateTimestampsCache.cs @@ -33,66 +33,72 @@ public UpdateTimestampsCache(Settings settings, IDictionary prop updateTimestamps = settings.CacheProvider.BuildCache(regionName, props); } - [MethodImpl(MethodImplOptions.Synchronized)] public void PreInvalidate(object[] spaces) { - //TODO: to handle concurrent writes correctly, this should return a Lock to the client - long ts = updateTimestamps.NextTimestamp() + updateTimestamps.Timeout; - for (int i = 0; i < spaces.Length; i++) + lock (this) { - updateTimestamps.Put(spaces[i], ts); + //TODO: to handle concurrent writes correctly, this should return a Lock to the client + long ts = updateTimestamps.NextTimestamp() + updateTimestamps.Timeout; + for (int i = 0; i < spaces.Length; i++) + { + updateTimestamps.Put(spaces[i], ts); + } + //TODO: return new Lock(ts); } - //TODO: return new Lock(ts); } /// - [MethodImpl(MethodImplOptions.Synchronized)] public void Invalidate(object[] spaces) { - //TODO: to handle concurrent writes correctly, the client should pass in a Lock - long ts = updateTimestamps.NextTimestamp(); - //TODO: if lock.getTimestamp().equals(ts) - for (int i = 0; i < spaces.Length; i++) + lock (this) { - log.Debug(string.Format("Invalidating space [{0}]", spaces[i])); - updateTimestamps.Put(spaces[i], ts); + //TODO: to handle concurrent writes correctly, the client should pass in a Lock + long ts = updateTimestamps.NextTimestamp(); + //TODO: if lock.getTimestamp().equals(ts) + for (int i = 0; i < spaces.Length; i++) + { + log.Debug(string.Format("Invalidating space [{0}]", spaces[i])); + updateTimestamps.Put(spaces[i], ts); + } } } - [MethodImpl(MethodImplOptions.Synchronized)] public bool IsUpToDate(ISet spaces, long timestamp /* H2.1 has Long here */) { - foreach (string space in spaces) + lock (this) { - object lastUpdate = updateTimestamps.Get(space); - if (lastUpdate == null) + foreach (string space in spaces) { - //the last update timestamp was lost from the cache - //(or there were no updates since startup!) + object lastUpdate = updateTimestamps.Get(space); + if (lastUpdate == null) + { + //the last update timestamp was lost from the cache + //(or there were no updates since startup!) - //NOTE: commented out, since users found the "safe" behavior - // counter-intuitive when testing, and we couldn't deal - // with all the forum posts :-( - //updateTimestamps.put( space, new Long( updateTimestamps.nextTimestamp() ) ); - //result = false; // safer + //NOTE: commented out, since users found the "safe" behavior + // counter-intuitive when testing, and we couldn't deal + // with all the forum posts :-( + //updateTimestamps.put( space, new Long( updateTimestamps.nextTimestamp() ) ); + //result = false; // safer - //OR: put a timestamp there, to avoid subsequent expensive - // lookups to a distributed cache - this is no good, since - // it is non-threadsafe (could hammer effect of an actual - // invalidation), and because this is not the way our - // preferred distributed caches work (they work by - // replication) - //updateTimestamps.put( space, new Long(Long.MIN_VALUE) ); - } - else - { - if ((long) lastUpdate >= timestamp) + //OR: put a timestamp there, to avoid subsequent expensive + // lookups to a distributed cache - this is no good, since + // it is non-threadsafe (could hammer effect of an actual + // invalidation), and because this is not the way our + // preferred distributed caches work (they work by + // replication) + //updateTimestamps.put( space, new Long(Long.MIN_VALUE) ); + } + else { - return false; + if ((long) lastUpdate >= timestamp) + { + return false; + } } } + return true; } - return true; } public void Destroy() diff --git a/src/NHibernate/CallbackException.cs b/src/NHibernate/CallbackException.cs index a0b3441eacc..55bc496e66c 100644 --- a/src/NHibernate/CallbackException.cs +++ b/src/NHibernate/CallbackException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -40,6 +43,7 @@ public CallbackException(string message, Exception innerException) : base(messag { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -54,5 +58,6 @@ public CallbackException(string message, Exception innerException) : base(messag protected CallbackException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } } diff --git a/src/NHibernate/Cfg/Configuration.cs b/src/NHibernate/Cfg/Configuration.cs index 06d1a168ee4..36b03a9a906 100644 --- a/src/NHibernate/Cfg/Configuration.cs +++ b/src/NHibernate/Cfg/Configuration.cs @@ -1,12 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; -using System.Security; using System.Text; using System.Xml; using System.Xml.Schema; @@ -25,11 +23,22 @@ using NHibernate.Impl; using NHibernate.Mapping; using NHibernate.Proxy; -using NHibernate.Tool.hbm2ddl; using NHibernate.Type; using NHibernate.Util; using Array = System.Array; + +#if FEATURE_SYSTEM_CONFIGURATION +using System.Configuration; +#endif + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +using System.Security; +#endif + +#if FEATURE_DATA_GETSCHEMATABLE +using NHibernate.Tool.hbm2ddl; +#endif namespace NHibernate.Cfg { @@ -49,7 +58,10 @@ namespace NHibernate.Cfg /// /// [Serializable] - public class Configuration : ISerializable + public class Configuration +#if FEATURE_SERIALIZATION + : ISerializable +#endif { /// Default name for hibernate configuration file. public const string DefaultHibernateCfgFileName = "hibernate.cfg.xml"; @@ -80,6 +92,7 @@ public class Configuration : ISerializable protected internal SettingsFactory settingsFactory; +#if FEATURE_SERIALIZATION #region ISerializable Members public Configuration(SerializationInfo info, StreamingContext context) { @@ -156,6 +169,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("filtersSecondPasses", filtersSecondPasses); } #endregion +#endif /// /// Clear the internal state of the object. @@ -350,25 +364,20 @@ private static void LogAndThrow(Exception exception) public Configuration AddXmlFile(string xmlFile) { log.Info("Mapping file: " + xmlFile); - XmlTextReader textReader = null; - try - { - textReader = new XmlTextReader(xmlFile); - AddXmlReader(textReader, xmlFile); - } - catch (MappingException) + using (TextReader streamReader = File.OpenText(xmlFile)) + using (XmlReader textReader = XmlReader.Create(streamReader)) { - throw; - } - catch (Exception e) - { - LogAndThrow(new MappingException("Could not configure datastore from file " + xmlFile, e)); - } - finally - { - if (textReader != null) + try + { + AddXmlReader(textReader, xmlFile); + } + catch (MappingException) + { + throw; + } + catch (Exception e) { - textReader.Close(); + LogAndThrow(new MappingException("Could not configure datastore from file " + xmlFile, e)); } } return this; @@ -392,28 +401,23 @@ public Configuration AddXml(string xml, string name) { log.Debug("Mapping XML:\n" + xml); } - XmlTextReader reader = null; - try + using (TextReader textReader = new StringReader(xml)) + using (XmlReader reader = XmlReader.Create(textReader)) { - reader = new XmlTextReader(xml, XmlNodeType.Document, null); - // make a StringReader for the string passed in - the StringReader - // inherits from TextReader. We can use the XmlTextReader.ctor that - // takes the TextReader to build from a string... - AddXmlReader(reader, name); - } - catch (MappingException) - { - throw; - } - catch (Exception e) - { - LogAndThrow(new MappingException("Could not configure datastore from XML string " + name, e)); - } - finally - { - if (reader != null) + try { - reader.Close(); + // make a StringReader for the string passed in - the StringReader + // inherits from TextReader. We can use the XmlTextReader.ctor that + // takes the TextReader to build from a string... + AddXmlReader(reader, name); + } + catch (MappingException) + { + throw; + } + catch (Exception e) + { + LogAndThrow(new MappingException("Could not configure datastore from XML string " + name, e)); } } return this; @@ -626,27 +630,21 @@ public Configuration AddInputStream(Stream xmlInputStream) /// public Configuration AddInputStream(Stream xmlInputStream, string name) { - XmlTextReader textReader = null; - try - { - textReader = new XmlTextReader(xmlInputStream); - AddXmlReader(textReader, name); - return this; - } - catch (MappingException) + using (XmlReader textReader = XmlReader.Create(xmlInputStream)) { - throw; - } - catch (Exception e) - { - LogAndThrow(new MappingException("Could not configure datastore from input stream " + name, e)); - return this; // To please the compiler - } - finally - { - if (textReader != null) + try + { + AddXmlReader(textReader, name); + return this; + } + catch (MappingException) { - textReader.Close(); + throw; + } + catch (Exception e) + { + LogAndThrow(new MappingException("Could not configure datastore from input stream " + name, e)); + return this; // To please the compiler } } } @@ -661,30 +659,25 @@ public Configuration AddResource(string path, Assembly assembly) { string debugName = path; log.Info("Mapping resource: " + debugName); - Stream rsrc = assembly.GetManifestResourceStream(path); - if (rsrc == null) + using (Stream rsrc = assembly.GetManifestResourceStream(path)) { - LogAndThrow(new MappingException("Resource not found: " + debugName)); - } + if (rsrc == null) + { + LogAndThrow(new MappingException("Resource not found: " + debugName)); + } - try - { - return AddInputStream(rsrc, debugName); - } - catch (MappingException) - { - throw; - } - catch (Exception e) - { - LogAndThrow(new MappingException("Could not configure datastore from resource " + debugName, e)); - return this; // To please the compiler - } - finally - { - if (rsrc != null) + try + { + return AddInputStream(rsrc, debugName); + } + catch (MappingException) + { + throw; + } + catch (Exception e) { - rsrc.Close(); + LogAndThrow(new MappingException("Could not configure datastore from resource " + debugName, e)); + return this; // To please the compiler } } } @@ -722,7 +715,7 @@ public Configuration AddResources(IEnumerable paths, Assembly assembly) /// public Configuration AddClass(System.Type persistentClass) { - return AddResource(persistentClass.FullName + ".hbm.xml", persistentClass.Assembly); + return AddResource(persistentClass.FullName + ".hbm.xml", persistentClass.GetTypeInfo().Assembly); } /// @@ -742,7 +735,7 @@ public Configuration AddAssembly(string assemblyName) Assembly assembly = null; try { - assembly = Assembly.Load(assemblyName); + assembly = Assembly.Load(new AssemblyName(assemblyName)); } catch (Exception e) { @@ -1252,8 +1245,10 @@ public ISessionFactory BuildSessionFactory() Environment.VerifyProperties(properties); Settings settings = BuildSettings(); +#if FEATURE_XML_SCHEMAS // Ok, don't need schemas anymore, so free them Schemas = null; +#endif return new SessionFactoryImpl(this, mapping, settings, GetInitializedEventListeners()); } @@ -1427,12 +1422,14 @@ private void AddProperties(ISessionFactoryConfiguration factoryConfiguration) /// public Configuration Configure() { +#if FEATURE_SYSTEM_CONFIGURATION var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as IHibernateConfiguration; if (hc != null && hc.SessionFactory != null) { return DoConfigure(hc.SessionFactory); } else +#endif { return Configure(GetDefaultConfigurationFilePath()); } @@ -1459,19 +1456,11 @@ private Configuration Configure(string fileName, bool ignoreSessionFactoryConfig properties = Environment.Properties; } - XmlTextReader reader = null; - try + using (TextReader streamReader = File.OpenText(fileName)) + using (XmlReader reader = XmlReader.Create(streamReader)) { - reader = new XmlTextReader(fileName); return Configure(reader); } - finally - { - if (reader != null) - { - reader.Close(); - } - } } /// @@ -1495,10 +1484,8 @@ public Configuration Configure(Assembly assembly, string resourceName) throw new HibernateException("Could not configure NHibernate.", new ArgumentNullException("resourceName")); } - Stream stream = null; - try + using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { - stream = assembly.GetManifestResourceStream(resourceName); if (stream == null) { // resource does not exist - throw appropriate exception @@ -1506,14 +1493,7 @@ public Configuration Configure(Assembly assembly, string resourceName) + " in Assembly " + assembly.FullName); } - return Configure(new XmlTextReader(stream)); - } - finally - { - if (stream != null) - { - stream.Close(); - } + return Configure(XmlReader.Create(stream)); } } @@ -1566,7 +1546,7 @@ protected Configuration DoConfigure(ISessionFactoryConfiguration factoryConfigur if (!string.IsNullOrEmpty(mc.Resource) && !string.IsNullOrEmpty(mc.Assembly)) { log.Debug(factoryConfiguration.Name + "<-" + mc.Resource + " in " + mc.Assembly); - AddResource(mc.Resource, Assembly.Load(mc.Assembly)); + AddResource(mc.Resource, Assembly.Load(new AssemblyName(mc.Assembly))); } else if (!string.IsNullOrEmpty(mc.Assembly)) { @@ -1794,8 +1774,16 @@ public void AddSqlFunction(string functionName, ISQLFunction sqlFunction) /// NamedXmlDocument containing the validated XmlDocument built from the XmlReader. public NamedXmlDocument LoadMappingDocument(XmlReader hbmReader, string name) { - XmlReaderSettings settings = Schemas.CreateMappingReaderSettings(); + XmlReaderSettings settings = +#if FEATURE_XML_SCHEMAS + Schemas.CreateMappingReaderSettings(); +#else + new XmlReaderSettings(); +#endif + +#if FEATURE_XML_VALIDATIONEVENTHANDLER settings.ValidationEventHandler += ValidationHandler; +#endif using (XmlReader reader = XmlReader.Create(hbmReader, settings)) { @@ -1866,19 +1854,26 @@ private void ProcessMappingsQueue() } } +#if FEATURE_XML_VALIDATIONEVENTHANDLER private void ValidationHandler(object o, ValidationEventArgs args) { string message = string.Format("{0}({1},{2}): XML validation error: {3}", currentDocumentName, args.Exception.LineNumber, args.Exception.LinePosition, args.Exception.Message); LogAndThrow(new MappingException(message, args.Exception)); } +#endif protected virtual string GetDefaultConfigurationFilePath() { +#if FEATURE_APPDOMAIN string baseDir = AppDomain.CurrentDomain.BaseDirectory; // Note RelativeSearchPath can be null even if the doc say something else; don't remove the check var searchPath = AppDomain.CurrentDomain.RelativeSearchPath ?? string.Empty; +#else + string baseDir = AppContext.BaseDirectory; + var searchPath = string.Empty; +#endif string relativeSearchPath = searchPath.Split(';').First(); string binPath = Path.Combine(baseDir, relativeSearchPath); @@ -1887,6 +1882,7 @@ protected virtual string GetDefaultConfigurationFilePath() #endregion +#if FEATURE_XML_SCHEMAS private XmlSchemas schemas; private XmlSchemas Schemas @@ -1894,6 +1890,7 @@ private XmlSchemas Schemas get { return schemas = schemas ?? new XmlSchemas(); } set { schemas = value; } } +#endif /// /// Set or clear listener for a given . @@ -2313,6 +2310,7 @@ private static T[] AppendListeners(T[] existing, T[] listenersToAdd) return list.ToArray(); } +#if FEATURE_DATA_GETSCHEMATABLE /// /// Generate DDL for altering tables /// @@ -2437,6 +2435,7 @@ public void ValidateSchema(Dialect.Dialect dialect, DatabaseMetadata databaseMet } } } +#endif private IEnumerable IterateGenerators(Dialect.Dialect dialect) { diff --git a/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs b/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs index ebe41928873..2608bc57daa 100644 --- a/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs +++ b/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Xml; using System.Xml.XPath; @@ -59,13 +60,21 @@ private HibernateConfiguration(XmlReader hbConfigurationReader, bool fromAppSett internal static HibernateConfiguration FromAppConfig(XmlNode node) { - XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Document, null); - return new HibernateConfiguration(reader, true); + using (TextReader textReader = new StringReader(node.OuterXml)) + using (XmlReader reader = XmlReader.Create(textReader)) + { + return new HibernateConfiguration(reader, true); + } } private XmlReaderSettings GetSettings() { - XmlReaderSettings xmlrs = (new XmlSchemas()).CreateConfigReaderSettings(); + XmlReaderSettings xmlrs = +#if FEATURE_XML_SCHEMAS + (new XmlSchemas()).CreateConfigReaderSettings(); +#else + new XmlReaderSettings(); +#endif return xmlrs; } diff --git a/src/NHibernate/Cfg/ConfigurationSectionHandler.cs b/src/NHibernate/Cfg/ConfigurationSectionHandler.cs index 5d3312bc2dc..e986c4c60b9 100644 --- a/src/NHibernate/Cfg/ConfigurationSectionHandler.cs +++ b/src/NHibernate/Cfg/ConfigurationSectionHandler.cs @@ -1,3 +1,5 @@ +#if FEATURE_SYSTEM_CONFIGURATION + using System; using System.Configuration; using System.Xml; @@ -19,4 +21,6 @@ object IConfigurationSectionHandler.Create(object parent, object configContext, #endregion } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Cfg/Environment.cs b/src/NHibernate/Cfg/Environment.cs index 9893ebab2d1..6d1e1d36ecc 100644 --- a/src/NHibernate/Cfg/Environment.cs +++ b/src/NHibernate/Cfg/Environment.cs @@ -1,12 +1,16 @@ using System; using System.Collections.Generic; -using System.Configuration; +using System.Linq; using System.Reflection; using NHibernate.Bytecode; using NHibernate.Cfg.ConfigurationSchema; using NHibernate.Util; +#if FEATURE_SYSTEM_CONFIGURATION +using System.Configuration; +#endif + namespace NHibernate.Cfg { /// @@ -47,10 +51,9 @@ public static string Version { if (cachedVersion == null) { - Assembly thisAssembly = Assembly.GetExecutingAssembly(); + Assembly thisAssembly = typeof(Environment).GetTypeInfo().Assembly; var attrs = - (AssemblyInformationalVersionAttribute[]) - thisAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); + thisAssembly.GetCustomAttributes().ToArray(); if (attrs != null && attrs.Length > 0) { @@ -233,6 +236,7 @@ static Environment() private static void LoadGlobalPropertiesFromAppConfig() { +#if FEATURE_SYSTEM_CONFIGURATION object config = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName); if (config == null) @@ -260,6 +264,7 @@ private static void LoadGlobalPropertiesFromAppConfig() GlobalProperties[kvp.Key] = kvp.Value; } } +#endif } internal static void ResetSessionFactoryProperties() @@ -343,8 +348,10 @@ private static IBytecodeProvider BuildBytecodeProvider(string providerName) { switch (providerName) { +#if FEATURE_CODEDOM case "codedom": return new Bytecode.CodeDom.BytecodeProviderImpl(); +#endif case "lcg": return new Bytecode.Lightweight.BytecodeProviderImpl(); case "null": diff --git a/src/NHibernate/Cfg/HibernateConfigException.cs b/src/NHibernate/Cfg/HibernateConfigException.cs index 4b04670b489..d0bf744311f 100644 --- a/src/NHibernate/Cfg/HibernateConfigException.cs +++ b/src/NHibernate/Cfg/HibernateConfigException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Cfg { @@ -57,6 +60,7 @@ public HibernateConfigException(string message, Exception innerException) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -72,5 +76,6 @@ protected HibernateConfigException(SerializationInfo info, StreamingContext cont : base(info, context) { } +#endif } } diff --git a/src/NHibernate/Cfg/Mappings.cs b/src/NHibernate/Cfg/Mappings.cs index ac1ab902233..6d1067b4fb4 100644 --- a/src/NHibernate/Cfg/Mappings.cs +++ b/src/NHibernate/Cfg/Mappings.cs @@ -538,7 +538,7 @@ public void AddColumnBinding(string logicalName, Column finalColumn, Table table if (oldFinalName != null && !(finalColumn.IsQuoted ? oldFinalName.Equals(finalColumn.GetQuotedName()) - : oldFinalName.Equals(finalColumn.GetQuotedName(), StringComparison.InvariantCultureIgnoreCase))) + : oldFinalName.Equals(finalColumn.GetQuotedName(), StringComparison.OrdinalIgnoreCase))) { //TODO possibly relax that throw new MappingException("Same logical column name referenced by different physical ones: " + table.Name + "." diff --git a/src/NHibernate/Cfg/MappingsQueue.cs b/src/NHibernate/Cfg/MappingsQueue.cs index b14e10526eb..d3da7c86d9e 100644 --- a/src/NHibernate/Cfg/MappingsQueue.cs +++ b/src/NHibernate/Cfg/MappingsQueue.cs @@ -1,4 +1,3 @@ -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,7 +9,7 @@ namespace NHibernate.Cfg /// public class MappingsQueue { - private readonly Queue availableEntries = new Queue(); + private readonly Queue availableEntries = new Queue(); private readonly ISet processedClassNames = new HashSet(); private readonly List unavailableEntries = new List(); @@ -109,4 +108,4 @@ private static string FormatExceptionMessage(IEnumerable res return message.ToString(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/SettingsFactory.cs b/src/NHibernate/Cfg/SettingsFactory.cs index 502a0dc4e4d..4404ba837e4 100644 --- a/src/NHibernate/Cfg/SettingsFactory.cs +++ b/src/NHibernate/Cfg/SettingsFactory.cs @@ -394,7 +394,13 @@ private static System.Type CreateLinqQueryProviderType(IDictionary properties) { string className = PropertiesHelper.GetString( - Environment.TransactionStrategy, properties, typeof(AdoNetWithDistributedTransactionFactory).FullName); + Environment.TransactionStrategy, properties +#if FEATURE_SYSTEM_TRANSACTIONS + , typeof(AdoNetWithDistributedTransactionFactory).FullName +#else + , typeof(AdoNetTransactionFactory).FullName // No distributed transactions for .NET Core +#endif + ); log.Info("Transaction factory: " + className); try diff --git a/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs index 7353478d59d..3539d71ccf2 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Mapping; using NHibernate.Type; using NHibernate.Util; @@ -230,7 +231,7 @@ private void BindCollection(ICollectionPropertiesMapping collectionMapping, Mapp if (!isGeneric.HasValue && containingType != null) { collectionType = GetPropertyType(containingType, collectionMapping.Name, collectionMapping.Access); - isGeneric = collectionType.IsGenericType; + isGeneric = collectionType.GetTypeInfo().IsGenericType; } model.IsGeneric = isGeneric.GetValueOrDefault(); diff --git a/src/NHibernate/Cfg/XmlHbmBinding/ColumnsBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/ColumnsBinder.cs index 3a06592157b..71db954a111 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/ColumnsBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/ColumnsBinder.cs @@ -76,7 +76,7 @@ private static void BindIndex(string indexAttribute, Table table, Column column) if (indexAttribute != null && table != null) { var tokens = indexAttribute.Split(','); - System.Array.ForEach(tokens, t => table.GetOrCreateIndex(t.Trim()).AddColumn(column)); + tokens.ForEach(t => table.GetOrCreateIndex(t.Trim()).AddColumn(column)); } } @@ -85,8 +85,8 @@ private static void BindUniqueKey(string uniqueKeyAttribute, Table table, Column if (uniqueKeyAttribute != null && table != null) { var tokens = uniqueKeyAttribute.Split(','); - System.Array.ForEach(tokens, t => table.GetOrCreateUniqueKey(t.Trim()).AddColumn(column)); + tokens.ForEach(t => table.GetOrCreateUniqueKey(t.Trim()).AddColumn(column)); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs index a68eef4fbad..a5b301f579d 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs @@ -109,13 +109,13 @@ private void AddSubclasses(HbmSubclass subClass, IDictionary properties, Table table, ID } else if ((anyMapping = entityPropertyMapping as HbmAny) != null) { +#if FEATURE_SERIALIZATION var value = new Any(table); BindAny(anyMapping, value, true); property = CreateProperty(entityPropertyMapping, className, value, inheritedMetas); BindAnyProperty(anyMapping, property); +#else + throw new NotImplementedException(string.Format("HbmAny not valid in .NET Core for property {0}", anyMapping.Name)); +#endif } else if ((nestedCompositeElementMapping = entityPropertyMapping as HbmNestedCompositeElement) != null) { @@ -361,12 +365,13 @@ private void BindComponentProperty(HbmComponent componentMapping, Property prope HbmTuplizer[] tuplizers = componentMapping.tuplizer; if (tuplizers != null) { - Array.ForEach(tuplizers.Select(tuplizer => new - { - TuplizerClassName = FullQualifiedClassName(tuplizer.@class, mappings), - Mode = tuplizer.entitymode.ToEntityMode() - }).ToArray(), - x => model.AddTuplizer(x.Mode, x.TuplizerClassName)); + tuplizers.Select( + tuplizer => new + { + TuplizerClassName = FullQualifiedClassName(tuplizer.@class, mappings), + Mode = tuplizer.entitymode.ToEntityMode() + }) + .ForEach(x => model.AddTuplizer(x.Mode, x.TuplizerClassName)); } } @@ -421,4 +426,4 @@ private string GetPropertyAccessorName(string propertyMappedAccessor) return propertyMappedAccessor ?? Mappings.DefaultAccess; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/TypeBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/TypeBinder.cs index 07bcf480478..02021912a03 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/TypeBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/TypeBinder.cs @@ -44,7 +44,7 @@ public void Bind(HbmType typeMapping) var parameters = new Dictionary(); if(typeMapping.param != null) { - System.Array.ForEach(typeMapping.param, p => parameters[p.name] = p.Text.LinesToString()); + typeMapping.param.ForEach(p => parameters[p.name] = p.Text.LinesToString()); } BindThroughTypeDefOrType(originalTypeName, parameters); @@ -83,4 +83,4 @@ private void BindThroughTypeDefOrType(string originalTypeName, IDictionary /// Initializes a new instance of the class /// with serialized data. @@ -64,5 +68,6 @@ public ValidationFailure(string message, Exception innerException) : base(messag protected ValidationFailure(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } } diff --git a/src/NHibernate/Compat/AppContext.cs b/src/NHibernate/Compat/AppContext.cs new file mode 100644 index 00000000000..dd7cedc6936 --- /dev/null +++ b/src/NHibernate/Compat/AppContext.cs @@ -0,0 +1,13 @@ +#if NET_4_0 +namespace System +{ + internal static class AppContext + { + /// Gets the pathname of the base directory that the assembly resolver uses to probe for assemblies. + public static string BaseDirectory + { + get { return AppDomain.CurrentDomain.BaseDirectory; } + } + } +} +#endif diff --git a/src/NHibernate/Compat/DesignerCategoryAttribute.cs b/src/NHibernate/Compat/DesignerCategoryAttribute.cs new file mode 100644 index 00000000000..c88655b2035 --- /dev/null +++ b/src/NHibernate/Compat/DesignerCategoryAttribute.cs @@ -0,0 +1,13 @@ +#if NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System.ComponentModel +{ + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] + internal class DesignerCategoryAttribute : Attribute + { + public DesignerCategoryAttribute(string category) + { + } + } +} +#endif diff --git a/src/NHibernate/Compat/ICloneable.cs b/src/NHibernate/Compat/ICloneable.cs new file mode 100644 index 00000000000..2ab0becc7fd --- /dev/null +++ b/src/NHibernate/Compat/ICloneable.cs @@ -0,0 +1,11 @@ +#if FEATURE_NETCORE_ICLONEABLE_API +// ReSharper disable once CheckNamespace +namespace System +{ + public interface ICloneable + { + object Clone(); + } +} +#endif + diff --git a/src/NHibernate/Compat/InvalidExpressionException.cs b/src/NHibernate/Compat/InvalidExpressionException.cs new file mode 100644 index 00000000000..3599a256912 --- /dev/null +++ b/src/NHibernate/Compat/InvalidExpressionException.cs @@ -0,0 +1,22 @@ +#if NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System.Data +{ + public class InvalidExpressionException : System.Exception + { + public InvalidExpressionException() + { + } + + public InvalidExpressionException(string s) + : base(s) + { + } + + public InvalidExpressionException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} +#endif diff --git a/src/NHibernate/Compat/NonSerializedAttribute.cs b/src/NHibernate/Compat/NonSerializedAttribute.cs new file mode 100644 index 00000000000..05107a66013 --- /dev/null +++ b/src/NHibernate/Compat/NonSerializedAttribute.cs @@ -0,0 +1,10 @@ +#if !FEATURE_SERIALIZATION && NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System +{ + [AttributeUsage(AttributeTargets.Field, Inherited = false)] + internal sealed class NonSerializedAttribute : Attribute + { + } +} +#endif diff --git a/src/NHibernate/Compat/SerializableAttribute.cs b/src/NHibernate/Compat/SerializableAttribute.cs new file mode 100644 index 00000000000..e12a812f14f --- /dev/null +++ b/src/NHibernate/Compat/SerializableAttribute.cs @@ -0,0 +1,10 @@ +#if !FEATURE_SERIALIZATION && NETSTANDARD +// ReSharper disable once CheckNamespace +namespace System +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] + internal sealed class SerializableAttribute : Attribute + { + } +} +#endif diff --git a/src/NHibernate/Compat/TypeReflectionExtensions.cs b/src/NHibernate/Compat/TypeReflectionExtensions.cs new file mode 100644 index 00000000000..9e174dd0984 --- /dev/null +++ b/src/NHibernate/Compat/TypeReflectionExtensions.cs @@ -0,0 +1,43 @@ +#if FEATURE_NETCORE_REFLECTION_API + +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace NHibernate +{ + internal static class TypeReflectionExtensions + { + public static MethodInfo GetMethod(this System.Type type, string name, BindingFlags bindingAttr, object binder, + System.Type[] types, ParameterModifier[] modifiers) + { + return type.GetMethods(bindingAttr) + .FirstOrDefault(m => m.Name == name && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(types)); + } + + public static PropertyInfo GetProperty(this System.Type type, string name, BindingFlags bindingAttr, System.Type returnType, object binder, + System.Type[] types, ParameterModifier[] modifiers) + { + return type.GetProperties(bindingAttr) + .FirstOrDefault(m => m.Name == name + && (returnType == null || m.PropertyType == returnType) + && (type == null || m.GetIndexParameters().Select(p => p.ParameterType).SequenceEqual(types))); + } + + public static ConstructorInfo GetConstructor(this System.Type type, BindingFlags bindingAttr, object binder, + System.Type[] types, ParameterModifier[] modifiers) + { + return type.GetConstructors(bindingAttr) + .FirstOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(types)); + } + + public static ConstructorInfo GetConstructor(this System.Type type, BindingFlags bindingAttr, object binder, + CallingConventions callingConventions, System.Type[] types, ParameterModifier[] modifiers) + { + return type.GetConstructors(bindingAttr) + .FirstOrDefault(m => m.CallingConvention.HasFlag(callingConventions) && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(types)); + } + } +} + +#endif diff --git a/src/NHibernate/Connection/ConnectionProvider.cs b/src/NHibernate/Connection/ConnectionProvider.cs index 8be053981e8..819b9fa3be1 100644 --- a/src/NHibernate/Connection/ConnectionProvider.cs +++ b/src/NHibernate/Connection/ConnectionProvider.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Configuration; using System.Data.Common; using NHibernate.Driver; @@ -8,6 +7,10 @@ using Environment=NHibernate.Cfg.Environment; using System.Collections.Generic; +#if FEATURE_SYSTEM_CONFIGURATION +using System.Configuration; +#endif + namespace NHibernate.Connection { /// @@ -73,6 +76,7 @@ public virtual void Configure(IDictionary settings) /// protected virtual string GetNamedConnectionString(IDictionary settings) { +#if FEATURE_SYSTEM_CONFIGURATION string connStringName; if(!settings.TryGetValue(Environment.ConnectionStringName, out connStringName)) return null; @@ -81,6 +85,9 @@ protected virtual string GetNamedConnectionString(IDictionary se if (connectionStringSettings == null) throw new HibernateException(string.Format("Could not find named connection string {0}", connStringName)); return connectionStringSettings.ConnectionString; +#else + return null; +#endif } /// diff --git a/src/NHibernate/Context/CallSessionContext.cs b/src/NHibernate/Context/CallSessionContext.cs index 9b6d2b3ce83..92325cb22ef 100644 --- a/src/NHibernate/Context/CallSessionContext.cs +++ b/src/NHibernate/Context/CallSessionContext.cs @@ -1,3 +1,5 @@ +#if FEATURE_REMOTING + using System; using System.Collections; using System.Runtime.Remoting.Messaging; @@ -36,4 +38,6 @@ protected override IDictionary GetMap() return CallContext.GetData(SessionFactoryMapKey) as IDictionary; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Context/ReflectiveHttpContext.cs b/src/NHibernate/Context/ReflectiveHttpContext.cs index 72b6adc2230..5004a1810eb 100644 --- a/src/NHibernate/Context/ReflectiveHttpContext.cs +++ b/src/NHibernate/Context/ReflectiveHttpContext.cs @@ -1,3 +1,5 @@ +#if FEATURE_WEB_SESSION_CONTEXT + using System; using System.Collections; using System.Linq.Expressions; @@ -54,4 +56,6 @@ private static void CreateHttpContextItemsGetter() HttpContextItemsGetter = (Func) Expression.Lambda(itemsProperty, contextParam).Compile(); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Context/WcfOperationSessionContext.cs b/src/NHibernate/Context/WcfOperationSessionContext.cs index 29a91ce305d..a4bcec6fade 100644 --- a/src/NHibernate/Context/WcfOperationSessionContext.cs +++ b/src/NHibernate/Context/WcfOperationSessionContext.cs @@ -1,3 +1,5 @@ +#if FEATURE_SYSTEM_SERVICEMODEL + using System; using System.Collections; using System.ServiceModel; @@ -49,4 +51,6 @@ public class WcfStateExtension : IExtension public void Attach(OperationContext owner) { } public void Detach(OperationContext owner) { } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Context/WebSessionContext.cs b/src/NHibernate/Context/WebSessionContext.cs index 3f30059be79..b169f765860 100644 --- a/src/NHibernate/Context/WebSessionContext.cs +++ b/src/NHibernate/Context/WebSessionContext.cs @@ -1,3 +1,5 @@ +#if FEATURE_WEB_SESSION_CONTEXT + using System; using System.Collections; using NHibernate.Engine; @@ -25,4 +27,6 @@ protected override void SetMap(IDictionary value) ReflectiveHttpContext.HttpContextCurrentItems[SessionFactoryMapKey] = value; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Criterion/CriterionUtil.cs b/src/NHibernate/Criterion/CriterionUtil.cs index 3ec77b24cca..2c5f09ba09e 100644 --- a/src/NHibernate/Criterion/CriterionUtil.cs +++ b/src/NHibernate/Criterion/CriterionUtil.cs @@ -2,6 +2,8 @@ namespace NHibernate.Criterion { using System; using System.Collections.Generic; + using System.Linq; + using System.Reflection; using Engine; using SqlCommand; using Type; @@ -62,7 +64,7 @@ internal static SqlString[] GetColumnNamesUsingProjection(IProjection projection private static SqlString[] GetColumnNamesUsingPropertyName(ICriteriaQuery criteriaQuery, ICriteria criteria, string propertyName) { string[] columnNames = criteriaQuery.GetColumnsUsingProjection(criteria, propertyName); - return Array.ConvertAll(columnNames, delegate(string input) { return new SqlString(input); }); + return columnNames.Select(input => new SqlString(input)).ToArray(); } private static SqlString[] GetColumnNamesUsingPropertyName( @@ -89,10 +91,7 @@ private static SqlString[] GetColumnNamesUsingPropertyName( + " use ICriteria.CreateCriteria instead", criteriaQuery.GetEntityName(criteria), propertyName)); } - return Array.ConvertAll(columnNames, delegate(string col) - { - return new SqlString(col); - }); + return columnNames.Select(col => new SqlString(col)).ToArray(); } public static TypedValue[] GetTypedValues(ICriteriaQuery criteriaQuery, ICriteria criteria, diff --git a/src/NHibernate/Criterion/ProjectionsExtensions.cs b/src/NHibernate/Criterion/ProjectionsExtensions.cs index 6a4dd0e53f2..9c2c2d47b3e 100644 --- a/src/NHibernate/Criterion/ProjectionsExtensions.cs +++ b/src/NHibernate/Criterion/ProjectionsExtensions.cs @@ -375,7 +375,7 @@ internal static IProjection ProcessCoalesce(MethodCallExpression methodCallExpre { IProjection property = ExpressionProcessor.FindMemberProjection(methodCallExpression.Arguments[0]).AsProjection(); object replaceValueIfIsNull = ExpressionProcessor.FindValue(methodCallExpression.Arguments[1]); - return Projections.SqlFunction("coalesce", NHibernateUtil.Object, property, Projections.Constant(replaceValueIfIsNull)); + return Projections.SqlFunction("coalesce", new Type.CoalesceType(), property, Projections.Constant(replaceValueIfIsNull)); } /// diff --git a/src/NHibernate/Criterion/SimpleExpression.cs b/src/NHibernate/Criterion/SimpleExpression.cs index bd82e7c71cf..722c9c1a189 100644 --- a/src/NHibernate/Criterion/SimpleExpression.cs +++ b/src/NHibernate/Criterion/SimpleExpression.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.Type; @@ -200,7 +201,7 @@ private string ValueToStrings() return "null"; } var type = value.GetType(); - if (type.IsPrimitive || CallToStringTypes.Any(t => t.IsAssignableFrom(type))) + if (type.GetTypeInfo().IsPrimitive || CallToStringTypes.Any(t => t.GetTypeInfo().IsAssignableFrom(type))) { return value.ToString(); } diff --git a/src/NHibernate/Dialect/BitwiseFunctionOperation.cs b/src/NHibernate/Dialect/BitwiseFunctionOperation.cs index 43faa74fa63..afe5ec49e0b 100644 --- a/src/NHibernate/Dialect/BitwiseFunctionOperation.cs +++ b/src/NHibernate/Dialect/BitwiseFunctionOperation.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using NHibernate.Dialect.Function; using NHibernate.Engine; using NHibernate.SqlCommand; @@ -15,7 +16,7 @@ public class BitwiseFunctionOperation : ISQLFunction { private readonly string _functionName; private SqlStringBuilder _sqlBuffer; - private Queue _args; + private Queue _args; /// /// Creates an instance of this class using the provided function name @@ -62,7 +63,7 @@ public SqlString Render(IList args, ISessionFactoryImplementor factory) private void Prepare(IList args) { _sqlBuffer = new SqlStringBuilder(); - _args = new Queue(); + _args = new Queue(); foreach (var arg in args) { if (!IsParens(arg.ToString())) diff --git a/src/NHibernate/Dialect/BitwiseNativeOperation.cs b/src/NHibernate/Dialect/BitwiseNativeOperation.cs index 7d31ae59c64..baba3b813fa 100644 --- a/src/NHibernate/Dialect/BitwiseNativeOperation.cs +++ b/src/NHibernate/Dialect/BitwiseNativeOperation.cs @@ -1,5 +1,7 @@ using System; using System.Collections; +using System.Collections.Generic; +using System.Linq; using NHibernate.Dialect.Function; using NHibernate.Engine; using NHibernate.SqlCommand; @@ -15,7 +17,7 @@ public class BitwiseNativeOperation : ISQLFunction { private readonly string _sqlOpToken; private readonly bool _isNot; - private Queue _args; + private Queue _args; private SqlStringBuilder _sqlBuffer; /// @@ -76,7 +78,7 @@ public SqlString Render(IList args, ISessionFactoryImplementor factory) private void Prepare(IList args) { _sqlBuffer = new SqlStringBuilder(); - _args = new Queue(args); + _args = new Queue(args.Cast()); } private void AddFirstArgument() diff --git a/src/NHibernate/Dialect/Dialect.cs b/src/NHibernate/Dialect/Dialect.cs index c9240005f95..4e2692ec924 100644 --- a/src/NHibernate/Dialect/Dialect.cs +++ b/src/NHibernate/Dialect/Dialect.cs @@ -426,10 +426,12 @@ public virtual bool SupportsNotNullUnique get { return true; } } +#if FEATURE_DATA_GETSCHEMATABLE public virtual IDataBaseSchema GetDataBaseSchema(DbConnection connection) { throw new NotSupportedException(); } +#endif #endregion @@ -2276,4 +2278,4 @@ public virtual ISQLExceptionConverter BuildSQLExceptionConverter() return new SQLStateConverter(ViolatedConstraintNameExtracter); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/FirebirdDialect.cs b/src/NHibernate/Dialect/FirebirdDialect.cs index be3949adf42..2f9c6b7df64 100644 --- a/src/NHibernate/Dialect/FirebirdDialect.cs +++ b/src/NHibernate/Dialect/FirebirdDialect.cs @@ -188,10 +188,12 @@ public override SqlString Render(IList args, ISessionFactoryImplementor factory) } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new FirebirdDataBaseSchema(connection); } +#endif public override string QuerySequencesString { @@ -426,4 +428,4 @@ private static bool IsUnallowedDecimal(DbType dbType, int precision) return dbType == DbType.Decimal && precision > MAX_DECIMAL_PRECISION; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Function/CastFunction.cs b/src/NHibernate/Dialect/Function/CastFunction.cs index cd1325014c3..747dd90440a 100644 --- a/src/NHibernate/Dialect/Function/CastFunction.cs +++ b/src/NHibernate/Dialect/Function/CastFunction.cs @@ -92,7 +92,7 @@ protected virtual bool CastingIsRequired(string sqlType) bool IFunctionGrammar.IsSeparator(string token) { - return "as".Equals(token, StringComparison.InvariantCultureIgnoreCase); + return "as".Equals(token, StringComparison.OrdinalIgnoreCase); } bool IFunctionGrammar.IsKnownArgument(string token) diff --git a/src/NHibernate/Dialect/Function/SQLFunctionRegistry.cs b/src/NHibernate/Dialect/Function/SQLFunctionRegistry.cs index 858b6227440..f060b97da64 100644 --- a/src/NHibernate/Dialect/Function/SQLFunctionRegistry.cs +++ b/src/NHibernate/Dialect/Function/SQLFunctionRegistry.cs @@ -12,7 +12,7 @@ public SQLFunctionRegistry(Dialect dialect, IDictionary us { this.dialect = dialect; this.userFunctions = new Dictionary(userFunctions, - StringComparer.InvariantCultureIgnoreCase); + StringComparer.OrdinalIgnoreCase); } public ISQLFunction FindSQLFunction(string functionName) diff --git a/src/NHibernate/Dialect/Lock/SelectLockingStrategy.cs b/src/NHibernate/Dialect/Lock/SelectLockingStrategy.cs index 4bf763d451d..65e821ebbfb 100644 --- a/src/NHibernate/Dialect/Lock/SelectLockingStrategy.cs +++ b/src/NHibernate/Dialect/Lock/SelectLockingStrategy.cs @@ -67,8 +67,7 @@ public void Lock(object id, object version, object obj, ISessionImplementor sess lockable.VersionType.NullSafeSet(st, version, lockable.IdentifierType.GetColumnSpan(factory), session); } - rs = session.Batcher.ExecuteReader(st); - try + using (rs = session.Batcher.ExecuteReader(st)) { if (!rs.Read()) { @@ -79,10 +78,6 @@ public void Lock(object id, object version, object obj, ISessionImplementor sess throw new StaleObjectStateException(lockable.EntityName, id); } } - finally - { - rs.Close(); - } } finally { @@ -110,4 +105,4 @@ public void Lock(object id, object version, object obj, ISessionImplementor sess #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/MsSql2000Dialect.cs b/src/NHibernate/Dialect/MsSql2000Dialect.cs index a2c41524352..d84442077f1 100644 --- a/src/NHibernate/Dialect/MsSql2000Dialect.cs +++ b/src/NHibernate/Dialect/MsSql2000Dialect.cs @@ -483,10 +483,12 @@ public override bool SupportsCircularCascadeDeleteConstraints } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new MsSqlDataBaseSchema(connection); } +#endif public override bool SupportsUnionAll { diff --git a/src/NHibernate/Dialect/MsSqlCeDialect.cs b/src/NHibernate/Dialect/MsSqlCeDialect.cs index 9c54ff9c4b9..5d5296d5c2d 100644 --- a/src/NHibernate/Dialect/MsSqlCeDialect.cs +++ b/src/NHibernate/Dialect/MsSqlCeDialect.cs @@ -124,10 +124,12 @@ public override bool SupportsLimitOffset get { return false; } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new MsSqlCeDataBaseSchema(connection); } +#endif public override SqlString GetLimitString(SqlString querySqlString, SqlString offset, SqlString limit) { @@ -203,4 +205,4 @@ public override long TimestampResolutionInTicks } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/MySQLDialect.cs b/src/NHibernate/Dialect/MySQLDialect.cs index 5c8865985ee..92e3aca87a3 100644 --- a/src/NHibernate/Dialect/MySQLDialect.cs +++ b/src/NHibernate/Dialect/MySQLDialect.cs @@ -234,10 +234,12 @@ public override bool SupportsLimit get { return true; } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new MySQLDataBaseSchema(connection); } +#endif public override bool SupportsSubSelects { @@ -387,4 +389,4 @@ public override long TimestampResolutionInTicks } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Oracle8iDialect.cs b/src/NHibernate/Dialect/Oracle8iDialect.cs index 323c0ed4a56..ffb7f8a2e0b 100644 --- a/src/NHibernate/Dialect/Oracle8iDialect.cs +++ b/src/NHibernate/Dialect/Oracle8iDialect.cs @@ -449,10 +449,12 @@ public override bool SupportsCurrentTimestampSelection get { return true; } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new OracleDataBaseSchema(connection); } +#endif public override long TimestampResolutionInTicks { @@ -536,4 +538,4 @@ public SqlString Render(IList args, ISessionFactoryImplementor factory) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/PostgreSQLDialect.cs b/src/NHibernate/Dialect/PostgreSQLDialect.cs index 2bb45c861f3..225bb4d8e68 100644 --- a/src/NHibernate/Dialect/PostgreSQLDialect.cs +++ b/src/NHibernate/Dialect/PostgreSQLDialect.cs @@ -229,11 +229,13 @@ public override string SelectGUIDString { get { return "select uuid_generate_v4()"; } } - + +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new PostgreSQLDataBaseMetadata(connection); } +#endif public override long TimestampResolutionInTicks { diff --git a/src/NHibernate/Dialect/SQLiteDialect.cs b/src/NHibernate/Dialect/SQLiteDialect.cs index 52d8ae8642e..ad05c1d1f77 100644 --- a/src/NHibernate/Dialect/SQLiteDialect.cs +++ b/src/NHibernate/Dialect/SQLiteDialect.cs @@ -125,10 +125,12 @@ protected virtual void RegisterDefaultProperties() DefaultProperties[Cfg.Environment.QuerySubstitutions] = "true 1, false 0, yes 'Y', no 'N'"; } +#if FEATURE_DATA_GETSCHEMATABLE public override Schema.IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new Schema.SQLiteDataBaseMetaData(connection); } +#endif public override string AddColumnString { @@ -344,4 +346,4 @@ protected override bool CastingIsRequired(string sqlType) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Schema/AbstractColumnMetaData.cs b/src/NHibernate/Dialect/Schema/AbstractColumnMetaData.cs index 85baf887f00..60c790dd57b 100644 --- a/src/NHibernate/Dialect/Schema/AbstractColumnMetaData.cs +++ b/src/NHibernate/Dialect/Schema/AbstractColumnMetaData.cs @@ -11,7 +11,7 @@ public abstract class AbstractColumnMetaData : IColumnMetadata private int numericalPrecision; private string isNullable; - public AbstractColumnMetaData(DataRow rs) + protected AbstractColumnMetaData() { } @@ -67,4 +67,4 @@ protected void SetNumericalPrecision(object numericalPrecisionValue) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs b/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs index 66e4b986ab4..01809a00625 100644 --- a/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs +++ b/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Collections.Generic; using System.Data; using System.Data.Common; @@ -109,4 +111,6 @@ protected virtual string ForeignKeysSchemaName #endregion } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/AbstractForeignKeyMetadata.cs b/src/NHibernate/Dialect/Schema/AbstractForeignKeyMetadata.cs index 2c0da115766..0ad560fbf04 100644 --- a/src/NHibernate/Dialect/Schema/AbstractForeignKeyMetadata.cs +++ b/src/NHibernate/Dialect/Schema/AbstractForeignKeyMetadata.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Collections.Generic; using System.Data; @@ -33,4 +35,6 @@ public override string ToString() return "ForeignKeyMetadata(" + name + ')'; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/AbstractIndexMetadata.cs b/src/NHibernate/Dialect/Schema/AbstractIndexMetadata.cs index 5327d7de75b..4a43e009cb6 100644 --- a/src/NHibernate/Dialect/Schema/AbstractIndexMetadata.cs +++ b/src/NHibernate/Dialect/Schema/AbstractIndexMetadata.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections.Generic; using System.Data; @@ -34,4 +36,6 @@ public override string ToString() return "IndexMatadata(" + name + ')'; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs b/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs index f550b6bee92..1153d37cd42 100644 --- a/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs +++ b/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Collections.Generic; using System.Data; using NHibernate.Util; @@ -167,4 +169,6 @@ private void InitColumns(IDataBaseSchema meta) } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/FirebirdMetaData.cs b/src/NHibernate/Dialect/Schema/FirebirdMetaData.cs index 8a9b42021c4..d2c246e6bc9 100644 --- a/src/NHibernate/Dialect/Schema/FirebirdMetaData.cs +++ b/src/NHibernate/Dialect/Schema/FirebirdMetaData.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; using System.Data.Common; @@ -66,7 +68,7 @@ protected override IIndexMetadata GetIndexMetadata(DataRow rs) public class FirebirdColumnMetadata : AbstractColumnMetaData { public FirebirdColumnMetadata(DataRow rs) - : base(rs) + : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -97,3 +99,5 @@ public FirebirdForeignKeyMetadata(DataRow rs) } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/IDataBaseSchema.cs b/src/NHibernate/Dialect/Schema/IDataBaseSchema.cs index d7e29207163..e5232af1790 100644 --- a/src/NHibernate/Dialect/Schema/IDataBaseSchema.cs +++ b/src/NHibernate/Dialect/Schema/IDataBaseSchema.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Collections.Generic; using System.Data; @@ -124,3 +126,5 @@ public interface IDataBaseSchema ISet GetReservedWords(); } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/MsSqlCeMetaData.cs b/src/NHibernate/Dialect/Schema/MsSqlCeMetaData.cs index 12671a58d67..31c744f98f8 100644 --- a/src/NHibernate/Dialect/Schema/MsSqlCeMetaData.cs +++ b/src/NHibernate/Dialect/Schema/MsSqlCeMetaData.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; using System.Data.Common; @@ -60,7 +62,7 @@ protected override IIndexMetadata GetIndexMetadata(DataRow rs) public class MsSqlCeColumnMetadata : AbstractColumnMetaData { - public MsSqlCeColumnMetadata(DataRow rs) : base(rs) + public MsSqlCeColumnMetadata(DataRow rs) : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -89,3 +91,5 @@ public MsSqlCeForeignKeyMetadata(DataRow rs) } } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/MsSqlMetaData.cs b/src/NHibernate/Dialect/Schema/MsSqlMetaData.cs index 230f6088df0..41fc7d77df3 100644 --- a/src/NHibernate/Dialect/Schema/MsSqlMetaData.cs +++ b/src/NHibernate/Dialect/Schema/MsSqlMetaData.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; using System.Data.Common; @@ -61,7 +63,7 @@ protected override IIndexMetadata GetIndexMetadata(DataRow rs) public class MsSqlColumnMetadata : AbstractColumnMetaData { - public MsSqlColumnMetadata(DataRow rs) : base(rs) + public MsSqlColumnMetadata(DataRow rs) : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -94,3 +96,5 @@ public MsSqlForeignKeyMetadata(DataRow rs) } } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/MySQLMetaData.cs b/src/NHibernate/Dialect/Schema/MySQLMetaData.cs index db5ef43a6cf..2b6caef04b6 100644 --- a/src/NHibernate/Dialect/Schema/MySQLMetaData.cs +++ b/src/NHibernate/Dialect/Schema/MySQLMetaData.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; using System.Data.Common; @@ -70,7 +72,7 @@ protected override IIndexMetadata GetIndexMetadata(DataRow rs) public class MySQLColumnMetadata : AbstractColumnMetaData { public MySQLColumnMetadata(DataRow rs) - : base(rs) + : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -100,3 +102,5 @@ public MySQLForeignKeyMetadata(DataRow rs) } } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/OracleMetaData.cs b/src/NHibernate/Dialect/Schema/OracleMetaData.cs index fc72bfff630..029f28563b3 100644 --- a/src/NHibernate/Dialect/Schema/OracleMetaData.cs +++ b/src/NHibernate/Dialect/Schema/OracleMetaData.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; using System.Data.Common; @@ -100,7 +102,7 @@ protected override IIndexMetadata GetIndexMetadata(DataRow rs) public class OracleColumnMetadata : AbstractColumnMetaData { public OracleColumnMetadata(DataRow rs) - : base(rs) + : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -130,3 +132,5 @@ public OracleForeignKeyMetadata(DataRow rs) } } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/PostgreSQLMetadata.cs b/src/NHibernate/Dialect/Schema/PostgreSQLMetadata.cs index bbb4c4369c7..380e71cf912 100644 --- a/src/NHibernate/Dialect/Schema/PostgreSQLMetadata.cs +++ b/src/NHibernate/Dialect/Schema/PostgreSQLMetadata.cs @@ -1,4 +1,6 @@ -using System; +#if FEATURE_DATA_GETSCHEMATABLE + +using System; using System.Data; using System.Data.Common; using System.Globalization; @@ -129,7 +131,7 @@ protected override void ParseTableInfo(DataRow rs) public class PostgreSQLColumnMetadata : AbstractColumnMetaData { public PostgreSQLColumnMetadata(DataRow rs) - : base(rs) + : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -158,4 +160,6 @@ public PostgreSQLForeignKeyMetadata(DataRow rs) Name = Convert.ToString(rs["CONSTRAINT_NAME"]); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs b/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs index 8be4242acce..a2eadf40a5a 100644 --- a/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs +++ b/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs @@ -1,4 +1,6 @@ -using System; +#if FEATURE_DATA_GETSCHEMATABLE + +using System; using System.Data; using System.Data.Common; @@ -66,7 +68,7 @@ protected override void ParseTableInfo(DataRow rs) public class SQLiteColumnMetaData : AbstractColumnMetaData { - public SQLiteColumnMetaData(DataRow rs) : base(rs) + public SQLiteColumnMetaData(DataRow rs) : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -93,4 +95,6 @@ public SQLiteForeignKeyMetaData(DataRow rs) : base(rs) Name = Convert.ToString(rs["CONSTRAINT_NAME"]); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/Schema/SchemaHelper.cs b/src/NHibernate/Dialect/Schema/SchemaHelper.cs index ec6bfc062c4..a3af92bca7f 100644 --- a/src/NHibernate/Dialect/Schema/SchemaHelper.cs +++ b/src/NHibernate/Dialect/Schema/SchemaHelper.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Data; @@ -40,3 +42,5 @@ public static string GetString(DataRow row, params string[] alternativeColumnNam } } } + +#endif diff --git a/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs b/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs index 08e312f2572..671127857b9 100644 --- a/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs +++ b/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs @@ -1,4 +1,6 @@ -using System; +#if FEATURE_DATA_GETSCHEMATABLE + +using System; using System.Collections.Generic; using System.Data; using System.Data.Common; @@ -114,7 +116,7 @@ protected override void ParseTableInfo(DataRow rs) public class SybaseAnywhereColumnMetaData : AbstractColumnMetaData { - public SybaseAnywhereColumnMetaData(DataRow rs) : base(rs) + public SybaseAnywhereColumnMetaData(DataRow rs) : base() { Name = Convert.ToString(rs["COLUMN_NAME"]); @@ -143,4 +145,6 @@ public SybaseAnywhereForeignKeyMetaData(DataRow rs) : base(rs) Name = (string) rs["COLUMN_NAME"]; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Dialect/SybaseASA9Dialect.cs b/src/NHibernate/Dialect/SybaseASA9Dialect.cs index 94745a76329..6826ed33144 100644 --- a/src/NHibernate/Dialect/SybaseASA9Dialect.cs +++ b/src/NHibernate/Dialect/SybaseASA9Dialect.cs @@ -116,10 +116,12 @@ public override SqlString GetLimitString(SqlString queryString, SqlString offset return queryString.Insert(intSelectInsertPoint, limitFragment.ToSqlString()); } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new SybaseAnywhereDataBaseMetaData(connection); } +#endif public override string AddColumnString { @@ -185,4 +187,4 @@ private static int GetAfterSelectInsertPoint(SqlString sql) return 0; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs b/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs index 49bae34a48c..d37e5775604 100644 --- a/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs +++ b/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs @@ -808,9 +808,11 @@ public override bool SupportsUnionAll get { return true; } } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new SybaseAnywhereDataBaseMetaData(connection); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs b/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs index d7075f0411c..293c75d7d05 100644 --- a/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs +++ b/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs @@ -122,9 +122,11 @@ public override string GetDropSequenceString(string sequenceName) return "DROP SEQUENCE " + sequenceName; } +#if FEATURE_DATA_GETSCHEMATABLE public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) { return new SybaseAnywhereDataBaseMetaData(connection); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/BasicResultSetsCommand.cs b/src/NHibernate/Driver/BasicResultSetsCommand.cs index aff389091c3..b7e56eb537e 100644 --- a/src/NHibernate/Driver/BasicResultSetsCommand.cs +++ b/src/NHibernate/Driver/BasicResultSetsCommand.cs @@ -246,15 +246,19 @@ public override int GetHashCode() return reader.GetHashCode(); } +#if FEATURE_DATA_CLOSE || NET_4_0 public override void Close() { batcher.CloseCommand(command, reader); } +#endif +#if FEATURE_DATA_GETSCHEMATABLE || NET_4_0 public override DataTable GetSchemaTable() { return reader.GetSchemaTable(); } +#endif public override bool NextResult() { @@ -281,4 +285,4 @@ public override int RecordsAffected get { return reader.RecordsAffected; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/NDataReader.cs b/src/NHibernate/Driver/NDataReader.cs index d70e4c1a030..a33688d39ec 100644 --- a/src/NHibernate/Driver/NDataReader.cs +++ b/src/NHibernate/Driver/NDataReader.cs @@ -47,33 +47,32 @@ public NDataReader(DbDataReader reader, bool isMidstream) { var resultList = new List(2); - try + using (reader) { - // if we are in midstream of processing a DataReader then we are already - // positioned on the first row (index=0) - if (isMidstream) + try { - currentRowIndex = 0; - } + // if we are in midstream of processing a DataReader then we are already + // positioned on the first row (index=0) + if (isMidstream) + { + currentRowIndex = 0; + } - // there will be atleast one result - resultList.Add(new NResult(reader, isMidstream)); + // there will be atleast one result + resultList.Add(new NResult(reader, isMidstream)); - while (reader.NextResult()) + while (reader.NextResult()) + { + // the second, third, nth result is not processed midstream + resultList.Add(new NResult(reader, false)); + } + + results = resultList.ToArray(); + } + catch (Exception e) { - // the second, third, nth result is not processed midstream - resultList.Add(new NResult(reader, false)); + throw new ADOException("There was a problem converting an DbDataReader to NDataReader", e); } - - results = resultList.ToArray(); - } - catch (Exception e) - { - throw new ADOException("There was a problem converting an DbDataReader to NDataReader", e); - } - finally - { - reader.Close(); } } @@ -108,7 +107,7 @@ public override int RecordsAffected public override bool HasRows { - get { return results.LongLength > 0; } + get { return results.Length > 0; } } /// @@ -135,10 +134,12 @@ public override bool NextResult() } /// +#if FEATURE_DATA_CLOSE || NET_4_0 public override void Close() { isClosed = true; } +#endif /// public override bool Read() @@ -163,11 +164,17 @@ public override int Depth get { return currentResultIndex; } } +#if FEATURE_DATA_GETSCHEMATABLE || NET_4_0 /// public override DataTable GetSchemaTable() { +#if FEATURE_DATA_GETSCHEMATABLE return GetCurrentResult().GetSchemaTable(); +#else + throw new NotImplementedException(); +#endif } +#endif protected override void Dispose(bool disposing) { @@ -247,7 +254,7 @@ public override long GetBytes(int i, long fieldOffset, byte[] buffer, int buffer length = (int) remainingLength; } - Array.Copy(cachedByteArray, fieldOffset, buffer, bufferOffset, length); + Array.Copy(cachedByteArray, (int)fieldOffset, buffer, bufferOffset, length); return length; } @@ -422,7 +429,7 @@ public override long GetChars(int i, long fieldOffset, char[] buffer, int buffer length = (int) remainingLength; } - Array.Copy(cachedCharArray, fieldOffset, buffer, bufferOffset, length); + Array.Copy(cachedCharArray, (int)fieldOffset, buffer, bufferOffset, length); return length; } @@ -466,7 +473,9 @@ private class NResult private readonly object[][] records; private int colCount = 0; +#if FEATURE_DATA_GETSCHEMATABLE private readonly DataTable schemaTable; +#endif // key = field name // index = field index @@ -485,7 +494,9 @@ private class NResult /// internal NResult(DbDataReader reader, bool isMidstream) { +#if FEATURE_DATA_GETSCHEMATABLE schemaTable = reader.GetSchemaTable(); +#endif List recordsList = new List(); int rowIndex = 0; @@ -561,11 +572,13 @@ public string GetName(int colIndex) return fieldIndexToName[colIndex]; } +#if FEATURE_DATA_GETSCHEMATABLE /// public DataTable GetSchemaTable() { return schemaTable; } +#endif /// /// @@ -635,4 +648,4 @@ public int RowCount } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/NHybridDataReader.cs b/src/NHibernate/Driver/NHybridDataReader.cs index a168e46fd2a..5a3454d74a7 100644 --- a/src/NHibernate/Driver/NHybridDataReader.cs +++ b/src/NHibernate/Driver/NHybridDataReader.cs @@ -97,7 +97,7 @@ public override bool HasRows /// public override bool IsClosed { - get { return _reader.IsClosed; } + get { return _reader == null || _reader.IsClosed; } } /// @@ -108,11 +108,13 @@ public override bool NextResult() return _reader.NextResult(); } +#if FEATURE_DATA_CLOSE || NET_4_0 /// public override void Close() { _reader.Close(); } +#endif /// public override bool Read() @@ -127,11 +129,13 @@ public override int Depth get { return _reader.Depth; } } +#if FEATURE_DATA_GETSCHEMATABLE || NET_4_0 /// public override DataTable GetSchemaTable() { return _reader.GetSchemaTable(); } +#endif /// /// A flag to indicate if Disose() has been called. @@ -163,7 +167,6 @@ protected override void Dispose(bool disposing) if (disposing && _reader != null) { _reader.Dispose(); - _reader = null; } disposed = true; @@ -415,4 +418,4 @@ public override short GetInt16(int i) return _reader.GetInt16(i); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/OdbcDriver.cs b/src/NHibernate/Driver/OdbcDriver.cs index 6101d321a5e..3cb879dcfc3 100644 --- a/src/NHibernate/Driver/OdbcDriver.cs +++ b/src/NHibernate/Driver/OdbcDriver.cs @@ -1,3 +1,5 @@ +#if FEATURE_ODBC_OLEDB + using System; using System.Collections.Generic; using System.Data; @@ -84,3 +86,5 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq } } } + +#endif diff --git a/src/NHibernate/Driver/OleDbDriver.cs b/src/NHibernate/Driver/OleDbDriver.cs index cb0d00c63c8..97e9df1bd9b 100644 --- a/src/NHibernate/Driver/OleDbDriver.cs +++ b/src/NHibernate/Driver/OleDbDriver.cs @@ -1,3 +1,5 @@ +#if FEATURE_ODBC_OLEDB + using System; using System.Data.Common; using System.Data.OleDb; @@ -49,4 +51,6 @@ public override bool SupportsMultipleOpenReaders get { return false; } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Driver/ReflectionBasedDriver.cs b/src/NHibernate/Driver/ReflectionBasedDriver.cs index dfe487004ac..8d2739b3790 100644 --- a/src/NHibernate/Driver/ReflectionBasedDriver.cs +++ b/src/NHibernate/Driver/ReflectionBasedDriver.cs @@ -41,12 +41,16 @@ protected ReflectionBasedDriver(string providerInvariantName, string driverAssem if (connectionType == null || commandType == null) { +#if FEATURE_DBPROVIDERFACTORIES if (string.IsNullOrEmpty(providerInvariantName)) { throw new HibernateException(string.Format(ReflectionTypedProviderExceptionMessageTemplate, driverAssemblyName)); } var factory = DbProviderFactories.GetFactory(providerInvariantName); connectionCommandProvider = new DbProviderFactoryDriveConnectionCommandProvider(factory); +#else + throw new HibernateException(string.Format(ReflectionTypedProviderExceptionMessageTemplate, driverAssemblyName)); +#endif } else { @@ -64,4 +68,4 @@ public override DbCommand CreateCommand() return connectionCommandProvider.CreateCommand(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/SqlClientDriver.cs b/src/NHibernate/Driver/SqlClientDriver.cs index fadec4ea5ab..2a105580580 100644 --- a/src/NHibernate/Driver/SqlClientDriver.cs +++ b/src/NHibernate/Driver/SqlClientDriver.cs @@ -187,7 +187,11 @@ protected static bool IsBlob(DbParameter dbParam, SqlType sqlType) System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass { +#if FEATURE_ADONET_SQLCOMMANDSET get { return typeof(SqlClientBatchingBatcherFactory); } +#else + get { return typeof(NonBatchingBatcherFactory); } +#endif } #endregion diff --git a/src/NHibernate/DuplicateMappingException.cs b/src/NHibernate/DuplicateMappingException.cs index 415c3bfe2bf..c86d1ebbeaa 100644 --- a/src/NHibernate/DuplicateMappingException.cs +++ b/src/NHibernate/DuplicateMappingException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -48,6 +51,7 @@ public DuplicateMappingException(string type, string name) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -63,5 +67,6 @@ public DuplicateMappingException(SerializationInfo info, StreamingContext contex : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Engine/Cascade.cs b/src/NHibernate/Engine/Cascade.cs index d0c7ed99c59..ff1241c36e2 100644 --- a/src/NHibernate/Engine/Cascade.cs +++ b/src/NHibernate/Engine/Cascade.cs @@ -1,5 +1,5 @@ using System.Collections; - +using System.Collections.Generic; using NHibernate.Collection; using NHibernate.Event; using NHibernate.Persister.Collection; @@ -76,7 +76,7 @@ public sealed class Cascade private readonly IEventSource eventSource; private readonly CascadingAction action; - private readonly Stack componentPathStack = new Stack(); + private readonly Stack componentPathStack = new Stack(); public Cascade(CascadingAction action, CascadePoint point, IEventSource eventSource) { @@ -340,4 +340,4 @@ private void DeleteOrphans(string entityName, IPersistentCollection pc) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Engine/CascadeStyle.cs b/src/NHibernate/Engine/CascadeStyle.cs index 47c60033516..88de7245bb4 100644 --- a/src/NHibernate/Engine/CascadeStyle.cs +++ b/src/NHibernate/Engine/CascadeStyle.cs @@ -1,15 +1,21 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; using System.Security; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Engine { /// A contract for defining the aspects of cascading various persistence actions. /// [Serializable] - public abstract class CascadeStyle : ISerializable + public abstract class CascadeStyle +#if FEATURE_SERIALIZATION + : ISerializable +#endif { /// package-protected constructor internal CascadeStyle() {} @@ -93,6 +99,7 @@ public static CascadeStyle GetCascadeStyle(string cascade) return style; } +#if FEATURE_SERIALIZATION [SecurityCritical] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { @@ -100,7 +107,9 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.SetType(typeof(CascadeStyleSingletonReference)); info.AddValue("cascadestyle", alias, typeof(string)); } +#endif +#if FEATURE_SERIALIZATION [Serializable] private sealed class CascadeStyleSingletonReference : IObjectReference, ISerializable { @@ -124,6 +133,7 @@ Object IObjectReference.GetRealObject(StreamingContext context) return GetCascadeStyle(_cascadeStyle); } } +#endif #endregion @@ -253,7 +263,11 @@ public override bool DoCascade(CascadingAction action) } [Serializable] - public sealed class MultipleCascadeStyle : CascadeStyle, ISerializable + public sealed class MultipleCascadeStyle + : CascadeStyle +#if FEATURE_SERIALIZATION + , ISerializable +#endif { private readonly CascadeStyle[] styles; public MultipleCascadeStyle(CascadeStyle[] styles) @@ -261,6 +275,7 @@ public MultipleCascadeStyle(CascadeStyle[] styles) this.styles = styles; } +#if FEATURE_SERIALIZATION private MultipleCascadeStyle(SerializationInfo info, StreamingContext context) { styles = (CascadeStyle[])info.GetValue("styles", typeof(CascadeStyle[])); @@ -271,6 +286,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex { info.AddValue("styles", styles); } +#endif public override bool DoCascade(CascadingAction action) { diff --git a/src/NHibernate/Engine/ForeignKeys.cs b/src/NHibernate/Engine/ForeignKeys.cs index aa1e870c91a..840877bba07 100644 --- a/src/NHibernate/Engine/ForeignKeys.cs +++ b/src/NHibernate/Engine/ForeignKeys.cs @@ -1,4 +1,5 @@ +using System.Reflection; using NHibernate.Id; using NHibernate.Persister.Entity; using NHibernate.Proxy; @@ -243,7 +244,7 @@ public static object GetEntityIdentifierIfNotUnsaved(string entityName, object e /***********************************************/ // NH-479 (very dirty patch) - if (entity.GetType().IsPrimitive) + if (entity.GetType().GetTypeInfo().IsPrimitive) return entity; /**********************************************/ diff --git a/src/NHibernate/Engine/StatefulPersistenceContext.cs b/src/NHibernate/Engine/StatefulPersistenceContext.cs index e303f1d9676..526f7499282 100644 --- a/src/NHibernate/Engine/StatefulPersistenceContext.cs +++ b/src/NHibernate/Engine/StatefulPersistenceContext.cs @@ -1,9 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; +using System.Reflection; using System.Text; using NHibernate.Collection; using NHibernate.Engine.Loading; @@ -13,6 +11,11 @@ using NHibernate.Proxy; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Security; +#endif + namespace NHibernate.Engine { /// @@ -27,7 +30,11 @@ namespace NHibernate.Engine /// PersistentContext to drive their processing. /// [Serializable] - public class StatefulPersistenceContext : IPersistenceContext, ISerializable, IDeserializationCallback + public class StatefulPersistenceContext + : IPersistenceContext +#if FEATURE_SERIALIZATION + , ISerializable, IDeserializationCallback +#endif { private const int InitCollectionSize = 8; private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(StatefulPersistenceContext)); @@ -1387,6 +1394,7 @@ public override string ToString() .ToString(); } +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members internal void SetSession(ISessionImplementor session) { @@ -1514,5 +1522,6 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.AddValue("context.defaultReadOnly", defaultReadOnly); } #endregion +#endif } } diff --git a/src/NHibernate/Engine/UnsavedValueFactory.cs b/src/NHibernate/Engine/UnsavedValueFactory.cs index 1f9b3cfed4c..a908a05b88e 100644 --- a/src/NHibernate/Engine/UnsavedValueFactory.cs +++ b/src/NHibernate/Engine/UnsavedValueFactory.cs @@ -90,7 +90,7 @@ public static VersionValue GetUnsavedVersionValue( if (constructor != null) { object defaultValue = versionGetter.Get(Instantiate(constructor)); - if (defaultValue != null && defaultValue.GetType().IsValueType) + if (defaultValue != null && defaultValue.GetType().GetTypeInfo().IsValueType) return new VersionValue(defaultValue); else { @@ -137,4 +137,4 @@ public static VersionValue GetUnsavedVersionValue( } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Event/Default/DefaultLoadEventListener.cs b/src/NHibernate/Event/Default/DefaultLoadEventListener.cs index 349644dfe67..b0cf6450f76 100644 --- a/src/NHibernate/Event/Default/DefaultLoadEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultLoadEventListener.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Reflection; using System.Text; using NHibernate.Cache; using NHibernate.Cache.Access; @@ -9,6 +10,7 @@ using NHibernate.Persister.Entity; using NHibernate.Proxy; using NHibernate.Type; +using NHibernate.Util; namespace NHibernate.Event.Default { @@ -546,7 +548,7 @@ protected virtual IEntityPersister GetEntityPersister(ISessionFactoryImplementor var messageBuilder = new StringBuilder(512); messageBuilder.AppendLine(string.Format("Ambiguous persister for {0} implemented by more than one hierarchy: ", entityName)); - Array.ForEach(implementors, s=> messageBuilder.AppendLine(s)); + implementors.ForEach(s => messageBuilder.AppendLine(s)); throw new HibernateException(messageBuilder.ToString()); } diff --git a/src/NHibernate/Exceptions/ADOConnectionException.cs b/src/NHibernate/Exceptions/ADOConnectionException.cs index 94611a6d5d9..bd6da3c9141 100644 --- a/src/NHibernate/Exceptions/ADOConnectionException.cs +++ b/src/NHibernate/Exceptions/ADOConnectionException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Exceptions { @@ -10,7 +13,9 @@ namespace NHibernate.Exceptions [Serializable] public class ADOConnectionException : ADOException { +#if FEATURE_SERIALIZATION public ADOConnectionException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public ADOConnectionException(string message, Exception innerException, string sql) : base(message, innerException, sql) {} public ADOConnectionException(string message, Exception innerException) : base(message, innerException) {} } diff --git a/src/NHibernate/Exceptions/ConstraintViolationException.cs b/src/NHibernate/Exceptions/ConstraintViolationException.cs index cee757168b3..9237783049f 100644 --- a/src/NHibernate/Exceptions/ConstraintViolationException.cs +++ b/src/NHibernate/Exceptions/ConstraintViolationException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Exceptions { @@ -11,8 +14,11 @@ namespace NHibernate.Exceptions public class ConstraintViolationException : ADOException { private readonly string constraintName; + +#if FEATURE_SERIALIZATION public ConstraintViolationException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public ConstraintViolationException(string message, Exception innerException, string sql, string constraintName) : base(message, innerException, sql) diff --git a/src/NHibernate/Exceptions/DataException.cs b/src/NHibernate/Exceptions/DataException.cs index 99357d5e194..e4cae3a6bb1 100644 --- a/src/NHibernate/Exceptions/DataException.cs +++ b/src/NHibernate/Exceptions/DataException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Exceptions { @@ -11,7 +14,9 @@ namespace NHibernate.Exceptions [Serializable] public class DataException : ADOException { +#if FEATURE_SERIALIZATION public DataException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public DataException(string message, Exception innerException, string sql) : base(message, innerException, sql) {} public DataException(string message, Exception innerException) : base(message, innerException) {} } diff --git a/src/NHibernate/Exceptions/GenericADOException.cs b/src/NHibernate/Exceptions/GenericADOException.cs index d45e298c3f3..6c89fed1db0 100644 --- a/src/NHibernate/Exceptions/GenericADOException.cs +++ b/src/NHibernate/Exceptions/GenericADOException.cs @@ -1,6 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; -using NHibernate.SqlCommand; +#endif namespace NHibernate.Exceptions { @@ -11,8 +13,10 @@ public GenericADOException() { } +#if FEATURE_SERIALIZATION public GenericADOException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif public GenericADOException(string message, Exception innerException, string sql) : base(message, innerException, sql) { } public GenericADOException(string message, Exception innerException) : base(message, innerException) { } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Exceptions/LockAcquisitionException.cs b/src/NHibernate/Exceptions/LockAcquisitionException.cs index 58a774b13f6..fbf69259a08 100644 --- a/src/NHibernate/Exceptions/LockAcquisitionException.cs +++ b/src/NHibernate/Exceptions/LockAcquisitionException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Exceptions { @@ -10,7 +13,9 @@ namespace NHibernate.Exceptions [Serializable] public class LockAcquisitionException : ADOException { +#if FEATURE_SERIALIZATION public LockAcquisitionException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public LockAcquisitionException(string message, Exception innerException, string sql) : base(message, innerException, sql) {} public LockAcquisitionException(string message, Exception innerException) : base(message, innerException) {} } diff --git a/src/NHibernate/Exceptions/SQLGrammarException.cs b/src/NHibernate/Exceptions/SQLGrammarException.cs index 29f655daac8..8df7d173190 100644 --- a/src/NHibernate/Exceptions/SQLGrammarException.cs +++ b/src/NHibernate/Exceptions/SQLGrammarException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Exceptions { @@ -10,7 +13,9 @@ namespace NHibernate.Exceptions [Serializable] public class SQLGrammarException : ADOException { +#if FEATURE_SERIALIZATION public SQLGrammarException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public SQLGrammarException(string message, Exception innerException, string sql) : base(message, innerException, sql) {} public SQLGrammarException(string message, Exception innerException) : base(message, innerException) {} } diff --git a/src/NHibernate/FKUnmatchingColumnsException.cs b/src/NHibernate/FKUnmatchingColumnsException.cs index 27d4f5e31ee..71d870fccc6 100644 --- a/src/NHibernate/FKUnmatchingColumnsException.cs +++ b/src/NHibernate/FKUnmatchingColumnsException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -33,6 +36,7 @@ public FKUnmatchingColumnsException(string message, Exception innerException) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -48,6 +52,7 @@ protected FKUnmatchingColumnsException(SerializationInfo info, StreamingContext : base(info, context) { } +#endif } } diff --git a/src/NHibernate/HibernateException.cs b/src/NHibernate/HibernateException.cs index cf9c71b5f25..3571526304d 100644 --- a/src/NHibernate/HibernateException.cs +++ b/src/NHibernate/HibernateException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -10,7 +13,7 @@ namespace NHibernate /// Exceptions that occur in the database layer are left as native exceptions. /// [Serializable] - public class HibernateException : ApplicationException + public class HibernateException : Exception { /// /// Initializes a new instance of the class. @@ -52,6 +55,7 @@ public HibernateException(string message, Exception innerException) : base(messa { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -66,5 +70,6 @@ public HibernateException(string message, Exception innerException) : base(messa protected HibernateException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs index 568c6b3dae9..b40ff7ddf18 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using Antlr.Runtime; using Antlr.Runtime.Tree; diff --git a/src/NHibernate/Hql/Ast/ANTLR/InvalidWithClauseException.cs b/src/NHibernate/Hql/Ast/ANTLR/InvalidWithClauseException.cs index 119e5c8163a..dd626081fab 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/InvalidWithClauseException.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/InvalidWithClauseException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Hql.Ast.ANTLR { @@ -11,6 +14,8 @@ protected InvalidWithClauseException() {} public InvalidWithClauseException(string message) : base(message) {} public InvalidWithClauseException(string message, Exception inner) : base(message, inner) {} +#if FEATURE_SERIALIZATION protected InvalidWithClauseException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/QuerySyntaxException.cs b/src/NHibernate/Hql/Ast/ANTLR/QuerySyntaxException.cs index c81e9dc34c8..851ea6addb2 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/QuerySyntaxException.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/QuerySyntaxException.cs @@ -1,7 +1,10 @@ using System; -using System.Runtime.Serialization; using Antlr.Runtime; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Hql.Ast.ANTLR { [CLSCompliant(false)] @@ -14,7 +17,9 @@ public QuerySyntaxException(string message, string hql) : base(message, hql) {} public QuerySyntaxException(string message) : base(message) {} public QuerySyntaxException(string message, Exception inner) : base(message, inner) {} +#if FEATURE_SERIALIZATION protected QuerySyntaxException(SerializationInfo info, StreamingContext context) : base(info, context) {} +#endif public static QuerySyntaxException Convert(RecognitionException e) { @@ -29,4 +34,4 @@ public static QuerySyntaxException Convert(RecognitionException e, string hql) return new QuerySyntaxException(e.Message + positionInfo, hql); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryArithmeticOperatorNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryArithmeticOperatorNode.cs index 14f68649f29..1cc4b7cf058 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryArithmeticOperatorNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryArithmeticOperatorNode.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using Antlr.Runtime; using NHibernate.Hql.Ast.ANTLR.Util; using NHibernate.Type; diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryLogicOperatorNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryLogicOperatorNode.cs index 827f9b1886a..23229e848d4 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryLogicOperatorNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/BinaryLogicOperatorNode.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Antlr.Runtime; using NHibernate.Engine; using NHibernate.Param; diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs index 453cc47fc11..3030bbd4372 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs @@ -325,7 +325,7 @@ private FromElement FindIntendedAliasedFromElementBasedOnCrazyJPARequirements(st foreach (var entry in _fromElementByClassAlias) { string alias = entry.Key; - if (string.Equals(alias, specifiedAlias, StringComparison.InvariantCultureIgnoreCase)) + if (string.Equals(alias, specifiedAlias, StringComparison.OrdinalIgnoreCase)) { return entry.Value; } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/IntoClause.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/IntoClause.cs index a59e6d5a8ec..c9c6b2ece5b 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/IntoClause.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/IntoClause.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using System.Text; using Antlr.Runtime; using NHibernate.Persister.Entity; @@ -263,4 +264,4 @@ private static bool AreSqlTypesCompatible(SqlType target, SqlType source) return target.Equals(source); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/CounterGenerator.cs b/src/NHibernate/Id/CounterGenerator.cs index c54ffede6e7..bc158e8e649 100644 --- a/src/NHibernate/Id/CounterGenerator.cs +++ b/src/NHibernate/Id/CounterGenerator.cs @@ -15,14 +15,16 @@ public class CounterGenerator : IIdentifierGenerator protected short Count { - [MethodImpl(MethodImplOptions.Synchronized)] get { - if (counter < 0) + lock (this) { - counter = 0; + if (counter < 0) + { + counter = 0; + } + return counter++; } - return counter++; } } @@ -31,4 +33,4 @@ public object Generate(ISessionImplementor cache, object obj) return unchecked ((DateTime.Now.Ticks << 16) + Count); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/OptimizerFactory.cs b/src/NHibernate/Id/Enhanced/OptimizerFactory.cs index 4b9c784e011..f4666ad5d97 100644 --- a/src/NHibernate/Id/Enhanced/OptimizerFactory.cs +++ b/src/NHibernate/Id/Enhanced/OptimizerFactory.cs @@ -140,29 +140,31 @@ public override bool ApplyIncrementSizeToSourceValues get { return false; } } - [MethodImpl(MethodImplOptions.Synchronized)] public override object Generate(IAccessCallback callback) { - if (_lastSourceValue < 0) + lock (this) { - _lastSourceValue = callback.GetNextValue(); - while (_lastSourceValue <= 0) + if (_lastSourceValue < 0) { _lastSourceValue = callback.GetNextValue(); - } + while (_lastSourceValue <= 0) + { + _lastSourceValue = callback.GetNextValue(); + } - // upperLimit defines the upper end of the bucket values - _upperLimit = (_lastSourceValue * IncrementSize) + 1; + // upperLimit defines the upper end of the bucket values + _upperLimit = (_lastSourceValue * IncrementSize) + 1; - // initialize value to the low end of the bucket - _value = _upperLimit - IncrementSize; - } - else if (_upperLimit <= _value) - { - _lastSourceValue = callback.GetNextValue(); - _upperLimit = (_lastSourceValue * IncrementSize) + 1; + // initialize value to the low end of the bucket + _value = _upperLimit - IncrementSize; + } + else if (_upperLimit <= _value) + { + _lastSourceValue = callback.GetNextValue(); + _upperLimit = (_lastSourceValue * IncrementSize) + 1; + } + return Make(_value++); } - return Make(_value++); } } @@ -303,35 +305,37 @@ public void InjectInitialValue(long initialValue) _initialValue = initialValue; } - [MethodImpl(MethodImplOptions.Synchronized)] public override object Generate(IAccessCallback callback) { - if (_hiValue < 0) + lock (this) { - _value = callback.GetNextValue(); - if (_value < 1) + if (_hiValue < 0) { - // unfortunately not really safe to normalize this - // to 1 as an initial value like we do the others - // because we would not be able to control this if - // we are using a sequence... - Log.Info("pooled optimizer source reported [" + _value + "] as the initial value; use of 1 or greater highly recommended"); + _value = callback.GetNextValue(); + if (_value < 1) + { + // unfortunately not really safe to normalize this + // to 1 as an initial value like we do the others + // because we would not be able to control this if + // we are using a sequence... + Log.Info("pooled optimizer source reported [" + _value + "] as the initial value; use of 1 or greater highly recommended"); + } + + if ((_initialValue == -1 && _value < IncrementSize) || _value == _initialValue) + _hiValue = callback.GetNextValue(); + else + { + _hiValue = _value; + _value = _hiValue - IncrementSize; + } } - - if ((_initialValue == -1 && _value < IncrementSize) || _value == _initialValue) - _hiValue = callback.GetNextValue(); - else + else if (_value >= _hiValue) { - _hiValue = _value; + _hiValue = callback.GetNextValue(); _value = _hiValue - IncrementSize; } + return Make(_value++); } - else if (_value >= _hiValue) - { - _hiValue = callback.GetNextValue(); - _value = _hiValue - IncrementSize; - } - return Make(_value++); } } @@ -356,18 +360,20 @@ public PooledLoOptimizer(System.Type returnClass, int incrementSize) : base(retu } } - [MethodImpl(MethodImplOptions.Synchronized)] public override object Generate(IAccessCallback callback) { - if (_lastSourceValue < 0 || _value >= (_lastSourceValue + IncrementSize)) + lock (this) { - _lastSourceValue = callback.GetNextValue(); - _value = _lastSourceValue; - // handle cases where initial-value is less than one (hsqldb for instance). - while (_value < 1) - _value++; + if (_lastSourceValue < 0 || _value >= (_lastSourceValue + IncrementSize)) + { + _lastSourceValue = callback.GetNextValue(); + _value = _lastSourceValue; + // handle cases where initial-value is less than one (hsqldb for instance). + while (_value < 1) + _value++; + } + return Make(_value++); } - return Make(_value++); } public override long LastSourceValue @@ -391,4 +397,4 @@ public long LastValue #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/SequenceStructure.cs b/src/NHibernate/Id/Enhanced/SequenceStructure.cs index e9de07d56ba..bcdc7b471bd 100644 --- a/src/NHibernate/Id/Enhanced/SequenceStructure.cs +++ b/src/NHibernate/Id/Enhanced/SequenceStructure.cs @@ -102,8 +102,7 @@ public virtual long GetNextValue() DbDataReader rs = null; try { - rs = _session.Batcher.ExecuteReader(st); - try + using (rs = _session.Batcher.ExecuteReader(st)) { rs.Read(); long result = Convert.ToInt64(rs.GetValue(0)); @@ -113,17 +112,6 @@ public virtual long GetNextValue() } return result; } - finally - { - try - { - rs.Close(); - } - catch - { - // intentionally empty - } - } } finally { @@ -141,4 +129,4 @@ public virtual long GetNextValue() #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/TableGenerator.cs b/src/NHibernate/Id/Enhanced/TableGenerator.cs index f39293bfa96..56cbe2fbe5d 100644 --- a/src/NHibernate/Id/Enhanced/TableGenerator.cs +++ b/src/NHibernate/Id/Enhanced/TableGenerator.cs @@ -403,10 +403,12 @@ protected void BuildInsertQuery() } - [MethodImpl(MethodImplOptions.Synchronized)] public virtual object Generate(ISessionImplementor session, object obj) { - return Optimizer.Generate(new TableAccessCallback(session, this)); + lock (this) + { + return Optimizer.Generate(new TableAccessCallback(session, this)); + } } diff --git a/src/NHibernate/Id/IdentifierGenerationException.cs b/src/NHibernate/Id/IdentifierGenerationException.cs index 1d76d44aec3..521296fb057 100644 --- a/src/NHibernate/Id/IdentifierGenerationException.cs +++ b/src/NHibernate/Id/IdentifierGenerationException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Id { @@ -37,6 +40,7 @@ public IdentifierGenerationException(string message, Exception e) : base(message { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -51,5 +55,6 @@ public IdentifierGenerationException(string message, Exception e) : base(message protected IdentifierGenerationException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/IncrementGenerator.cs b/src/NHibernate/Id/IncrementGenerator.cs index d9ef06da4d0..05a8b27c2e3 100644 --- a/src/NHibernate/Id/IncrementGenerator.cs +++ b/src/NHibernate/Id/IncrementGenerator.cs @@ -85,14 +85,16 @@ public void Configure(IType type, IDictionary parms, Dialect.Dia /// /// /// - [MethodImpl(MethodImplOptions.Synchronized)] public object Generate(ISessionImplementor session, object obj) { - if (_sql != null) + lock (this) { - GetNext(session); + if (_sql != null) + { + GetNext(session); + } + return IdentifierGeneratorFactory.CreateNumber(_next++, _returnClass); } - return IdentifierGeneratorFactory.CreateNumber(_next++, _returnClass); } private void GetNext(ISessionImplementor session) @@ -105,8 +107,7 @@ private void GetNext(ISessionImplementor session) DbDataReader reader = null; try { - reader = session.Batcher.ExecuteReader(cmd); - try + using (reader = session.Batcher.ExecuteReader(cmd)) { if (reader.Read()) { @@ -119,10 +120,6 @@ private void GetNext(ISessionImplementor session) _sql = null; Logger.Debug("first free id: " + _next); } - finally - { - reader.Close(); - } } finally { diff --git a/src/NHibernate/Id/NativeGuidGenerator.cs b/src/NHibernate/Id/NativeGuidGenerator.cs index 0164f23e870..1d0a38f46e7 100644 --- a/src/NHibernate/Id/NativeGuidGenerator.cs +++ b/src/NHibernate/Id/NativeGuidGenerator.cs @@ -29,17 +29,12 @@ public object Generate(ISessionImplementor session, object obj) DbDataReader reader = null; try { - reader = session.Batcher.ExecuteReader(st); object result; - try + using (reader = session.Batcher.ExecuteReader(st)) { reader.Read(); result = IdentifierGeneratorFactory.Get(reader, identifierType, session); } - finally - { - reader.Close(); - } log.Debug("GUID identifier generated: " + result); return result; } @@ -56,4 +51,4 @@ public object Generate(ISessionImplementor session, object obj) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/SequenceGenerator.cs b/src/NHibernate/Id/SequenceGenerator.cs index 721ce0d6395..a6f07e27be0 100644 --- a/src/NHibernate/Id/SequenceGenerator.cs +++ b/src/NHibernate/Id/SequenceGenerator.cs @@ -117,8 +117,7 @@ public virtual object Generate(ISessionImplementor session, object obj) DbDataReader reader = null; try { - reader = session.Batcher.ExecuteReader(cmd); - try + using (reader = session.Batcher.ExecuteReader(cmd)) { reader.Read(); object result = IdentifierGeneratorFactory.Get(reader, identifierType, session); @@ -128,10 +127,6 @@ public virtual object Generate(ISessionImplementor session, object obj) } return result; } - finally - { - reader.Close(); - } } finally { diff --git a/src/NHibernate/Id/SequenceHiLoGenerator.cs b/src/NHibernate/Id/SequenceHiLoGenerator.cs index 018bd52a568..faeb54b0166 100644 --- a/src/NHibernate/Id/SequenceHiLoGenerator.cs +++ b/src/NHibernate/Id/SequenceHiLoGenerator.cs @@ -75,29 +75,31 @@ public override void Configure(IType type, IDictionary parms, Di /// The this id is being generated in. /// The entity for which the id is being generated. /// The new identifier as a , , or . - [MethodImpl(MethodImplOptions.Synchronized)] public override object Generate(ISessionImplementor session, object obj) { - if (maxLo < 1) + lock (this) { - //keep the behavior consistent even for boundary usages - long val = Convert.ToInt64(base.Generate(session, obj)); - if (val == 0) - val = Convert.ToInt64(base.Generate(session, obj)); - return IdentifierGeneratorFactory.CreateNumber(val, returnClass); - } + if (maxLo < 1) + { + //keep the behavior consistent even for boundary usages + long val = Convert.ToInt64(base.Generate(session, obj)); + if (val == 0) + val = Convert.ToInt64(base.Generate(session, obj)); + return IdentifierGeneratorFactory.CreateNumber(val, returnClass); + } - if (lo > maxLo) - { - long hival = Convert.ToInt64(base.Generate(session, obj)); - lo = 1; - hi = hival * (maxLo + 1); - if (log.IsDebugEnabled) - log.Debug("new hi value: " + hival); + if (lo > maxLo) + { + long hival = Convert.ToInt64(base.Generate(session, obj)); + lo = 1; + hi = hival * (maxLo + 1); + if (log.IsDebugEnabled) + log.Debug("new hi value: " + hival); + } + return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); } - return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/TableGenerator.cs b/src/NHibernate/Id/TableGenerator.cs index 11396482008..441b39e2463 100644 --- a/src/NHibernate/Id/TableGenerator.cs +++ b/src/NHibernate/Id/TableGenerator.cs @@ -151,13 +151,15 @@ public virtual void Configure(IType type, IDictionary parms, Dia /// The this id is being generated in. /// The entity for which the id is being generated. /// The new identifier as a , , or . - [MethodImpl(MethodImplOptions.Synchronized)] public virtual object Generate(ISessionImplementor session, object obj) { - // This has to be done using a different connection to the containing - // transaction becase the new hi value must remain valid even if the - // containing transaction rolls back. - return DoWorkInNewTransaction(session); + lock (this) + { + // This has to be done using a different connection to the containing + // transaction becase the new hi value must remain valid even if the + // containing transaction rolls back. + return DoWorkInNewTransaction(session); + } } #endregion @@ -221,43 +223,43 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D //select + uspdate even for no transaction //or read committed isolation level (needed for .net?) - var qps = conn.CreateCommand(); - DbDataReader rs = null; - qps.CommandText = query; - qps.CommandType = CommandType.Text; - qps.Transaction = transaction; - PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand("Reading high value:", qps, FormatStyle.Basic); - try + using (DbCommand qps = conn.CreateCommand()) { - rs = qps.ExecuteReader(); - if (!rs.Read()) + qps.CommandText = query; + qps.CommandType = CommandType.Text; + qps.Transaction = transaction; + PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand("Reading high value:", qps, FormatStyle.Basic); + using (DbDataReader rs = qps.ExecuteReader()) { - string err; - if (string.IsNullOrEmpty(whereClause)) + try { - err = "could not read a hi value - you need to populate the table: " + tableName; + ; + if (!rs.Read()) + { + string err; + if (string.IsNullOrEmpty(whereClause)) + { + err = "could not read a hi value - you need to populate the table: " + tableName; + } + else + { + err = + string.Format( + "could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table.", + tableName, + whereClause); + } + log.Error(err); + throw new IdentifierGenerationException(err); + } + result = Convert.ToInt64(columnType.Get(rs, 0)); } - else + catch (Exception e) { - err = string.Format("could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table.", tableName, whereClause); + log.Error("could not read a hi value", e); + throw; } - log.Error(err); - throw new IdentifierGenerationException(err); - } - result = Convert.ToInt64(columnType.Get(rs, 0)); - } - catch (Exception e) - { - log.Error("could not read a hi value", e); - throw; - } - finally - { - if (rs != null) - { - rs.Close(); } - qps.Dispose(); } var ups = session.Factory.ConnectionProvider.Driver.GenerateCommand(CommandType.Text, updateSql, parameterTypes); @@ -288,4 +290,4 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/TableHiLoGenerator.cs b/src/NHibernate/Id/TableHiLoGenerator.cs index 70d780c8c8c..7fd7cd02d33 100644 --- a/src/NHibernate/Id/TableHiLoGenerator.cs +++ b/src/NHibernate/Id/TableHiLoGenerator.cs @@ -78,28 +78,30 @@ public override void Configure(IType type, IDictionary parms, Di /// The this id is being generated in. /// The entity for which the id is being generated. /// The new identifier as a . - [MethodImpl(MethodImplOptions.Synchronized)] public override object Generate(ISessionImplementor session, object obj) { - if (maxLo < 1) + lock (this) { - //keep the behavior consistent even for boundary usages - long val = Convert.ToInt64(base.Generate(session, obj)); - if (val == 0) - val = Convert.ToInt64(base.Generate(session, obj)); - return IdentifierGeneratorFactory.CreateNumber(val, returnClass); - } - if (lo > maxLo) - { - long hival = Convert.ToInt64(base.Generate(session, obj)); - lo = (hival == 0) ? 1 : 0; - hi = hival * (maxLo + 1); - log.Debug("New high value: " + hival); - } + if (maxLo < 1) + { + //keep the behavior consistent even for boundary usages + long val = Convert.ToInt64(base.Generate(session, obj)); + if (val == 0) + val = Convert.ToInt64(base.Generate(session, obj)); + return IdentifierGeneratorFactory.CreateNumber(val, returnClass); + } + if (lo > maxLo) + { + long hival = Convert.ToInt64(base.Generate(session, obj)); + lo = (hival == 0) ? 1 : 0; + hi = hival * (maxLo + 1); + log.Debug("New high value: " + hival); + } - return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); + return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); + } } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Iesi.Collections.Generic/LinkedHashSet.cs b/src/NHibernate/Iesi.Collections.Generic/LinkedHashSet.cs new file mode 100644 index 00000000000..1bb40fbdc67 --- /dev/null +++ b/src/NHibernate/Iesi.Collections.Generic/LinkedHashSet.cs @@ -0,0 +1,416 @@ +/* Copyright © 2012 Oskar Berggren */ + +#if FEATURE_INTERNALIZE_IESI + +using System; +using System.Linq; +using System.Collections; +using System.Collections.Generic; + + +namespace Iesi.Collections.Generic +{ + /// + /// Implementation of ISet that also maintains a linked list over all elements. + /// Enumeration of this set is guaranteed to return the elements in the order + /// they were added. + /// + [Serializable] + public class LinkedHashSet : ISet + { + private readonly Dictionary> _elements; + private LinkedHashNode _first, _last; + + public LinkedHashSet() + { + _elements = new Dictionary>(); + } + + + public LinkedHashSet(IEnumerable initialValues) + : this() + { + UnionWith(initialValues); + } + + + + #region Implementation of IEnumerable + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + /// 1 + IEnumerator IEnumerable.GetEnumerator() + { + var current = _first; + while (current != null) + { + yield return current.Value; + current = current.Next; + } + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + /// 2 + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + + #endregion + + + + #region Implementation of ICollection + + /// + /// Adds an item to the . + /// + /// The object to add to the .The is read-only. + void ICollection.Add(T item) + { + Add(item); + } + + + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + public int Count + { + get { return _elements.Count; } + } + + /// + /// Gets a value indicating whether the is read-only. + /// + /// + /// true if the is read-only; otherwise, false. + /// + bool ICollection.IsReadOnly + { + get { return false; } + } + + /// + /// Removes all items from the . + /// + /// The is read-only. + public void Clear() + { + _elements.Clear(); + _first = null; + _last = null; + } + + + /// + /// Determines whether the contains a specific value. + /// + /// + /// true if is found in the ; otherwise, false. + /// + /// The object to locate in the . + public bool Contains(T item) + { + return _elements.ContainsKey(item); + } + + /// + /// Copies the elements of the to an , starting at a particular index. + /// + /// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing.The zero-based index in at which copying begins. is null. is less than 0. is multidimensional.-or-The number of elements in the source is greater than the available space from to the end of the destination .-or-Type cannot be cast automatically to the type of the destination . + public void CopyTo(T[] array, int arrayIndex) + { + int index = arrayIndex; + + foreach (var item in this) + array[index++] = item; + } + + /// + /// Removes the first occurrence of a specific object from the . + /// + /// + /// true if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . + /// + /// The object to remove from the .The is read-only. + public bool Remove(T item) + { + LinkedHashNode node; + if (_elements.TryGetValue(item, out node)) + { + _elements.Remove(item); + Unlink(node); + return true; + } + + return false; + } + + #endregion + + + #region Implementation of ISet + + /// + /// Modifies the current set so that it contains all elements that are present in either the current set or the specified collection. + /// + /// The collection to compare to the current set. is null. + public void UnionWith(IEnumerable other) + { + foreach (var item in other) + Add(item); + } + + /// + /// Modifies the current set so that it contains only elements that are also in a specified collection. + /// + /// The collection to compare to the current set. is null. + public void IntersectWith(IEnumerable other) + { + var otherSet = AsSet(other); + + var current = _first; + while (current != null) + { + if (!otherSet.Contains(current.Value)) + { + _elements.Remove(current.Value); + Unlink(current); + } + current = current.Next; + } + } + + /// + /// Removes all elements in the specified collection from the current set. + /// + /// The collection of items to remove from the set. is null. + public void ExceptWith(IEnumerable other) + { + foreach (var item in other) + Remove(item); + } + + /// + /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. + /// + /// The collection to compare to the current set. is null. + public void SymmetricExceptWith(IEnumerable other) + { + foreach (var item in other) + { + LinkedHashNode node; + if (_elements.TryGetValue(item, out node)) + { + _elements.Remove(item); + Unlink(node); + } + else + Add(item); + } + } + + /// + /// Determines whether a set is a subset of a specified collection. + /// + /// + /// true if the current set is a subset of ; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool IsSubsetOf(IEnumerable other) + { + var otherSet = AsSet(other); + + if (Count > otherSet.Count) + return false; + + return _elements.Keys.All(otherSet.Contains); + } + + + /// + /// Determines whether the current set is a superset of a specified collection. + /// + /// + /// true if the current set is a superset of ; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool IsSupersetOf(IEnumerable other) + { + int numberOfOthersPresent; + var numberOfOthers = CountOthers(other, out numberOfOthersPresent); + + // All others must be present. + return numberOfOthersPresent == numberOfOthers; + } + + /// + /// Determines whether the current set is a correct superset of a specified collection. + /// + /// + /// true if the object is a correct superset of ; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool IsProperSupersetOf(IEnumerable other) + { + int numberOfOthersPresent; + var numberOfOthers = CountOthers(other, out numberOfOthersPresent); + + // All others must be present, plus we need to have at least one additional item. + return numberOfOthersPresent == numberOfOthers && numberOfOthers < Count; + } + + /// + /// Determines whether the current set is a proper (strict) subset of a specified collection. + /// + /// + /// true if the current set is a correct subset of ; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool IsProperSubsetOf(IEnumerable other) + { + var otherSet = AsSet(other); + + if (Count >= otherSet.Count) + return false; + + return _elements.Keys.All(otherSet.Contains); + } + + /// + /// Determines whether the current set overlaps with the specified collection. + /// + /// + /// true if the current set and share at least one common element; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool Overlaps(IEnumerable other) + { + return other.Any(Contains); + } + + /// + /// Determines whether the current set and the specified collection contain the same elements. + /// + /// + /// true if the current set is equal to ; otherwise, false. + /// + /// The collection to compare to the current set. is null. + public bool SetEquals(IEnumerable other) + { + int numberOfOthersPresent; + var numberOfOthers = CountOthers(other, out numberOfOthersPresent); + + return numberOfOthers == Count && numberOfOthersPresent == Count; + } + + + /// + /// Adds an element to the current set and returns a value to indicate if the element was successfully added. + /// + /// + /// true if the element is added to the set; false if the element is already in the set. + /// + /// The element to add to the set. + public bool Add(T item) + { + if (_elements.ContainsKey(item)) + return false; + + var node = new LinkedHashNode(item) { Previous = _last }; + + if (_first == null) + _first = node; + + if (_last != null) + _last.Next = node; + + _last = node; + + _elements.Add(item, node); + + return true; + } + + #endregion + + + /// + /// Count the elements in the given collection and determine both the total + /// count and how many of the elements that are present in the current set. + /// + private int CountOthers(IEnumerable items, out int numberOfOthersPresent) + { + numberOfOthersPresent = 0; + int numberOfOthers = 0; + + foreach (var item in items) + { + numberOfOthers++; + if (Contains(item)) + numberOfOthersPresent++; + } + return numberOfOthers; + } + + + /// + /// Cast the given collection to an ISet<T> if possible. If not, + /// return a new set containing the items. + /// + private static ISet AsSet(IEnumerable items) + { + return items as ISet ?? new HashSet(items); + } + + + /// + /// Unlink a node from the linked list by updating the node pointers in + /// its preceeding and subsequent node. Also update the _first and _last + /// pointers if necessary. + /// + private void Unlink(LinkedHashNode node) + { + if (node.Previous != null) + node.Previous.Next = node.Next; + + if (node.Next != null) + node.Next.Previous = node.Previous; + + if (ReferenceEquals(node, _first)) + _first = node.Next; + if (ReferenceEquals(node, _last)) + _last = node.Previous; + } + + [Serializable] + private class LinkedHashNode + { + public LinkedHashNode(TElement value) + { + Value = value; + } + + public TElement Value { get; private set; } + + public LinkedHashNode Next { get; set; } + public LinkedHashNode Previous { get; set; } + } + } +} + +#endif diff --git a/src/NHibernate/Impl/AbstractQueryImpl.cs b/src/NHibernate/Impl/AbstractQueryImpl.cs index 729334b5c50..f8c8095f99d 100644 --- a/src/NHibernate/Impl/AbstractQueryImpl.cs +++ b/src/NHibernate/Impl/AbstractQueryImpl.cs @@ -10,6 +10,7 @@ using NHibernate.Type; using NHibernate.Util; using System.Linq; +using System.Reflection; namespace NHibernate.Impl { @@ -195,7 +196,11 @@ private IType GuessType(System.Type clazz) string typename = clazz.AssemblyQualifiedName; IType type = TypeFactory.HeuristicType(typename); +#if FEATURE_SERIALIZATION bool serializable = (type != null && type is SerializableType); +#else + bool serializable = false; +#endif if (type == null || serializable) { try @@ -936,7 +941,7 @@ public IQuery SetIgnoreUknownNamedParameters(bool ignoredUnknownNamedParameters) public T UniqueResult() { object result = UniqueResult(); - if (result == null && typeof(T).IsValueType) + if (result == null && typeof(T).GetTypeInfo().IsValueType) { return default(T); } diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index aaa6ad229a9..e02c7f9dba0 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Data.Common; +using System.Reflection; using NHibernate.AdoNet; using NHibernate.Cache; using NHibernate.Collection; diff --git a/src/NHibernate/Impl/CriteriaImpl.cs b/src/NHibernate/Impl/CriteriaImpl.cs index 3f2edbd8afb..d2efa388444 100644 --- a/src/NHibernate/Impl/CriteriaImpl.cs +++ b/src/NHibernate/Impl/CriteriaImpl.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Reflection; using System.Text; using NHibernate.Criterion; using NHibernate.Engine; @@ -280,7 +281,7 @@ public IList List() public T UniqueResult() { object result = UniqueResult(); - if (result == null && typeof (T).IsValueType) + if (result == null && typeof (T).GetTypeInfo().IsValueType) { return default(T); } @@ -808,7 +809,7 @@ public IList List() public T UniqueResult() { object result = UniqueResult(); - if (result == null && typeof (T).IsValueType) + if (result == null && typeof (T).GetTypeInfo().IsValueType) { throw new InvalidCastException( "UniqueResult() cannot cast null result to value type. Call UniqueResult() instead"); diff --git a/src/NHibernate/Impl/ExpressionProcessor.cs b/src/NHibernate/Impl/ExpressionProcessor.cs index 6afd3d49f8d..ffb2c195632 100644 --- a/src/NHibernate/Impl/ExpressionProcessor.cs +++ b/src/NHibernate/Impl/ExpressionProcessor.cs @@ -301,7 +301,7 @@ private static bool IsCompilerGeneratedMemberExpressionOfCompilerGeneratedClass( var memberExpression = expression as MemberExpression; if (memberExpression != null && memberExpression.Member.DeclaringType != null) { - return Attribute.GetCustomAttribute(memberExpression.Member.DeclaringType, typeof(CompilerGeneratedAttribute)) != null + return memberExpression.Member.DeclaringType.GetTypeInfo().GetCustomAttribute() != null && GeneratedMemberNameRegex.IsMatch(memberExpression.Member.Name); } @@ -508,10 +508,10 @@ private static object ConvertType(object value, System.Type type) type = type.UnwrapIfNullable(); - if (type.IsEnum) + if (type.GetTypeInfo().IsEnum) return Enum.ToObject(type, value); - if (type.IsPrimitive) + if (type.GetTypeInfo().IsPrimitive) return Convert.ChangeType(value, type); throw new Exception(string.Format("Cannot convert '{0}' to {1}", value, type)); diff --git a/src/NHibernate/Impl/FilterImpl.cs b/src/NHibernate/Impl/FilterImpl.cs index 69926cac109..06d85df7d59 100644 --- a/src/NHibernate/Impl/FilterImpl.cs +++ b/src/NHibernate/Impl/FilterImpl.cs @@ -1,8 +1,9 @@ using System; using System.Collections; +using System.Collections.Generic; +using System.Reflection; using NHibernate.Engine; using NHibernate.Type; -using System.Collections.Generic; namespace NHibernate.Impl { diff --git a/src/NHibernate/Impl/MessageHelper.cs b/src/NHibernate/Impl/MessageHelper.cs index 04b3f828c2f..883dd5a4cb7 100644 --- a/src/NHibernate/Impl/MessageHelper.cs +++ b/src/NHibernate/Impl/MessageHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using System.Text; using NHibernate.Collection; using NHibernate.Engine; @@ -297,7 +298,7 @@ internal static String CollectionInfoString(ICollectionPersister persister, IPer object ownerKey; // TODO: Is it redundant to attempt to use the collectionKey, // or is always using the owner id sufficient? - if (ownerIdentifierType.ReturnedClass.IsInstanceOfType(collectionKey)) + if (collectionKey.GetType().GetTypeInfo().IsAssignableFrom(ownerIdentifierType.ReturnedClass)) { ownerKey = collectionKey; } diff --git a/src/NHibernate/Impl/SessionFactoryImpl.cs b/src/NHibernate/Impl/SessionFactoryImpl.cs index 32d4ef09edb..8cbfda43c77 100644 --- a/src/NHibernate/Impl/SessionFactoryImpl.cs +++ b/src/NHibernate/Impl/SessionFactoryImpl.cs @@ -3,9 +3,8 @@ using System.Collections.Generic; using System.Data.Common; using System.Linq; -using System.Runtime.Serialization; -using System.Security; using System.Text; +using System.Reflection; using NHibernate.Cache; using NHibernate.Cfg; using NHibernate.Connection; @@ -25,7 +24,6 @@ using NHibernate.Persister.Entity; using NHibernate.Proxy; using NHibernate.Stat; -using NHibernate.Tool.hbm2ddl; using NHibernate.Transaction; using NHibernate.Type; using NHibernate.Util; @@ -33,6 +31,15 @@ using HibernateDialect = NHibernate.Dialect.Dialect; using IQueryable = NHibernate.Persister.Entity.IQueryable; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Security; +#endif + +#if FEATURE_DATA_GETSCHEMATABLE +using NHibernate.Tool.hbm2ddl; +#endif + namespace NHibernate.Impl { /// @@ -72,7 +79,11 @@ namespace NHibernate.Impl /// /// [Serializable] - public sealed class SessionFactoryImpl : ISessionFactoryImplementor, IObjectReference + public sealed class SessionFactoryImpl + : ISessionFactoryImplementor +#if FEATURE_SERIALIZATION + , IObjectReference +#endif { #region Default entity not found delegate @@ -149,8 +160,12 @@ public void HandleEntityNotFound(string entityName, object id) [NonSerialized] private readonly ConcurrentDictionary queryCaches; + +#if FEATURE_DATA_GETSCHEMATABLE [NonSerialized] private readonly SchemaExport schemaExport; +#endif + [NonSerialized] private readonly Settings settings; @@ -193,6 +208,7 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties)); } +#if FEATURE_DATA_GETSCHEMATABLE try { if (settings.IsKeywordsImportEnabled) @@ -208,6 +224,7 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings { // Ignore if the Dialect does not provide DataBaseSchema } +#endif #region Caches settings.CacheProvider.Start(properties); @@ -349,6 +366,7 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings log.Debug("Instantiated session factory"); +#if FEATURE_DATA_GETSCHEMATABLE #region Schema management if (settings.IsAutoCreateSchema) { @@ -368,6 +386,7 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings schemaExport = new SchemaExport(cfg); } #endregion +#endif #region Obtaining TransactionManager // not ported yet @@ -421,6 +440,7 @@ public EventListeners EventListeners get { return eventListeners; } } +#if FEATURE_SERIALIZATION #region IObjectReference Members [SecurityCritical] @@ -457,6 +477,7 @@ public object GetRealObject(StreamingContext context) } #endregion +#endif #region ISessionFactoryImplementor Members @@ -839,10 +860,12 @@ public void Close() SessionFactoryObjectFactory.RemoveInstance(uuid, name, properties); } +#if FEATURE_DATA_GETSCHEMATABLE if (settings.IsAutoDropSchema) { schemaExport.Drop(false, true); } +#endif eventListeners.DestroyListeners(); } @@ -1229,14 +1252,20 @@ private ICurrentSessionContext BuildCurrentSessionContext() { case null: return null; +#if FEATURE_REMOTING case "call": return new CallSessionContext(this); +#endif case "thread_static": return new ThreadStaticSessionContext(this); +#if FEATURE_WEB_SESSION_CONTEXT case "web": return new WebSessionContext(this); +#endif +#if FEATURE_REMOTING case "wcf_operation": return new WcfOperationSessionContext(this); +#endif } try diff --git a/src/NHibernate/Impl/SessionFactoryObjectFactory.cs b/src/NHibernate/Impl/SessionFactoryObjectFactory.cs index d8e279acce5..9d234013e40 100644 --- a/src/NHibernate/Impl/SessionFactoryObjectFactory.cs +++ b/src/NHibernate/Impl/SessionFactoryObjectFactory.cs @@ -20,6 +20,7 @@ namespace NHibernate.Impl /// public static class SessionFactoryObjectFactory { + private static readonly object StaticSyncRoot = new object(); private static readonly IInternalLogger log; private static readonly IDictionary Instances = new Dictionary(); @@ -39,25 +40,27 @@ static SessionFactoryObjectFactory() /// The name of the ISessionFactory. /// The ISessionFactory. /// The configured properties for the ISessionFactory. - [MethodImpl(MethodImplOptions.Synchronized)] public static void AddInstance(string uid, string name, ISessionFactory instance, IDictionary properties) { - if (log.IsDebugEnabled) + lock (StaticSyncRoot) { - string nameMsg = ((!string.IsNullOrEmpty(name)) ? name : "unnamed"); + if (log.IsDebugEnabled) + { + string nameMsg = ((!string.IsNullOrEmpty(name)) ? name : "unnamed"); - log.Debug("registered: " + uid + "(" + nameMsg + ")"); - } + log.Debug("registered: " + uid + "(" + nameMsg + ")"); + } - Instances[uid] = instance; - if (!string.IsNullOrEmpty(name)) - { - log.Info("Factory name:" + name); - NamedInstances[name] = instance; - } - else - { - log.Info("no name configured"); + Instances[uid] = instance; + if (!string.IsNullOrEmpty(name)) + { + log.Info("Factory name:" + name); + NamedInstances[name] = instance; + } + else + { + log.Info("no name configured"); + } } } @@ -67,15 +70,17 @@ public static void AddInstance(string uid, string name, ISessionFactory instance /// The identifier of the ISessionFactory. /// The name of the ISessionFactory. /// The configured properties for the ISessionFactory. - [MethodImpl(MethodImplOptions.Synchronized)] public static void RemoveInstance(string uid, string name, IDictionary properties) { - if (!string.IsNullOrEmpty(name)) + lock (StaticSyncRoot) { - log.Info("unbinding factory: " + name); - NamedInstances.Remove(name); + if (!string.IsNullOrEmpty(name)) + { + log.Info("unbinding factory: " + name); + NamedInstances.Remove(name); + } + Instances.Remove(uid); } - Instances.Remove(uid); } /// @@ -83,17 +88,19 @@ public static void RemoveInstance(string uid, string name, IDictionary /// The name of the ISessionFactory. /// An instantiated ISessionFactory. - [MethodImpl(MethodImplOptions.Synchronized)] public static ISessionFactory GetNamedInstance(string name) { - log.Debug("lookup: name=" + name); - ISessionFactory factory; - bool found=NamedInstances.TryGetValue(name, out factory); - if (!found) + lock (StaticSyncRoot) { - log.Warn("Not found: " + name); + log.Debug("lookup: name=" + name); + ISessionFactory factory; + bool found=NamedInstances.TryGetValue(name, out factory); + if (!found) + { + log.Warn("Not found: " + name); + } + return factory; } - return factory; } /// @@ -101,17 +108,19 @@ public static ISessionFactory GetNamedInstance(string name) /// /// The identifier of the ISessionFactory. /// An instantiated ISessionFactory. - [MethodImpl(MethodImplOptions.Synchronized)] public static ISessionFactory GetInstance(string uid) { - log.Debug("lookup: uid=" + uid); - ISessionFactory factory; - bool found = Instances.TryGetValue(uid, out factory); - if (!found) + lock (StaticSyncRoot) { - log.Warn("Not found: " + uid); + log.Debug("lookup: uid=" + uid); + ISessionFactory factory; + bool found = Instances.TryGetValue(uid, out factory); + if (!found) + { + log.Warn("Not found: " + uid); + } + return factory; } - return factory; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Impl/SessionImpl.cs b/src/NHibernate/Impl/SessionImpl.cs index 4cef69ec6d8..3912bcd88d8 100644 --- a/src/NHibernate/Impl/SessionImpl.cs +++ b/src/NHibernate/Impl/SessionImpl.cs @@ -4,8 +4,6 @@ using System.Data; using System.Data.Common; using System.Linq.Expressions; -using System.Runtime.Serialization; -using System.Security; using NHibernate.AdoNet; using NHibernate.Collection; using NHibernate.Criterion; @@ -24,6 +22,11 @@ using NHibernate.Type; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Security; +#endif + namespace NHibernate.Impl { /// @@ -36,7 +39,11 @@ namespace NHibernate.Impl /// hard stuff is... This class is NOT THREADSAFE. /// [Serializable] - public sealed class SessionImpl : AbstractSessionImpl, IEventSource, ISerializable, IDeserializationCallback + public sealed class SessionImpl + : AbstractSessionImpl, IEventSource +#if FEATURE_SERIALIZATION + , ISerializable, IDeserializationCallback +#endif { private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SessionImpl)); @@ -90,6 +97,7 @@ public sealed class SessionImpl : AbstractSessionImpl, IEventSource, ISerializab [NonSerialized] private readonly ConnectionReleaseMode connectionReleaseMode; +#if FEATURE_SERIALIZATION #region System.Runtime.Serialization.ISerializable Members /// @@ -187,6 +195,7 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif /// /// Constructor used for OpenSession(...) processing, as well as construction diff --git a/src/NHibernate/InstantiationException.cs b/src/NHibernate/InstantiationException.cs index 08496bffdc2..480a8d384f6 100644 --- a/src/NHibernate/InstantiationException.cs +++ b/src/NHibernate/InstantiationException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -61,6 +63,7 @@ public override string Message get { return base.Message + (type == null ? "" : type.FullName); } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -98,5 +101,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/InvalidProxyTypeException.cs b/src/NHibernate/InvalidProxyTypeException.cs index 946478379ba..d646e13ae7f 100644 --- a/src/NHibernate/InvalidProxyTypeException.cs +++ b/src/NHibernate/InvalidProxyTypeException.cs @@ -1,11 +1,13 @@ using System; using System.Collections; -using System.Runtime.Serialization; -using System.Security; -using System.Security.Permissions; using System.Text; using System.Collections.Generic; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +using System.Security; +#endif + namespace NHibernate { /// @@ -34,6 +36,7 @@ private static string FormatMessage(IEnumerable errors) return result.ToString(); } +#if FEATURE_SERIALIZATION #region Serialization public InvalidProxyTypeException(SerializationInfo info, StreamingContext context) @@ -50,5 +53,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/LazyInitializationException.cs b/src/NHibernate/LazyInitializationException.cs index 8f08a502fc2..73e4786c315 100644 --- a/src/NHibernate/LazyInitializationException.cs +++ b/src/NHibernate/LazyInitializationException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate @@ -63,6 +66,7 @@ public LazyInitializationException(string message, Exception innerException) : b LoggerProvider.LoggerFor(typeof(LazyInitializationException)).Error(message, this); } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -77,5 +81,6 @@ public LazyInitializationException(string message, Exception innerException) : b protected LazyInitializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/Clauses/NhJoinClause.cs b/src/NHibernate/Linq/Clauses/NhJoinClause.cs index 1a246af6dce..619909085cd 100644 --- a/src/NHibernate/Linq/Clauses/NhJoinClause.cs +++ b/src/NHibernate/Linq/Clauses/NhJoinClause.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq.Expressions; using NHibernate.Linq.Visitors; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; -using Remotion.Linq.Collections; namespace NHibernate.Linq.Clauses { @@ -59,4 +59,4 @@ public override void TransformExpressions(Func transform base.TransformExpressions(transformation); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs b/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs index 4fe954d31f3..4c86a0c4854 100644 --- a/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs +++ b/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs @@ -4,7 +4,6 @@ using System.Linq.Expressions; using System.Reflection; using Remotion.Linq; -using Remotion.Linq.Utilities; namespace NHibernate.Linq { @@ -13,40 +12,40 @@ public static class EagerFetchingExtensionMethods public static INhFetchRequest Fetch( this IQueryable query, Expression> relatedObjectSelector) { - ArgumentUtility.CheckNotNull("query", query); - ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector); + CheckNotNull("query", query); + CheckNotNull("relatedObjectSelector", relatedObjectSelector); - var methodInfo = ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOriginating), typeof(TRelated)); + var methodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(nameof(Fetch)).MakeGenericMethod(typeof(TOriginating), typeof(TRelated)); return CreateFluentFetchRequest(methodInfo, query, relatedObjectSelector); } public static INhFetchRequest FetchMany( this IQueryable query, Expression>> relatedObjectSelector) { - ArgumentUtility.CheckNotNull("query", query); - ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector); + CheckNotNull("query", query); + CheckNotNull("relatedObjectSelector", relatedObjectSelector); - var methodInfo = ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOriginating), typeof(TRelated)); + var methodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(nameof(FetchMany)).MakeGenericMethod(typeof(TOriginating), typeof(TRelated)); return CreateFluentFetchRequest(methodInfo, query, relatedObjectSelector); } public static INhFetchRequest ThenFetch( this INhFetchRequest query, Expression> relatedObjectSelector) { - ArgumentUtility.CheckNotNull("query", query); - ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector); + CheckNotNull("query", query); + CheckNotNull("relatedObjectSelector", relatedObjectSelector); - var methodInfo = ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TQueried), typeof(TFetch), typeof(TRelated)); + var methodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(nameof(ThenFetch)).MakeGenericMethod(typeof(TQueried), typeof(TFetch), typeof(TRelated)); return CreateFluentFetchRequest(methodInfo, query, relatedObjectSelector); } public static INhFetchRequest ThenFetchMany( this INhFetchRequest query, Expression>> relatedObjectSelector) { - ArgumentUtility.CheckNotNull("query", query); - ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector); + CheckNotNull("query", query); + CheckNotNull("relatedObjectSelector", relatedObjectSelector); - var methodInfo = ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TQueried), typeof(TFetch), typeof(TRelated)); + var methodInfo = typeof(EagerFetchingExtensionMethods).GetMethod(nameof(ThenFetchMany)).MakeGenericMethod(typeof(TQueried), typeof(TFetch), typeof(TRelated)); return CreateFluentFetchRequest(methodInfo, query, relatedObjectSelector); } @@ -59,7 +58,14 @@ private static INhFetchRequest CreateFluentFetchRequest< var callExpression = Expression.Call(currentFetchMethod, query.Expression, relatedObjectSelector); return new NhFetchRequest(queryProvider, callExpression); } - } + + private static T CheckNotNull(string argumentName, T actualValue) + { + if ((object)actualValue == null) + throw new ArgumentNullException(argumentName); + return actualValue; + } + } public interface INhFetchRequest : IOrderedQueryable { @@ -72,4 +78,4 @@ public NhFetchRequest(IQueryProvider provider, Expression expression) { } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/EnumerableHelper.cs b/src/NHibernate/Linq/EnumerableHelper.cs index f36bf432506..eac5d58ee00 100644 --- a/src/NHibernate/Linq/EnumerableHelper.cs +++ b/src/NHibernate/Linq/EnumerableHelper.cs @@ -129,7 +129,7 @@ private static bool ParameterTypesMatch(ParameterInfo[] parameters, System.Type[ continue; } - if (parameters[i].ParameterType.ContainsGenericParameters && types[i].ContainsGenericParameters && + if (parameters[i].ParameterType.GetTypeInfo().ContainsGenericParameters && types[i].GetTypeInfo().ContainsGenericParameters && parameters[i].ParameterType.GetGenericArguments().Length == types[i].GetGenericArguments().Length) { continue; @@ -141,4 +141,4 @@ private static bool ParameterTypesMatch(ParameterInfo[] parameters, System.Type[ return true; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/ExpressionExtensions.cs b/src/NHibernate/Linq/ExpressionExtensions.cs index 8c84ccfe302..def44c8d4f5 100644 --- a/src/NHibernate/Linq/ExpressionExtensions.cs +++ b/src/NHibernate/Linq/ExpressionExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; @@ -12,7 +13,7 @@ public static class ExpressionExtensions public static bool IsGroupingKey(this MemberExpression expression) { return expression.Member.Name == "Key" && expression.Member.DeclaringType!=null && - expression.Member.DeclaringType.IsGenericType && expression.Member.DeclaringType.GetGenericTypeDefinition() == typeof(IGrouping<,>); + expression.Member.DeclaringType.GetTypeInfo().IsGenericType && expression.Member.DeclaringType.GetGenericTypeDefinition() == typeof(IGrouping<,>); } public static bool IsGroupingKeyOf(this MemberExpression expression,GroupResultOperator groupBy) diff --git a/src/NHibernate/Linq/ExpressionToHqlTranslationResults.cs b/src/NHibernate/Linq/ExpressionToHqlTranslationResults.cs index 5c1ed7c5b4a..c4002bbb67a 100644 --- a/src/NHibernate/Linq/ExpressionToHqlTranslationResults.cs +++ b/src/NHibernate/Linq/ExpressionToHqlTranslationResults.cs @@ -43,7 +43,7 @@ private static TDelegate MergeLambdasAndCompile(IList transformat return lambda; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/ExpressionTransformers/RemoveRedundantCast.cs b/src/NHibernate/Linq/ExpressionTransformers/RemoveRedundantCast.cs index d5a87a97eb9..d5f26183d68 100644 --- a/src/NHibernate/Linq/ExpressionTransformers/RemoveRedundantCast.cs +++ b/src/NHibernate/Linq/ExpressionTransformers/RemoveRedundantCast.cs @@ -1,4 +1,5 @@ using System.Linq.Expressions; +using System.Reflection; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; namespace NHibernate.Linq.ExpressionTransformers @@ -34,4 +35,4 @@ public ExpressionType[] SupportedExpressionTypes get { return _supportedExpressionTypes; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs b/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs index 760b029e22f..b8094be119e 100644 --- a/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs +++ b/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs @@ -37,7 +37,7 @@ private static HqlExpression GetRhs(MethodInfo method, ReadOnlyCollection x.Type.IsValueType ? Expression.Convert(x, typeof(object)) : x)); + groupBy.KeySelector = Expression.NewArrayInit(typeof (object), keys.Select(x => x.Type.GetTypeInfo().IsValueType ? Expression.Convert(x, typeof(object)) : x)); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/GroupBy/NonAggregatingGroupByRewriter.cs b/src/NHibernate/Linq/GroupBy/NonAggregatingGroupByRewriter.cs index 120d332a7f4..384e3ed542d 100644 --- a/src/NHibernate/Linq/GroupBy/NonAggregatingGroupByRewriter.cs +++ b/src/NHibernate/Linq/GroupBy/NonAggregatingGroupByRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Linq.Expressions; +using System.Reflection; using NHibernate.Linq.ResultOperators; using Remotion.Linq; using Remotion.Linq.Clauses; @@ -103,4 +104,4 @@ public ClientSideSelect2(LambdaExpression selectClause) SelectClause = selectClause; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/NestedSelects/NestedSelectRewriter.cs b/src/NHibernate/Linq/NestedSelects/NestedSelectRewriter.cs index 56a5ded7921..8be488266bc 100644 --- a/src/NHibernate/Linq/NestedSelects/NestedSelectRewriter.cs +++ b/src/NHibernate/Linq/NestedSelects/NestedSelectRewriter.cs @@ -182,9 +182,9 @@ private static Expression SubCollectionQuery(System.Type collectionType, System. private static ConstructorInfo GetCollectionConstructor(System.Type collectionType, System.Type elementType) { - if (collectionType.IsInterface) + if (collectionType.GetTypeInfo().IsInterface) { - if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(ISet<>)) + if (collectionType.GetTypeInfo().IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(ISet<>)) { return typeof(HashSet<>).MakeGenericType(elementType).GetConstructor(new[] { typeof(IEnumerable<>).MakeGenericType(elementType) }); } @@ -210,7 +210,7 @@ private static LambdaExpression MakePredicate(int index) private static Expression GetIdentifier(ISessionFactory sessionFactory, Expression expression) { - if (expression.Type.IsPrimitive || expression.Type == typeof(string)) + if (expression.Type.GetTypeInfo().IsPrimitive || expression.Type == typeof(string)) return expression; var classMetadata = sessionFactory.GetClassMetadata(expression.Type); diff --git a/src/NHibernate/Linq/NhLinqExpression.cs b/src/NHibernate/Linq/NhLinqExpression.cs index d7c671ced7d..a9e084c4a54 100644 --- a/src/NHibernate/Linq/NhLinqExpression.cs +++ b/src/NHibernate/Linq/NhLinqExpression.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using NHibernate.Engine; using NHibernate.Engine.Query; using NHibernate.Hql.Ast.ANTLR.Tree; diff --git a/src/NHibernate/Linq/ReWriters/RemoveUnnecessaryBodyOperators.cs b/src/NHibernate/Linq/ReWriters/RemoveUnnecessaryBodyOperators.cs index fc42a14eeff..90b4655ff6d 100644 --- a/src/NHibernate/Linq/ReWriters/RemoveUnnecessaryBodyOperators.cs +++ b/src/NHibernate/Linq/ReWriters/RemoveUnnecessaryBodyOperators.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using NHibernate.Util; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.ResultOperators; @@ -31,14 +32,14 @@ public override void VisitResultOperator(ResultOperatorBase resultOperator, Quer } if (resultOperator is CastResultOperator) { - Array.ForEach(queryModel.ResultOperators.OfType().ToArray(), castOperator=> queryModel.ResultOperators.Remove(castOperator)); + queryModel.ResultOperators.OfType().ToArray().ForEach(castOperator => queryModel.ResultOperators.Remove(castOperator)); } if (resultOperator is AnyResultOperator) { - Array.ForEach(queryModel.ResultOperators.OfType().ToArray(), op => queryModel.ResultOperators.Remove(op)); - Array.ForEach(queryModel.ResultOperators.OfType().ToArray(), op => queryModel.ResultOperators.Remove(op)); + queryModel.ResultOperators.OfType().ToArray().ForEach(op => queryModel.ResultOperators.Remove(op)); + queryModel.ResultOperators.OfType().ToArray().ForEach(op => queryModel.ResultOperators.Remove(op)); } base.VisitResultOperator(resultOperator, queryModel, index); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/ReWriters/ResultOperatorRewriter.cs b/src/NHibernate/Linq/ReWriters/ResultOperatorRewriter.cs index fe1e50f7c40..0ab135b5925 100644 --- a/src/NHibernate/Linq/ReWriters/ResultOperatorRewriter.cs +++ b/src/NHibernate/Linq/ReWriters/ResultOperatorRewriter.cs @@ -5,6 +5,7 @@ namespace NHibernate.Linq.ReWriters using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; + using System.Reflection; using NHibernate.Linq.Visitors; @@ -46,7 +47,7 @@ public override void VisitMainFromClause(MainFromClause fromClause, QueryModel q if (fromClause.FromExpression.NodeType == ExpressionType.Constant) { System.Type expressionType = queryModel.MainFromClause.FromExpression.Type; - if (expressionType.IsGenericType && expressionType.GetGenericTypeDefinition() == typeof(NhQueryable<>)) + if (expressionType.GetTypeInfo().IsGenericType && expressionType.GetGenericTypeDefinition() == typeof(NhQueryable<>)) { queryModel.MainFromClause.ItemType = expressionType.GetGenericArguments()[0]; } diff --git a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs index dbe44395a50..dd73b2e7dce 100644 --- a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs +++ b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using NHibernate.Engine.Query; using NHibernate.Hql.Ast; using NHibernate.Linq.Expressions; @@ -447,8 +448,8 @@ protected HqlTreeNode VisitUnaryExpression(UnaryExpression expression) case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.TypeAs: - if ((expression.Operand.Type.IsPrimitive || expression.Operand.Type == typeof(Decimal)) && - (expression.Type.IsPrimitive || expression.Type == typeof(Decimal))) + if ((expression.Operand.Type.GetTypeInfo().IsPrimitive || expression.Operand.Type == typeof(Decimal)) && + (expression.Type.GetTypeInfo().IsPrimitive || expression.Type == typeof(Decimal))) { return _hqlTreeBuilder.Cast(VisitExpression(expression.Operand).AsExpression(), expression.Type); } diff --git a/src/NHibernate/Linq/Visitors/QuerySourceLocator.cs b/src/NHibernate/Linq/Visitors/QuerySourceLocator.cs index c6a80ddd380..910aacbb158 100644 --- a/src/NHibernate/Linq/Visitors/QuerySourceLocator.cs +++ b/src/NHibernate/Linq/Visitors/QuerySourceLocator.cs @@ -1,4 +1,5 @@ -using Remotion.Linq; +using System.Reflection; +using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Collections; @@ -49,4 +50,4 @@ public override void VisitMainFromClause(MainFromClause fromClause, QueryModel q } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregateFromSeed.cs b/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregateFromSeed.cs index 34f3b4d39fe..f514dcc5e88 100644 --- a/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregateFromSeed.cs +++ b/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregateFromSeed.cs @@ -1,6 +1,9 @@ using System.Collections.Generic; using System.Linq.Expressions; using NHibernate.Util; +using System.Reflection; +using System.Text; +using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Clauses.StreamedData; using Remotion.Linq.Parsing.ExpressionTreeVisitors; diff --git a/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessClientSideSelect.cs b/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessClientSideSelect.cs index 81bf0fc1c7d..3ee18791303 100644 --- a/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessClientSideSelect.cs +++ b/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessClientSideSelect.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq.Expressions; +using System.Reflection; using NHibernate.Linq.GroupBy; using NHibernate.Util; @@ -32,4 +33,4 @@ public void Process(ClientSideSelect2 resultOperator, QueryModelVisitor queryMod tree.AddListTransformer(resultOperator.SelectClause); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs b/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs index 4b2254e53e3..db0a2aa3c46 100644 --- a/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs +++ b/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs @@ -61,7 +61,7 @@ public void Visit(Expression expression) } // Handle any boolean results in the output nodes - _hqlTreeNodes = _hqlTreeNodes.ConvertAll(node => node.ToArithmeticExpression()); + _hqlTreeNodes = _hqlTreeNodes.Select(node => node.ToArithmeticExpression()).ToList(); if (distinct != null) { diff --git a/src/NHibernate/Loader/BasicLoader.cs b/src/NHibernate/Loader/BasicLoader.cs index a9958c88666..4f673b39f8d 100644 --- a/src/NHibernate/Loader/BasicLoader.cs +++ b/src/NHibernate/Loader/BasicLoader.cs @@ -1,3 +1,4 @@ +using System.Reflection; using NHibernate.Engine; using NHibernate.Persister.Collection; using NHibernate.Persister.Entity; @@ -69,7 +70,7 @@ protected override void PostInstantiate() private static bool IsBag(ICollectionPersister collectionPersister) { var type = collectionPersister.CollectionType.GetType(); - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof (GenericBagType<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof (GenericBagType<>); } /// @@ -99,4 +100,4 @@ public static string[] GenerateSuffixes(int seed, int length) return suffixes; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 5baefdf843e..dd7025c0306 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -1292,20 +1292,22 @@ protected internal virtual void AutoDiscoverTypes(DbDataReader rs) throw new AssertionFailure("Auto discover types not supported in this loader"); } - [MethodImpl(MethodImplOptions.Synchronized)] private DbDataReader WrapResultSet(DbDataReader rs) { - // synchronized to avoid multi-thread access issues; defined as method synch to avoid - // potential deadlock issues due to nature of code. - try - { - Log.Debug("Wrapping result set [" + rs + "]"); - return new ResultSetWrapper(rs, RetreiveColumnNameToIndexCache(rs)); - } - catch (Exception e) + lock (this) { - Log.Info("Error wrapping result set", e); - return rs; + // synchronized to avoid multi-thread access issues; defined as method synch to avoid + // potential deadlock issues due to nature of code. + try + { + Log.Debug("Wrapping result set [" + rs + "]"); + return new ResultSetWrapper(rs, RetreiveColumnNameToIndexCache(rs)); + } + catch (Exception e) + { + Log.Info("Error wrapping result set", e); + return rs; + } } } @@ -1314,7 +1316,13 @@ private ColumnNameCache RetreiveColumnNameToIndexCache(DbDataReader rs) if (_columnNameCache == null) { Log.Debug("Building columnName->columnIndex cache"); - _columnNameCache = new ColumnNameCache(rs.GetSchemaTable().Rows.Count); + _columnNameCache = new ColumnNameCache( +#if FEATURE_DATA_GETSCHEMATABLE + rs.GetSchemaTable().Rows.Count +#else + 0 +#endif + ); } return _columnNameCache; @@ -1859,4 +1867,4 @@ protected bool TryGetLimitString(Dialect.Dialect dialect, SqlString queryString, #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Logging.cs b/src/NHibernate/Logging.cs index 32a39d1683c..de8fca955a8 100644 --- a/src/NHibernate/Logging.cs +++ b/src/NHibernate/Logging.cs @@ -1,10 +1,14 @@ using System; -using System.Configuration; using System.IO; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using NHibernate.Util; +#if FEATURE_SYSTEM_CONFIGURATION +using System.Configuration; +#endif + namespace NHibernate { public interface IInternalLogger @@ -63,40 +67,53 @@ private static ILoggerFactory GetLoggerFactory(string nhibernateLoggerClass) } catch (MissingMethodException ex) { - throw new ApplicationException("Public constructor was not found for " + loggerFactoryType, ex); + throw new Exception("Public constructor was not found for " + loggerFactoryType, ex); } catch (InvalidCastException ex) { - throw new ApplicationException(loggerFactoryType + "Type does not implement " + typeof (ILoggerFactory), ex); + throw new Exception(loggerFactoryType + "Type does not implement " + typeof (ILoggerFactory), ex); } catch (Exception ex) { - throw new ApplicationException("Unable to instantiate: " + loggerFactoryType, ex); + throw new Exception("Unable to instantiate: " + loggerFactoryType, ex); } return loggerFactory; } private static string GetNhibernateLoggerClass() { - var nhibernateLogger = ConfigurationManager.AppSettings.Keys.Cast().FirstOrDefault(k => NhibernateLoggerConfKey.Equals(k.ToLowerInvariant())); string nhibernateLoggerClass = null; +#if FEATURE_SYSTEM_CONFIGURATION + var nhibernateLogger = ConfigurationManager.AppSettings.Keys.Cast().FirstOrDefault(k => NhibernateLoggerConfKey.Equals(k.ToLowerInvariant())); if (string.IsNullOrEmpty(nhibernateLogger)) +#endif { // look for log4net.dll +#if FEATURE_APPDOMAIN string baseDir = AppDomain.CurrentDomain.BaseDirectory; string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath; +#else + string baseDir = AppContext.BaseDirectory; + string relativeSearchPath = null; +#endif string binPath = relativeSearchPath == null ? baseDir : Path.Combine(baseDir, relativeSearchPath); string log4NetDllPath = binPath == null ? "log4net.dll" : Path.Combine(binPath, "log4net.dll"); - if (File.Exists(log4NetDllPath) || AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == "log4net")) + if (File.Exists(log4NetDllPath) +#if FEATURE_APPDOMAIN + || AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == "log4net") +#endif + ) { nhibernateLoggerClass = typeof (Log4NetLoggerFactory).AssemblyQualifiedName; } } +#if FEATURE_SYSTEM_CONFIGURATION else { nhibernateLoggerClass = ConfigurationManager.AppSettings[nhibernateLogger]; } +#endif return nhibernateLoggerClass; } @@ -241,7 +258,7 @@ public IInternalLogger LoggerFor(System.Type type) private static Func GetGetLoggerMethodCall() { - var method = LogManagerType.GetMethod("GetLogger", new[] { typeof(TParameter) }); + var method = LogManagerType.GetTypeInfo().GetMethod("GetLogger", new[] { typeof(TParameter) }); ParameterExpression resultValue; ParameterExpression keyParam = Expression.Parameter(typeof(TParameter), "key"); MethodCallExpression methodCall = Expression.Call(null, method, resultValue = keyParam); diff --git a/src/NHibernate/Mapping/ByCode/AbstractExplicitlyDeclaredModel.cs b/src/NHibernate/Mapping/ByCode/AbstractExplicitlyDeclaredModel.cs index 421fb769ab1..9b4e9c8cdff 100644 --- a/src/NHibernate/Mapping/ByCode/AbstractExplicitlyDeclaredModel.cs +++ b/src/NHibernate/Mapping/ByCode/AbstractExplicitlyDeclaredModel.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using System.Text; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode { @@ -228,7 +229,7 @@ protected virtual void AddAsTablePerClassEntity(System.Type type, bool rootEntit { if(!rootEntityMustExists) { - delayedRootEntityRegistrations.Enqueue(() => System.Array.ForEach(GetRootEntitiesOf(type).ToArray(), root=> tablePerClassEntities.Add(root))); + delayedRootEntityRegistrations.Enqueue(() => GetRootEntitiesOf(type).ForEach(root => tablePerClassEntities.Add(root))); EnlistTypeRegistration(type, t => AddAsTablePerClassEntity(t, true)); return; } @@ -263,7 +264,7 @@ protected virtual void AddAsTablePerClassHierarchyEntity(System.Type type, bool { if (!rootEntityMustExists) { - delayedRootEntityRegistrations.Enqueue(() => System.Array.ForEach(GetRootEntitiesOf(type).ToArray(), root => tablePerClassHierarchyEntities.Add(root))); + delayedRootEntityRegistrations.Enqueue(() => GetRootEntitiesOf(type).ForEach(root => tablePerClassHierarchyEntities.Add(root))); EnlistTypeRegistration(type, t => AddAsTablePerClassHierarchyEntity(t, true)); return; } @@ -299,7 +300,7 @@ protected virtual void AddAsTablePerConcreteClassEntity(System.Type type, bool r { if (!rootEntityMustExists) { - delayedRootEntityRegistrations.Enqueue(() => System.Array.ForEach(GetRootEntitiesOf(type).ToArray(), root => tablePerConcreteClassEntities.Add(root))); + delayedRootEntityRegistrations.Enqueue(() => GetRootEntitiesOf(type).ForEach(root => tablePerConcreteClassEntities.Add(root))); EnlistTypeRegistration(type, t => AddAsTablePerConcreteClassEntity(t, true)); return; } @@ -450,7 +451,7 @@ public void AddAsPropertySplit(SplitDefinition definition) System.Type propertyContainer = definition.On; string splitGroupId = definition.GroupId; MemberInfo member = definition.Member; - var memberKey = member.GetMemberFromDeclaringType(); + var memberKey = member.GetMemberFromDeclaringType(propertyContainer); string splitGroup; if (!memberSplitGroup.TryGetValue(memberKey, out splitGroup)) { @@ -592,4 +593,4 @@ protected bool HasDelayedEntityRegistration(System.Type type) return delayedEntityRegistrations.ContainsKey(type); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/ConventionModelMapper.cs b/src/NHibernate/Mapping/ByCode/ConventionModelMapper.cs index 6a6e6ed57d7..d2dd8ad06ec 100644 --- a/src/NHibernate/Mapping/ByCode/ConventionModelMapper.cs +++ b/src/NHibernate/Mapping/ByCode/ConventionModelMapper.cs @@ -61,9 +61,9 @@ protected virtual void ComponentParentToFieldAccessor(IModelInspector modelInspe { System.Type componentType = member.LocalMember.GetPropertyOrFieldType(); IEnumerable persistentProperties = - MembersProvider.GetComponentMembers(componentType).Where(p => ModelInspector.IsPersistentProperty(p)); + MembersProvider.GetComponentMembers(componentType).Where(p => ModelInspector.IsPersistentProperty(p, componentType)); - MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, member.LocalMember.ReflectedType); + MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, member.ComponentType, componentType); if (parentReferenceProperty != null && MatchPropertyToField(parentReferenceProperty)) { componentMapper.Parent(parentReferenceProperty, cp=> cp.Access(Accessor.Field)); @@ -74,9 +74,9 @@ protected virtual void ComponentParentNoSetterToField(IModelInspector modelInspe { System.Type componentType = member.LocalMember.GetPropertyOrFieldType(); IEnumerable persistentProperties = - MembersProvider.GetComponentMembers(componentType).Where(p => ModelInspector.IsPersistentProperty(p)); + MembersProvider.GetComponentMembers(componentType).Where(p => ModelInspector.IsPersistentProperty(p, componentType)); - MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, member.LocalMember.ReflectedType); + MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, member.ComponentType, componentType); if (parentReferenceProperty != null && MatchNoSetterProperty(parentReferenceProperty)) { componentMapper.Parent(parentReferenceProperty, cp => cp.Access(Accessor.NoSetter)); @@ -107,12 +107,12 @@ protected bool MatchReadOnlyProperty(MemberInfo subject) private bool CanReadCantWriteInsideType(PropertyInfo property) { - return !property.CanWrite && property.CanRead && property.DeclaringType == property.ReflectedType; + return !property.CanWrite && property.CanRead && property.DeclaringType == property.DeclaringType; } private bool CanReadCantWriteInBaseType(PropertyInfo property) { - if (property.DeclaringType == property.ReflectedType) + if (property.DeclaringType == property.DeclaringType) { return false; } @@ -155,7 +155,7 @@ protected bool MatchPropertyToField(MemberInfo subject) protected virtual void NoSetterPoidToField(IModelInspector modelInspector, System.Type type, IClassAttributesMapper classCustomizer) { - MemberInfo poidPropertyOrField = MembersProvider.GetEntityMembersForPoid(type).FirstOrDefault(modelInspector.IsPersistentId); + MemberInfo poidPropertyOrField = MembersProvider.GetEntityMembersForPoid(type).FirstOrDefault(mi => modelInspector.IsPersistentId(mi, type)); if(MatchNoSetterProperty(poidPropertyOrField)) { classCustomizer.Id(idm=> idm.Access(Accessor.NoSetter)); @@ -180,7 +180,7 @@ protected bool MatchNoSetterProperty(MemberInfo subject) protected virtual void NoPoidGuid(IModelInspector modelInspector, System.Type type, IClassAttributesMapper classCustomizer) { - MemberInfo poidPropertyOrField = MembersProvider.GetEntityMembersForPoid(type).FirstOrDefault(mi => modelInspector.IsPersistentId(mi)); + MemberInfo poidPropertyOrField = MembersProvider.GetEntityMembersForPoid(type).FirstOrDefault(mi => modelInspector.IsPersistentId(mi, type)); if (!ReferenceEquals(null, poidPropertyOrField)) { return; @@ -313,4 +313,4 @@ public void IsTablePerClassSplit(Func match) SimpleModelInspector.IsTablePerClassSplit(match); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/ExplicitlyDeclaredModel.cs b/src/NHibernate/Mapping/ByCode/ExplicitlyDeclaredModel.cs index a5725776d38..553db439070 100644 --- a/src/NHibernate/Mapping/ByCode/ExplicitlyDeclaredModel.cs +++ b/src/NHibernate/Mapping/ByCode/ExplicitlyDeclaredModel.cs @@ -46,7 +46,7 @@ public virtual bool IsTablePerConcreteClass(System.Type type) return IsMappedForTablePerConcreteClassEntities(type); } - public virtual bool IsOneToOne(MemberInfo member) + public virtual bool IsOneToOne(MemberInfo member, System.Type _) { return OneToOneRelations.Contains(member); } @@ -56,12 +56,17 @@ public virtual bool IsManyToOne(MemberInfo member) return ManyToOneRelations.Contains(member); } - public virtual bool IsManyToManyItem(MemberInfo member) + public virtual bool IsManyToOne(MemberInfo member, System.Type _) + { + return ManyToOneRelations.Contains(member); + } + + public virtual bool IsManyToManyItem(MemberInfo member, System.Type _) { return ItemManyToManyRelations.Contains(member); } - public virtual bool IsManyToManyKey(MemberInfo member) + public virtual bool IsManyToManyKey(MemberInfo member, System.Type _) { return KeyManyToManyRelations.Contains(member); } @@ -71,12 +76,17 @@ public virtual bool IsOneToMany(MemberInfo member) return OneToManyRelations.Contains(member); } - public bool IsManyToAny(MemberInfo member) + public virtual bool IsOneToMany(MemberInfo member, System.Type _) + { + return OneToManyRelations.Contains(member); + } + + public bool IsManyToAny(MemberInfo member, System.Type _) { return ManyToAnyRelations.Contains(member); } - public virtual bool IsAny(MemberInfo member) + public virtual bool IsAny(MemberInfo member, System.Type _) { return Any.Contains(member); } @@ -86,6 +96,11 @@ public virtual bool IsPersistentId(MemberInfo member) return Poids.Contains(member); } + public virtual bool IsPersistentId(MemberInfo member, System.Type _) + { + return Poids.Contains(member); + } + public bool IsMemberOfComposedId(MemberInfo member) { return ComposedIds.Contains(member); @@ -96,32 +111,57 @@ public virtual bool IsVersion(MemberInfo member) return VersionProperties.Contains(member); } + public virtual bool IsVersion(MemberInfo member, System.Type _) + { + return VersionProperties.Contains(member); + } + public virtual bool IsMemberOfNaturalId(MemberInfo member) { return NaturalIds.Contains(member); } + public virtual bool IsMemberOfNaturalId(MemberInfo member, System.Type _) + { + return NaturalIds.Contains(member); + } + public virtual bool IsPersistentProperty(MemberInfo member) { return PersistentMembers.Contains(member); } + public virtual bool IsPersistentProperty(MemberInfo member, System.Type _) + { + return PersistentMembers.Contains(member); + } + public virtual bool IsSet(MemberInfo role) { return Sets.Contains(role); } + public virtual bool IsSet(MemberInfo role, System.Type _) + { + return Sets.Contains(role); + } + public virtual bool IsBag(MemberInfo role) { return Bags.Contains(role); } - public virtual bool IsIdBag(MemberInfo role) + public virtual bool IsBag(MemberInfo role, System.Type _) + { + return Bags.Contains(role); + } + + public virtual bool IsIdBag(MemberInfo role, System.Type _) { return IdBags.Contains(role); } - public virtual bool IsList(MemberInfo role) + public virtual bool IsList(MemberInfo role, System.Type _) { return Lists.Contains(role); } @@ -131,17 +171,27 @@ public virtual bool IsArray(MemberInfo role) return Arrays.Contains(role); } + public virtual bool IsArray(MemberInfo role, System.Type _) + { + return Arrays.Contains(role); + } + public virtual bool IsDictionary(MemberInfo role) { return Dictionaries.Contains(role); } - public virtual bool IsProperty(MemberInfo member) + public virtual bool IsDictionary(MemberInfo role, System.Type _) + { + return Dictionaries.Contains(role); + } + + public virtual bool IsProperty(MemberInfo member, System.Type _) { return Properties.Contains(member); } - public virtual bool IsDynamicComponent(MemberInfo member) + public virtual bool IsDynamicComponent(MemberInfo member, System.Type _) { return DynamicComponents.Contains(member); } @@ -153,4 +203,4 @@ public virtual IEnumerable GetPropertiesSplits(System.Type type) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/ForClass.cs b/src/NHibernate/Mapping/ByCode/ForClass.cs index bcfc3aa296f..ed8c8d36e14 100644 --- a/src/NHibernate/Mapping/ByCode/ForClass.cs +++ b/src/NHibernate/Mapping/ByCode/ForClass.cs @@ -23,8 +23,8 @@ private static FieldInfo GetField(System.Type type, string fieldName) { return null; } - FieldInfo member = type.GetField(fieldName, DefaultFlags) ?? GetField(type.BaseType, fieldName); + FieldInfo member = type.GetField(fieldName, DefaultFlags) ?? GetField(type.GetTypeInfo().BaseType, fieldName); return member; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/IModelInspector.cs b/src/NHibernate/Mapping/ByCode/IModelInspector.cs index a831e44d76a..9f5a2b44146 100644 --- a/src/NHibernate/Mapping/ByCode/IModelInspector.cs +++ b/src/NHibernate/Mapping/ByCode/IModelInspector.cs @@ -14,31 +14,41 @@ public interface IModelInspector bool IsTablePerClassHierarchy(System.Type type); bool IsTablePerConcreteClass(System.Type type); - bool IsOneToOne(MemberInfo member); + bool IsOneToOne(MemberInfo member, System.Type componentType); bool IsManyToOne(MemberInfo member); - bool IsManyToManyItem(MemberInfo member); - bool IsManyToManyKey(MemberInfo member); + bool IsManyToOne(MemberInfo member, System.Type componentType); + bool IsManyToManyItem(MemberInfo member, System.Type componentType); + bool IsManyToManyKey(MemberInfo member, System.Type componentType); bool IsOneToMany(MemberInfo member); - bool IsManyToAny(MemberInfo member); + bool IsOneToMany(MemberInfo member, System.Type componentType); + bool IsManyToAny(MemberInfo member, System.Type componentType); - bool IsAny(MemberInfo member); + bool IsAny(MemberInfo member, System.Type componentType); bool IsPersistentId(MemberInfo member); + bool IsPersistentId(MemberInfo member, System.Type componentType); bool IsMemberOfComposedId(MemberInfo member); bool IsVersion(MemberInfo member); + bool IsVersion(MemberInfo member, System.Type componentType); bool IsMemberOfNaturalId(MemberInfo member); + bool IsMemberOfNaturalId(MemberInfo member, System.Type componentType); bool IsPersistentProperty(MemberInfo member); + bool IsPersistentProperty(MemberInfo member, System.Type componentType); bool IsSet(MemberInfo role); + bool IsSet(MemberInfo role, System.Type componentType); bool IsBag(MemberInfo role); - bool IsIdBag(MemberInfo role); - bool IsList(MemberInfo role); + bool IsBag(MemberInfo role, System.Type componentType); + bool IsIdBag(MemberInfo role, System.Type componentType); + bool IsList(MemberInfo role, System.Type componentType); bool IsArray(MemberInfo role); + bool IsArray(MemberInfo role, System.Type componentType); bool IsDictionary(MemberInfo role); - bool IsProperty(MemberInfo member); - bool IsDynamicComponent(MemberInfo member); + bool IsDictionary(MemberInfo role, System.Type componentType); + bool IsProperty(MemberInfo member, System.Type componentType); + bool IsDynamicComponent(MemberInfo member, System.Type componentType); System.Type GetDynamicComponentTemplate(MemberInfo member); IEnumerable GetPropertiesSplits(System.Type type); } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/AccessorPropertyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/AccessorPropertyMapper.cs index f264dcbf55e..3d29e354813 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/AccessorPropertyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/AccessorPropertyMapper.cs @@ -132,8 +132,8 @@ private static MemberInfo GetField(System.Type type, string fieldName) { return null; } - MemberInfo member = type.GetField(fieldName, FieldBindingFlag) ?? GetField(type.BaseType, fieldName); + MemberInfo member = type.GetField(fieldName, FieldBindingFlag) ?? GetField(type.GetTypeInfo().BaseType, fieldName); return member; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ClassMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ClassMapper.cs index 554420f46a3..bc7418c6846 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ClassMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ClassMapper.cs @@ -4,6 +4,7 @@ using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Persister.Entity; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode.Impl { @@ -26,7 +27,7 @@ public ClassMapper(System.Type rootClass, HbmMapping mapDoc, MemberInfo idProper classMapping = new HbmClass(); var toAdd = new[] {classMapping}; classMapping.name = rootClass.GetShortClassName(mapDoc); - if (rootClass.IsAbstract) + if (rootClass.GetTypeInfo().IsAbstract) { classMapping.@abstract = true; classMapping.abstractSpecified = true; @@ -335,8 +336,10 @@ public void Synchronize(params string[] table) return; } var existingSyncs = new HashSet(classMapping.synchronize != null ? classMapping.synchronize.Select(x => x.table) : Enumerable.Empty()); - System.Array.ForEach(table.Where(x => x != null).Select(tableName => tableName.Trim()).Where(cleanedName => !"".Equals(cleanedName)).ToArray(), - x => existingSyncs.Add(x.Trim())); + table.Where(x => x != null) + .Select(tableName => tableName.Trim()) + .Where(cleanedName => !"".Equals(cleanedName)) + .ForEach(x => existingSyncs.Add(x.Trim())); classMapping.synchronize = existingSyncs.Select(x => new HbmSynchronize {table = x}).ToArray(); } @@ -391,4 +394,4 @@ public void Subselect(string sql) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/CollectionIdMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/CollectionIdMapper.cs index 1189d33380f..69db1633d44 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/CollectionIdMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/CollectionIdMapper.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; @@ -93,4 +94,4 @@ private void AutosetTypeThroughGeneratorDef(IGeneratorDef generator) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ColumnMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ColumnMapper.cs index 6555618025c..c8e40eedb91 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ColumnMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ColumnMapper.cs @@ -1,5 +1,5 @@ using System; -using System.Runtime.Serialization; +using System.Globalization; using NHibernate.Cfg.MappingSchema; namespace NHibernate.Mapping.ByCode.Impl @@ -29,7 +29,7 @@ public ColumnMapper(HbmColumn mapping, string memberName) } } - #region Implementation of IColumnMapper +#region Implementation of IColumnMapper public void Name(string name) { @@ -95,10 +95,9 @@ public void Check(string checkConstraint) public void Default(object defaultValue) { - var formatterConverter = new FormatterConverter(); - mapping.@default = defaultValue == null ? "null" : formatterConverter.ToString(defaultValue); + mapping.@default = defaultValue == null ? "null" : Convert.ToString(defaultValue, CultureInfo.InvariantCulture); } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ClassCustomizer.cs b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ClassCustomizer.cs index 1364bba265e..9b18dd93025 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ClassCustomizer.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ClassCustomizer.cs @@ -92,7 +92,7 @@ private void RegisterComponentAsIdMapping(Action(ExplicitDeclarationsHolder, CustomizersHolder, propertyPath)); } } @@ -291,4 +291,4 @@ IModelExplicitDeclarationsHolder IConformistHoldersProvider.ExplicitDeclarations get { return ExplicitDeclarationsHolder; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ComponentElementCustomizer.cs b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ComponentElementCustomizer.cs index d0ec9d0480a..fa7504dd731 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ComponentElementCustomizer.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/ComponentElementCustomizer.cs @@ -71,9 +71,9 @@ public void Class() where TConcrete : TComponent public void Property(Expression> property, Action mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); - _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, member), mapping); + _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, member, typeof(TComponent)), mapping); MemberInfo memberOf = TypeExtensions.DecodeMemberAccessExpressionOf(property); - _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, memberOf), mapping); + _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, memberOf, typeof(TComponent)), mapping); _explicitDeclarationsHolder.AddAsProperty(member); _explicitDeclarationsHolder.AddAsProperty(memberOf); } @@ -87,17 +87,17 @@ public void Component(Expression(_explicitDeclarationsHolder, new PropertyPath(_propertyPath, member), _customizersHolder)); + mapping(new ComponentElementCustomizer(_explicitDeclarationsHolder, new PropertyPath(_propertyPath, member, typeof(TComponent)), _customizersHolder)); MemberInfo memberOf = TypeExtensions.DecodeMemberAccessExpressionOf(property); - mapping(new ComponentElementCustomizer(_explicitDeclarationsHolder, new PropertyPath(_propertyPath, memberOf), _customizersHolder)); + mapping(new ComponentElementCustomizer(_explicitDeclarationsHolder, new PropertyPath(_propertyPath, memberOf, typeof(TComponent)), _customizersHolder)); } public void ManyToOne(Expression> property, Action mapping) where TProperty : class { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); - _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, member), mapping); + _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, member, typeof(TComponent)), mapping); MemberInfo memberOf = TypeExtensions.DecodeMemberAccessExpressionOf(property); - _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, memberOf), mapping); + _customizersHolder.AddCustomizer(new PropertyPath(_propertyPath, memberOf, typeof(TComponent)), mapping); _explicitDeclarationsHolder.AddAsManyToOneRelation(member); _explicitDeclarationsHolder.AddAsManyToOneRelation(memberOf); } @@ -124,4 +124,4 @@ public void OptimisticLock(bool takeInConsiderationForOptimisticLock) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/MapKeyComponentCustomizer.cs b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/MapKeyComponentCustomizer.cs index 16474ed3999..c87dc8962a1 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/MapKeyComponentCustomizer.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/MapKeyComponentCustomizer.cs @@ -20,7 +20,7 @@ public MapKeyComponentCustomizer(IModelExplicitDeclarationsHolder explicitDeclar public void Property(Expression> property, Action mapping) { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); - customizersHolder.AddCustomizer(new PropertyPath(propertyPath, member), mapping); + customizersHolder.AddCustomizer(new PropertyPath(propertyPath, member, typeof(TKey)), mapping); } public void Property(Expression> property) @@ -31,9 +31,9 @@ public void Property(Expression> property) public void ManyToOne(Expression> property, Action mapping) where TProperty : class { MemberInfo member = TypeExtensions.DecodeMemberAccessExpression(property); - customizersHolder.AddCustomizer(new PropertyPath(propertyPath, member), mapping); + customizersHolder.AddCustomizer(new PropertyPath(propertyPath, member, typeof(TKey)), mapping); } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/PropertyContainerCustomizer.cs b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/PropertyContainerCustomizer.cs index b3119f6244a..f9f15f162fd 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/PropertyContainerCustomizer.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/CustomizersImpl/PropertyContainerCustomizer.cs @@ -63,7 +63,7 @@ protected void RegistePropertyMapping(Action mapping, params Me { foreach (var member in members) { - CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member), mapping); + CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member, typeof(TEntity)), mapping); explicitDeclarationsHolder.AddAsProperty(member); } } @@ -89,7 +89,8 @@ protected void RegisterComponentMapping(Action(explicitDeclarationsHolder, CustomizersHolder, new PropertyPath(PropertyPath, member))); + var componentType = member.DeclaringType;//typeof(TEntity); // + mapping(new ComponentCustomizer(explicitDeclarationsHolder, CustomizersHolder, new PropertyPath(PropertyPath, member, componentType))); } } @@ -109,7 +110,7 @@ protected void RegisterDynamicComponentMapping(Action(explicitDeclarationsHolder, CustomizersHolder, new PropertyPath(PropertyPath, member))); + mapping(new DynamicComponentCustomizer(explicitDeclarationsHolder, CustomizersHolder, new PropertyPath(PropertyPath, member, typeof(TEntity)))); } } @@ -132,7 +133,7 @@ protected void RegisterManyToOneMapping(Action mapp { foreach (var member in members) { - CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member), mapping); + CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member, typeof(TEntity)), mapping); explicitDeclarationsHolder.AddAsManyToOneRelation(member); } } @@ -168,7 +169,7 @@ protected void RegisterOneToOneMapping(Action mapping((IOneToOneMapper) x)); + CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member, typeof(TEntity)), (IOneToOneMapper x) => mapping((IOneToOneMapper) x)); explicitDeclarationsHolder.AddAsOneToOneRelation(member); } } @@ -192,8 +193,8 @@ protected void RegisterAnyMapping(Action mapping, System. { foreach (var member in members) { - CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member), (IAnyMapper am) => am.IdType(idTypeOfMetaType)); - CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member), mapping); + CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member, typeof(TEntity)), (IAnyMapper am) => am.IdType(idTypeOfMetaType)); + CustomizersHolder.AddCustomizer(new PropertyPath(PropertyPath, member, typeof(TEntity)), mapping); explicitDeclarationsHolder.AddAsAny(member); } @@ -222,8 +223,8 @@ protected void RegisterSetMapping(Action(explicitDeclarationsHolder, new PropertyPath(null, member), CustomizersHolder)); - mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member), CustomizersHolder)); + collectionMapping(new SetPropertiesCustomizer(explicitDeclarationsHolder, new PropertyPath(null, member, typeof(TEntity)), CustomizersHolder)); + mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member, typeof(TEntity)), CustomizersHolder)); } } @@ -249,8 +250,8 @@ protected void RegisterBagMapping(Action(explicitDeclarationsHolder, new PropertyPath(null, member), CustomizersHolder)); - mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member), CustomizersHolder)); + collectionMapping(new BagPropertiesCustomizer(explicitDeclarationsHolder, new PropertyPath(null, member, typeof(TEntity)), CustomizersHolder)); + mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member, typeof(TEntity)), CustomizersHolder)); } } @@ -276,8 +277,8 @@ protected void RegisterListMapping(Action(explicitDeclarationsHolder, new PropertyPath(null, member), CustomizersHolder)); - mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member), CustomizersHolder)); + collectionMapping(new ListPropertiesCustomizer(explicitDeclarationsHolder, new PropertyPath(null, member, typeof(TEntity)), CustomizersHolder)); + mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member, typeof(TEntity)), CustomizersHolder)); } } @@ -305,7 +306,7 @@ protected virtual void RegisterMapMapping(Action(explicitDeclarationsHolder, memberPath, CustomizersHolder)); keyMapping(new MapKeyRelationCustomizer(explicitDeclarationsHolder, memberPath, CustomizersHolder)); mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, memberPath, CustomizersHolder)); @@ -342,8 +343,8 @@ protected virtual void RegisterIdBagMapping(Action(explicitDeclarationsHolder, new PropertyPath(null, member), CustomizersHolder)); - mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member), CustomizersHolder)); + collectionMapping(new IdBagPropertiesCustomizer(explicitDeclarationsHolder, new PropertyPath(null, member, typeof(TEntity)), CustomizersHolder)); + mapping(new CollectionElementRelationCustomizer(explicitDeclarationsHolder, new PropertyPath(PropertyPath, member, typeof(TEntity)), CustomizersHolder)); } } @@ -505,4 +506,4 @@ public static MemberInfo GetPropertyOrFieldMatchingNameOrThrow(string memberName return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/DefaultCandidatePersistentMembersProvider.cs b/src/NHibernate/Mapping/ByCode/Impl/DefaultCandidatePersistentMembersProvider.cs index 1e4118de76a..f2526bebc79 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/DefaultCandidatePersistentMembersProvider.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/DefaultCandidatePersistentMembersProvider.cs @@ -29,7 +29,7 @@ public IEnumerable GetSubEntityMembers(System.Type entityClass, Syst const BindingFlags flattenHierarchyBindingFlag = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; - if (!entitySuperclass.Equals(entityClass.BaseType)) + if (!entitySuperclass.Equals(entityClass.GetTypeInfo().BaseType)) { IEnumerable propertiesOfSubclass = GetCandidatePersistentProperties(entityClass, flattenHierarchyBindingFlag); IEnumerable propertiesOfBaseClass = GetCandidatePersistentProperties(entitySuperclass, flattenHierarchyBindingFlag); @@ -63,13 +63,13 @@ private IEnumerable GetFieldsOfHierarchy(System.Type type) { yield return fieldInfo; } - analizing = analizing.BaseType; + analizing = analizing.GetTypeInfo().BaseType; } } private IEnumerable GetCandidatePersistentProperties(System.Type type, BindingFlags propertiesBindingFlags) { - return type.IsInterface ? type.GetInterfaceProperties() : type.GetProperties(propertiesBindingFlags); + return type.GetTypeInfo().IsInterface ? type.GetInterfaceProperties() : type.GetProperties(propertiesBindingFlags); } #region Nested type: PropertyNameEqualityComparer @@ -93,4 +93,4 @@ public int GetHashCode(MemberInfo obj) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/DiscriminatorMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/DiscriminatorMapper.cs index 0832761d105..24e8fdda340 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/DiscriminatorMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/DiscriminatorMapper.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; using NHibernate.Util; @@ -142,4 +143,4 @@ private void ResetColumnPlainValues() discriminatorMapping.formula = null; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ElementMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ElementMapper.cs index d6afcfbf4ce..0572f1440f4 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ElementMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ElementMapper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; using NHibernate.UserTypes; @@ -206,4 +207,4 @@ public void Formula(string formula) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/GeneratorMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/GeneratorMapper.cs index 16c48bc5831..669ba1a828d 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/GeneratorMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/GeneratorMapper.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; namespace NHibernate.Mapping.ByCode.Impl @@ -42,4 +43,4 @@ public void Params(IDictionary generatorParameters) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/JoinedSubclassMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/JoinedSubclassMapper.cs index e096329a30a..d606b5b0d96 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/JoinedSubclassMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/JoinedSubclassMapper.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Persister.Entity; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode.Impl { @@ -15,10 +17,10 @@ public JoinedSubclassMapper(System.Type subClass, HbmMapping mapDoc) : base(subC { var toAdd = new[] {classMapping}; classMapping.name = subClass.GetShortClassName(mapDoc); - classMapping.extends = subClass.BaseType.GetShortClassName(mapDoc); + classMapping.extends = subClass.GetTypeInfo().BaseType.GetShortClassName(mapDoc); if (classMapping.key == null) { - classMapping.key = new HbmKey {column1 = subClass.BaseType.Name.ToLowerInvariant() + "_key"}; + classMapping.key = new HbmKey {column1 = subClass.GetTypeInfo().BaseType.Name.ToLowerInvariant() + "_key"}; } keyMapper = new KeyMapper(subClass, classMapping.key); mapDoc.Items = mapDoc.Items == null ? toAdd : mapDoc.Items.Concat(toAdd).ToArray(); @@ -92,8 +94,10 @@ public void Synchronize(params string[] table) return; } var existingSyncs = new HashSet(classMapping.synchronize != null ? classMapping.synchronize.Select(x => x.table) : Enumerable.Empty()); - System.Array.ForEach(table.Where(x => x != null).Select(tableName => tableName.Trim()).Where(cleanedName => !"".Equals(cleanedName)).ToArray(), - x => existingSyncs.Add(x.Trim())); + table.Where(x => x != null) + .Select(tableName => tableName.Trim()) + .Where(cleanedName => !"".Equals(cleanedName)) + .ForEach(x => existingSyncs.Add(x.Trim())); classMapping.synchronize = existingSyncs.Select(x => new HbmSynchronize { table = x }).ToArray(); } @@ -209,4 +213,4 @@ public void Filter(string filterName, Action filterMapping) } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/KeyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/KeyMapper.cs index d312b6f6489..f1633c23345 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/KeyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/KeyMapper.cs @@ -96,7 +96,7 @@ public void PropertyRef(MemberInfo property) mapping.propertyref = null; return; } - if (!ownerEntityType.Equals(property.DeclaringType) && !ownerEntityType.Equals(property.ReflectedType)) + if (!property.DeclaringType.IsAssignableFrom(ownerEntityType)) { throw new ArgumentOutOfRangeException("property", "Can't reference a property of another entity."); } @@ -150,4 +150,4 @@ private void ResetColumnPlainValues() #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs index 486c502f057..d151d2d70a6 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; @@ -153,4 +154,4 @@ private void CheckIdTypeImmutability(string nhTypeName) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ManyToManyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ManyToManyMapper.cs index 8e5aff104bf..3ef36e92a2e 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ManyToManyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ManyToManyMapper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Util; @@ -173,4 +174,4 @@ public void Where(string sqlWhereClause) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/MapKeyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/MapKeyMapper.cs index f0c3a62ee58..96d3c8d2a46 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/MapKeyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/MapKeyMapper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; using NHibernate.UserTypes; @@ -140,4 +141,4 @@ private bool ColumnTagIsRequired(HbmColumn hbm) || hbm.check != null; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/MapMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/MapMapper.cs index e5bd28f1f6d..16265be03c1 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/MapMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/MapMapper.cs @@ -48,7 +48,7 @@ public MapMapper(System.Type ownerType, System.Type keyType, System.Type valueTy } keyMapper = new KeyMapper(ownerType, mapping.Key); - if (KeyType.IsValueType || KeyType == typeof (string)) + if (KeyType.GetTypeInfo().IsValueType || KeyType == typeof (string)) { mapping.Item = new HbmMapKey {type = KeyType.GetNhTypeName()}; } @@ -302,4 +302,4 @@ public void Subselect(string sql) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/OneToManyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/OneToManyMapper.cs index d9a95ba9aad..431fabbb393 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/OneToManyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/OneToManyMapper.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using NHibernate.Cfg.MappingSchema; namespace NHibernate.Mapping.ByCode.Impl @@ -53,4 +54,4 @@ public void NotFound(NotFoundMode mode) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/SubclassMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/SubclassMapper.cs index 81d01caaaf0..36a0c708865 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/SubclassMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/SubclassMapper.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Persister.Entity; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode.Impl { @@ -15,7 +17,7 @@ public SubclassMapper(System.Type subClass, HbmMapping mapDoc) : base(subClass, { var toAdd = new[] {classMapping}; classMapping.name = subClass.GetShortClassName(mapDoc); - classMapping.extends = subClass.BaseType.GetShortClassName(mapDoc); + classMapping.extends = subClass.GetTypeInfo().BaseType.GetShortClassName(mapDoc); mapDoc.Items = mapDoc.Items == null ? toAdd : mapDoc.Items.Concat(toAdd).ToArray(); } @@ -135,8 +137,10 @@ public void Synchronize(params string[] table) return; } var existingSyncs = new HashSet(classMapping.synchronize != null ? classMapping.synchronize.Select(x => x.table) : Enumerable.Empty()); - System.Array.ForEach(table.Where(x => x != null).Select(tableName => tableName.Trim()).Where(cleanedName => !"".Equals(cleanedName)).ToArray(), - x => existingSyncs.Add(x.Trim())); + table.Where(x => x != null) + .Select(tableName => tableName.Trim()) + .Where(cleanedName => !"".Equals(cleanedName)) + .ForEach(x => existingSyncs.Add(x.Trim())); classMapping.synchronize = existingSyncs.Select(x => new HbmSynchronize { table = x }).ToArray(); } @@ -197,4 +201,4 @@ public void Filter(string filterName, Action filterMapping) } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/TypeNameUtil.cs b/src/NHibernate/Mapping/ByCode/Impl/TypeNameUtil.cs index ecb05487972..4b32937015e 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/TypeNameUtil.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/TypeNameUtil.cs @@ -1,3 +1,4 @@ +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Type; @@ -15,7 +16,7 @@ public static string GetNhTypeName(this System.Type type) } else { - typeName = type.FullName + ", " + type.Assembly.GetName().Name; + typeName = type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name; } return typeName; } @@ -30,8 +31,8 @@ public static string GetShortClassName(this System.Type type, HbmMapping mapDoc) { return type.AssemblyQualifiedName; } - string typeAssembly = type.Assembly.GetName().Name; - string typeAssemblyFullName = type.Assembly.FullName; + string typeAssembly = type.GetTypeInfo().Assembly.GetName().Name; + string typeAssemblyFullName = type.GetTypeInfo().Assembly.FullName; string typeNameSpace = type.Namespace; string assembly = null; if (typeAssembly != mapDoc.assembly && typeAssemblyFullName != mapDoc.assembly) @@ -61,11 +62,11 @@ public static string GetShortClassName(this System.Type type, HbmMapping mapDoc) private static string GetTypeNameForMapping(System.Type type) { - if (type.IsGenericType || type.IsNested) + if (type.GetTypeInfo().IsGenericType || type.IsNested) { return type.FullName; } return type.Name; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/UnionSubclassMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/UnionSubclassMapper.cs index f4993bd26a0..01d6e16a2c9 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/UnionSubclassMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/UnionSubclassMapper.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using NHibernate.Cfg.MappingSchema; using NHibernate.Persister.Entity; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode.Impl { @@ -16,8 +18,8 @@ public UnionSubclassMapper(System.Type subClass, HbmMapping mapDoc) classMapping = new HbmUnionSubclass(); var toAdd = new[] {classMapping}; classMapping.name = subClass.GetShortClassName(mapDoc); - classMapping.extends = subClass.BaseType.GetShortClassName(mapDoc); - if (subClass.IsAbstract) + classMapping.extends = subClass.GetTypeInfo().BaseType.GetShortClassName(mapDoc); + if (subClass.GetTypeInfo().IsAbstract) { classMapping.@abstract = true; classMapping.abstractSpecified = true; @@ -93,8 +95,10 @@ public void Synchronize(params string[] table) return; } var existingSyncs = new HashSet(classMapping.synchronize != null ? classMapping.synchronize.Select(x => x.table) : Enumerable.Empty()); - System.Array.ForEach(table.Where(x => x != null).Select(tableName => tableName.Trim()).Where(cleanedName => !"".Equals(cleanedName)).ToArray(), - x => existingSyncs.Add(x.Trim())); + table.Where(x => x != null) + .Select(tableName => tableName.Trim()) + .Where(cleanedName => !"".Equals(cleanedName)) + .ForEach(x => existingSyncs.Add(x.Trim())); classMapping.synchronize = existingSyncs.Select(x => new HbmSynchronize { table = x }).ToArray(); } @@ -187,4 +191,4 @@ public void Extends(System.Type baseType) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/MappingsExtensions.cs b/src/NHibernate/Mapping/ByCode/MappingsExtensions.cs index 969623c1612..0d746b1ef25 100644 --- a/src/NHibernate/Mapping/ByCode/MappingsExtensions.cs +++ b/src/NHibernate/Mapping/ByCode/MappingsExtensions.cs @@ -5,6 +5,7 @@ using System.Xml; using System.Xml.Serialization; using NHibernate.Cfg.MappingSchema; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode { @@ -39,8 +40,13 @@ public static string AsString(this HbmMapping mappings) private static string ArrangeMappingsFolderPath() { +#if FEATURE_APPDOMAIN string baseDir = AppDomain.CurrentDomain.BaseDirectory; string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath; +#else + string baseDir = AppContext.BaseDirectory; + string relativeSearchPath = null; +#endif string binPath = relativeSearchPath != null ? Path.Combine(baseDir, relativeSearchPath): baseDir; string mappingsFolderPath = Path.Combine(binPath, "Mappings"); @@ -50,7 +56,7 @@ private static string ArrangeMappingsFolderPath() } else { - System.Array.ForEach(Directory.GetFiles(mappingsFolderPath), File.Delete); + Directory.GetFiles(mappingsFolderPath).ForEach(File.Delete); } return mappingsFolderPath; } @@ -101,4 +107,4 @@ private static string Serialize(HbmMapping hbmElement) return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/ModelExplicitDeclarationsHolderExtensions.cs b/src/NHibernate/Mapping/ByCode/ModelExplicitDeclarationsHolderExtensions.cs index e952ce848c8..478ce0d4fa5 100644 --- a/src/NHibernate/Mapping/ByCode/ModelExplicitDeclarationsHolderExtensions.cs +++ b/src/NHibernate/Mapping/ByCode/ModelExplicitDeclarationsHolderExtensions.cs @@ -1,4 +1,5 @@ using System.Linq; +using NHibernate.Util; namespace NHibernate.Mapping.ByCode { @@ -11,34 +12,34 @@ public static void Merge(this IModelExplicitDeclarationsHolder destination, IMod return; } - System.Array.ForEach(source.RootEntities.ToArray(), destination.AddAsRootEntity); - System.Array.ForEach(source.Components.ToArray(), destination.AddAsComponent); - System.Array.ForEach(source.TablePerClassEntities.ToArray(), destination.AddAsTablePerClassEntity); - System.Array.ForEach(source.TablePerClassHierarchyEntities.ToArray(), destination.AddAsTablePerClassHierarchyEntity); - System.Array.ForEach(source.TablePerConcreteClassEntities.ToArray(), destination.AddAsTablePerConcreteClassEntity); + source.RootEntities.ForEach(destination.AddAsRootEntity); + source.Components.ForEach(destination.AddAsComponent); + source.TablePerClassEntities.ForEach(destination.AddAsTablePerClassEntity); + source.TablePerClassHierarchyEntities.ForEach(destination.AddAsTablePerClassHierarchyEntity); + source.TablePerConcreteClassEntities.ForEach(destination.AddAsTablePerConcreteClassEntity); - System.Array.ForEach(source.OneToOneRelations.ToArray(), destination.AddAsOneToOneRelation); - System.Array.ForEach(source.ManyToOneRelations.ToArray(), destination.AddAsManyToOneRelation); - System.Array.ForEach(source.KeyManyToManyRelations.ToArray(), destination.AddAsManyToManyKeyRelation); - System.Array.ForEach(source.ItemManyToManyRelations.ToArray(), destination.AddAsManyToManyItemRelation); - System.Array.ForEach(source.ManyToAnyRelations.ToArray(), destination.AddAsManyToAnyRelation); - System.Array.ForEach(source.OneToManyRelations.ToArray(), destination.AddAsOneToManyRelation); - System.Array.ForEach(source.Any.ToArray(), destination.AddAsAny); + source.OneToOneRelations.ForEach(destination.AddAsOneToOneRelation); + source.ManyToOneRelations.ForEach(destination.AddAsManyToOneRelation); + source.KeyManyToManyRelations.ForEach(destination.AddAsManyToManyKeyRelation); + source.ItemManyToManyRelations.ForEach(destination.AddAsManyToManyItemRelation); + source.ManyToAnyRelations.ForEach(destination.AddAsManyToAnyRelation); + source.OneToManyRelations.ForEach(destination.AddAsOneToManyRelation); + source.Any.ForEach(destination.AddAsAny); - System.Array.ForEach(source.Poids.ToArray(), destination.AddAsPoid); - System.Array.ForEach(source.ComposedIds.ToArray(), destination.AddAsPartOfComposedId); - System.Array.ForEach(source.VersionProperties.ToArray(), destination.AddAsVersionProperty); - System.Array.ForEach(source.NaturalIds.ToArray(), destination.AddAsNaturalId); + source.Poids.ForEach(destination.AddAsPoid); + source.ComposedIds.ForEach(destination.AddAsPartOfComposedId); + source.VersionProperties.ForEach(destination.AddAsVersionProperty); + source.NaturalIds.ForEach(destination.AddAsNaturalId); - System.Array.ForEach(source.Sets.ToArray(), destination.AddAsSet); - System.Array.ForEach(source.Bags.ToArray(), destination.AddAsBag); - System.Array.ForEach(source.IdBags.ToArray(), destination.AddAsIdBag); - System.Array.ForEach(source.Lists.ToArray(), destination.AddAsList); - System.Array.ForEach(source.Arrays.ToArray(), destination.AddAsArray); - System.Array.ForEach(source.Dictionaries.ToArray(), destination.AddAsMap); - System.Array.ForEach(source.Properties.ToArray(), destination.AddAsProperty); - System.Array.ForEach(source.PersistentMembers.ToArray(), destination.AddAsPersistentMember); - System.Array.ForEach(source.SplitDefinitions.ToArray(), destination.AddAsPropertySplit); + source.Sets.ForEach(destination.AddAsSet); + source.Bags.ForEach(destination.AddAsBag); + source.IdBags.ForEach(destination.AddAsIdBag); + source.Lists.ForEach(destination.AddAsList); + source.Arrays.ForEach(destination.AddAsArray); + source.Dictionaries.ForEach(destination.AddAsMap); + source.Properties.ForEach(destination.AddAsProperty); + source.PersistentMembers.ForEach(destination.AddAsPersistentMember); + source.SplitDefinitions.ForEach(destination.AddAsPropertySplit); foreach (var dynamicComponent in source.DynamicComponents) { var template = source.GetDynamicComponentTemplate(dynamicComponent); @@ -46,4 +47,4 @@ public static void Merge(this IModelExplicitDeclarationsHolder destination, IMod } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/ModelMapper.cs b/src/NHibernate/Mapping/ByCode/ModelMapper.cs index 17f460188ed..e280a857902 100644 --- a/src/NHibernate/Mapping/ByCode/ModelMapper.cs +++ b/src/NHibernate/Mapping/ByCode/ModelMapper.cs @@ -556,10 +556,10 @@ public HbmMapping CompileMappingFor(IEnumerable types) string defaultAssemblyName = null; string defaultNamespace = null; System.Type firstType = typeToMap.FirstOrDefault(); - if (firstType != null && typeToMap.All(t => t.Assembly.Equals(firstType.Assembly))) + if (firstType != null && typeToMap.All(t => t.GetTypeInfo().Assembly.Equals(firstType.GetTypeInfo().Assembly))) { //NH-2831: always use the full name of the assembly because it may come from GAC - defaultAssemblyName = firstType.Assembly.GetName().FullName; + defaultAssemblyName = firstType.GetTypeInfo().Assembly.GetName().FullName; } if (firstType != null && typeToMap.All(t => t.Namespace == firstType.Namespace)) { @@ -590,13 +590,13 @@ public IEnumerable CompileMappingForEach(IEnumerable ty //NH-2831: always use the full name of the assembly because it may come from GAC foreach (var type in RootClasses(typeToMap)) { - var mapping = NewHbmMapping(type.Assembly.GetName().FullName, type.Namespace); + var mapping = NewHbmMapping(type.GetTypeInfo().Assembly.GetName().FullName, type.Namespace); MapRootClass(type, mapping); yield return mapping; } foreach (var type in Subclasses(typeToMap)) { - var mapping = NewHbmMapping(type.Assembly.GetName().FullName, type.Namespace); + var mapping = NewHbmMapping(type.GetTypeInfo().Assembly.GetName().FullName, type.Namespace); AddSubclassMapping(mapping, type); yield return mapping; } @@ -643,7 +643,7 @@ private void MapUnionSubclass(System.Type type, HbmMapping mapping) var classMapper = new UnionSubclassMapper(type, mapping); IEnumerable candidateProperties = null; - if (!modelInspector.IsEntity(type.BaseType)) + if (!modelInspector.IsEntity(type.GetTypeInfo().BaseType)) { System.Type baseType = GetEntityBaseType(type); if (baseType != null) @@ -652,9 +652,9 @@ private void MapUnionSubclass(System.Type type, HbmMapping mapping) candidateProperties = membersProvider.GetSubEntityMembers(type, baseType); } } - candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.BaseType); + candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.GetTypeInfo().BaseType); IEnumerable propertiesToMap = - candidateProperties.Where(p => modelInspector.IsPersistentProperty(p) && !modelInspector.IsPersistentId(p)); + candidateProperties.Where(p => modelInspector.IsPersistentProperty(p, type) && !modelInspector.IsPersistentId(p, type)); InvokeBeforeMapUnionSubclass(type, classMapper); customizerHolder.InvokeCustomizers(type, classMapper); @@ -667,7 +667,7 @@ private void MapSubclass(System.Type type, HbmMapping mapping) { var classMapper = new SubclassMapper(type, mapping); IEnumerable candidateProperties = null; - if (!modelInspector.IsEntity(type.BaseType)) + if (!modelInspector.IsEntity(type.GetTypeInfo().BaseType)) { System.Type baseType = GetEntityBaseType(type); if (baseType != null) @@ -676,7 +676,7 @@ private void MapSubclass(System.Type type, HbmMapping mapping) candidateProperties = membersProvider.GetSubEntityMembers(type, baseType); } } - candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.BaseType); + candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.GetTypeInfo().BaseType); InvokeBeforeMapSubclass(type, classMapper); customizerHolder.InvokeCustomizers(type, classMapper); @@ -686,7 +686,7 @@ private void MapSubclass(System.Type type, HbmMapping mapping) } var splitGroups = modelInspector.GetPropertiesSplits(type); - var propertiesToMap = candidateProperties.Where(p => modelInspector.IsPersistentProperty(p) && !modelInspector.IsPersistentId(p)); + var propertiesToMap = candidateProperties.Where(p => modelInspector.IsPersistentProperty(p, type) && !modelInspector.IsPersistentId(p, type)); var propertiesInSplits = new HashSet(); foreach (var splitGroup in splitGroups) { @@ -709,7 +709,7 @@ private void MapJoinedSubclass(System.Type type, HbmMapping mapping) { var classMapper = new JoinedSubclassMapper(type, mapping); IEnumerable candidateProperties = null; - if (!modelInspector.IsEntity(type.BaseType)) + if (!modelInspector.IsEntity(type.GetTypeInfo().BaseType)) { System.Type baseType = GetEntityBaseType(type); if (baseType != null) @@ -719,9 +719,9 @@ private void MapJoinedSubclass(System.Type type, HbmMapping mapping) candidateProperties = membersProvider.GetSubEntityMembers(type, baseType); } } - candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.BaseType); + candidateProperties = candidateProperties ?? membersProvider.GetSubEntityMembers(type, type.GetTypeInfo().BaseType); IEnumerable propertiesToMap = - candidateProperties.Where(p => modelInspector.IsPersistentProperty(p) && !modelInspector.IsPersistentId(p)); + candidateProperties.Where(p => modelInspector.IsPersistentProperty(p, type) && !modelInspector.IsPersistentId(p, type)); InvokeBeforeMapJoinedSubclass(type, classMapper); customizerHolder.InvokeCustomizers(type, classMapper); @@ -735,7 +735,7 @@ private System.Type GetEntityBaseType(System.Type type) System.Type analyzingType = type; while (analyzingType != null && analyzingType != typeof (object)) { - analyzingType = analyzingType.BaseType; + analyzingType = analyzingType.GetTypeInfo().BaseType; if (modelInspector.IsEntity(analyzingType)) { return analyzingType; @@ -746,7 +746,7 @@ private System.Type GetEntityBaseType(System.Type type) private void MapRootClass(System.Type type, HbmMapping mapping) { - MemberInfo poidPropertyOrField = membersProvider.GetEntityMembersForPoid(type).FirstOrDefault(mi => modelInspector.IsPersistentId(mi)); + MemberInfo poidPropertyOrField = membersProvider.GetEntityMembersForPoid(type).FirstOrDefault(mi => modelInspector.IsPersistentId(mi, type)); var classMapper = new ClassMapper(type, mapping, poidPropertyOrField); if (modelInspector.IsTablePerClassHierarchy(type)) { @@ -754,7 +754,7 @@ private void MapRootClass(System.Type type, HbmMapping mapping) } MemberInfo[] persistentProperties = membersProvider.GetRootEntityMembers(type).Where( - p => modelInspector.IsPersistentProperty(p) && !modelInspector.IsPersistentId(p)).ToArray(); + p => modelInspector.IsPersistentProperty(p, type) && !modelInspector.IsPersistentId(p, type)).ToArray(); InvokeBeforeMapClass(type, classMapper); InvokeClassCustomizers(type, classMapper); @@ -763,21 +763,21 @@ private void MapRootClass(System.Type type, HbmMapping mapping) { classMapper.ComponentAsId(poidPropertyOrField, compoAsId => { - var memberPath = new PropertyPath(null, poidPropertyOrField); + var memberPath = new PropertyPath(null, poidPropertyOrField, type); var componentMapper = new ComponentAsIdLikeComponentAttributesMapper(compoAsId); InvokeBeforeMapComponent(memberPath, componentMapper); System.Type componentType = poidPropertyOrField.GetPropertyOrFieldType(); IEnumerable componentPersistentProperties = - membersProvider.GetComponentMembers(componentType).Where(p => modelInspector.IsPersistentProperty(p)); + membersProvider.GetComponentMembers(componentType).Where(p => modelInspector.IsPersistentProperty(p, componentType)); customizerHolder.InvokeCustomizers(componentType, componentMapper); - ForEachMemberPath(poidPropertyOrField, memberPath, pp => customizerHolder.InvokeCustomizers(pp, compoAsId)); + ForEachMemberPath(memberPath, pp => customizerHolder.InvokeCustomizers(pp, compoAsId)); InvokeAfterMapComponent(memberPath, componentMapper); foreach (MemberInfo property in componentPersistentProperties) { - MapComposedIdProperties(compoAsId, new PropertyPath(memberPath, property)); + MapComposedIdProperties(compoAsId, new PropertyPath(memberPath, property, componentType)); } }); } @@ -789,12 +789,12 @@ private void MapRootClass(System.Type type, HbmMapping mapping) { foreach (MemberInfo property in composedIdPropeties) { - MapComposedIdProperties(composedIdMapper, new PropertyPath(null, property)); + MapComposedIdProperties(composedIdMapper, new PropertyPath(null, property, type)); } }); } - MemberInfo[] naturalIdPropeties = persistentProperties.Except(composedIdPropeties).Where(mi => modelInspector.IsMemberOfNaturalId(mi)).ToArray(); + MemberInfo[] naturalIdPropeties = persistentProperties.Except(composedIdPropeties).Where(mi => modelInspector.IsMemberOfNaturalId(mi, type)).ToArray(); if (naturalIdPropeties.Length > 0) { classMapper.NaturalId(naturalIdMapper => @@ -806,7 +806,7 @@ private void MapRootClass(System.Type type, HbmMapping mapping) }); } var splitGroups = modelInspector.GetPropertiesSplits(type); - var propertiesToMap = persistentProperties.Except(naturalIdPropeties).Except(composedIdPropeties).Where(mi => !modelInspector.IsVersion(mi) && !modelInspector.IsVersion(mi.GetMemberFromDeclaringType())).ToList(); + var propertiesToMap = persistentProperties.Except(naturalIdPropeties).Except(composedIdPropeties).Where(mi => !modelInspector.IsVersion(mi, type) && !modelInspector.IsVersion(mi.GetMemberFromDeclaringType(type), mi.DeclaringType)).ToList(); var propertiesInSplits = new HashSet(); foreach (var splitGroup in splitGroups) { @@ -830,54 +830,54 @@ private void MapSplitProperties(System.Type propertiesContainerType, IEnumerable { MemberInfo member = property; System.Type propertyType = property.GetPropertyOrFieldType(); - var memberPath = new PropertyPath(null, member); - if (modelInspector.IsProperty(member)) + var memberPath = new PropertyPath(null, member, propertiesContainerType); + if (modelInspector.IsProperty(member, propertiesContainerType)) { - MapProperty(member, memberPath, propertiesContainer); + MapProperty(memberPath, propertiesContainer); } - else if (modelInspector.IsAny(member)) + else if (modelInspector.IsAny(member, propertiesContainerType)) { - MapAny(member, memberPath, propertiesContainer); + MapAny(memberPath, propertiesContainer); } - else if (modelInspector.IsManyToOne(property)) + else if (modelInspector.IsManyToOne(property, propertiesContainerType)) { - MapManyToOne(member, memberPath, propertiesContainer); + MapManyToOne(memberPath, propertiesContainer); } - else if (modelInspector.IsSet(property)) + else if (modelInspector.IsSet(property, propertiesContainerType)) { - MapSet(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapSet(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsDictionary(property)) + else if (modelInspector.IsDictionary(property, propertiesContainerType)) { - MapDictionary(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapDictionary(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsArray(property)) + else if (modelInspector.IsArray(property, propertiesContainerType)) { throw new NotSupportedException(); } - else if (modelInspector.IsList(property)) + else if (modelInspector.IsList(property, propertiesContainerType)) { - MapList(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapList(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsIdBag(property)) + else if (modelInspector.IsIdBag(property, propertiesContainerType)) { - MapIdBag(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapIdBag(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsBag(property)) + else if (modelInspector.IsBag(property, propertiesContainerType)) { - MapBag(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapBag(memberPath, propertyType, propertiesContainer, propertiesContainerType); } else if (modelInspector.IsComponent(propertyType)) { - MapComponent(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapComponent(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsDynamicComponent(member)) + else if (modelInspector.IsDynamicComponent(member, propertiesContainerType)) { - MapDynamicComponent(member, memberPath, propertyType, propertiesContainer); + MapDynamicComponent(memberPath, propertyType, propertiesContainer); } else { - MapProperty(member, memberPath, propertiesContainer); + MapProperty(memberPath, propertiesContainer); } } } @@ -908,20 +908,21 @@ private void InvokeAncestorsCustomizers(IEnumerable typeAncestors, private void MapComposedIdProperties(IMinimalPlainPropertyContainerMapper composedIdMapper, PropertyPath propertyPath) { MemberInfo member = propertyPath.LocalMember; + System.Type componentType = propertyPath.ComponentType; System.Type propertyType = member.GetPropertyOrFieldType(); var memberPath = propertyPath; - if (modelInspector.IsProperty(member)) + if (modelInspector.IsProperty(member, componentType)) { - MapProperty(member, memberPath, composedIdMapper); + MapProperty(memberPath, composedIdMapper); } - else if (modelInspector.IsManyToOne(member)) + else if (modelInspector.IsManyToOne(member, componentType)) { - MapManyToOne(member, memberPath, composedIdMapper); + MapManyToOne(memberPath, composedIdMapper); } - else if (modelInspector.IsAny(member) || modelInspector.IsComponent(propertyType) || - modelInspector.IsOneToOne(member) || modelInspector.IsSet(member) - || modelInspector.IsDictionary(member) || modelInspector.IsArray(member) - || modelInspector.IsList(member) || modelInspector.IsBag(member)) + else if (modelInspector.IsAny(member, componentType) || modelInspector.IsComponent(propertyType) || + modelInspector.IsOneToOne(member, componentType) || modelInspector.IsSet(member, componentType) + || modelInspector.IsDictionary(member, componentType) || modelInspector.IsArray(member, componentType) + || modelInspector.IsList(member, componentType) || modelInspector.IsBag(member, componentType)) { throw new ArgumentOutOfRangeException("propertyPath", string.Format("The property {0} of {1} can't be part of composite-id.", @@ -929,7 +930,7 @@ private void MapComposedIdProperties(IMinimalPlainPropertyContainerMapper compos } else { - MapProperty(member, memberPath, composedIdMapper); + MapProperty(memberPath, composedIdMapper); } } @@ -937,26 +938,26 @@ private void MapNaturalIdProperties(System.Type rootEntityType, INaturalIdMapper { MemberInfo member = property; System.Type propertyType = property.GetPropertyOrFieldType(); - var memberPath = new PropertyPath(null, member); - if (modelInspector.IsProperty(member)) + var memberPath = new PropertyPath(null, member, rootEntityType); + if (modelInspector.IsProperty(member, rootEntityType)) { - MapProperty(member, memberPath, naturalIdMapper); + MapProperty(memberPath, naturalIdMapper); } - else if (modelInspector.IsAny(member)) + else if (modelInspector.IsAny(member, rootEntityType)) { - MapAny(member, memberPath, naturalIdMapper); + MapAny(memberPath, naturalIdMapper); } - else if (modelInspector.IsManyToOne(member)) + else if (modelInspector.IsManyToOne(member, rootEntityType)) { - MapManyToOne(member, memberPath, naturalIdMapper); + MapManyToOne(memberPath, naturalIdMapper); } else if (modelInspector.IsComponent(propertyType)) { - MapComponent(member, memberPath, propertyType, naturalIdMapper, rootEntityType); + MapComponent(memberPath, propertyType, naturalIdMapper, rootEntityType); } - else if (modelInspector.IsOneToOne(member) || modelInspector.IsSet(property) - || modelInspector.IsDictionary(property) || modelInspector.IsArray(property) - || modelInspector.IsList(property) || modelInspector.IsBag(property)) + else if (modelInspector.IsOneToOne(member, rootEntityType) || modelInspector.IsSet(property, rootEntityType) + || modelInspector.IsDictionary(property, rootEntityType) || modelInspector.IsArray(property, rootEntityType) + || modelInspector.IsList(property, rootEntityType) || modelInspector.IsBag(property, rootEntityType)) { throw new ArgumentOutOfRangeException("property", string.Format("The property {0} of {1} can't be part of natural-id.", @@ -964,121 +965,126 @@ private void MapNaturalIdProperties(System.Type rootEntityType, INaturalIdMapper } else { - MapProperty(member, memberPath, naturalIdMapper); + MapProperty(memberPath, naturalIdMapper); } } private void MapProperties(System.Type propertiesContainerType, IEnumerable propertiesToMap, IPropertyContainerMapper propertiesContainer) { - MapProperties(propertiesContainerType, propertiesToMap, propertiesContainer, null); + MapProperties(propertiesContainerType, propertiesToMap, propertiesContainer, null, null); } private void MapProperties(System.Type propertiesContainerType, IEnumerable propertiesToMap, - IPropertyContainerMapper propertiesContainer, PropertyPath path) + IPropertyContainerMapper propertiesContainer, PropertyPath path, System.Type componentType) { foreach (var property in propertiesToMap) { MemberInfo member = property; System.Type propertyType = property.GetPropertyOrFieldType(); - var memberPath = new PropertyPath(path, member); - if (modelInspector.IsProperty(member)) + componentType = componentType != null ? componentType : propertiesContainerType; + var memberPath = new PropertyPath(path, member, componentType); + if (modelInspector.IsProperty(member, componentType)) { - MapProperty(member, memberPath, propertiesContainer); + MapProperty(memberPath, propertiesContainer); } - else if (modelInspector.IsAny(member)) + else if (modelInspector.IsAny(member, componentType)) { - MapAny(member, memberPath, propertiesContainer); + MapAny(memberPath, propertiesContainer); } - else if (modelInspector.IsManyToOne(property)) + else if (modelInspector.IsManyToOne(property, componentType)) { - MapManyToOne(member, memberPath, propertiesContainer); + MapManyToOne(memberPath, propertiesContainer); } - else if (modelInspector.IsOneToOne(property)) + else if (modelInspector.IsOneToOne(property, componentType)) { - MapOneToOne(member, memberPath, propertiesContainer); + MapOneToOne(memberPath, propertiesContainer); } - else if (modelInspector.IsDynamicComponent(property)) + else if (modelInspector.IsDynamicComponent(property, componentType)) { - MapDynamicComponent(member, memberPath, propertyType, propertiesContainer); + MapDynamicComponent(memberPath, propertyType, propertiesContainer); } - else if (modelInspector.IsSet(property)) + else if (modelInspector.IsSet(property, componentType)) { - MapSet(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapSet(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsDictionary(property)) + else if (modelInspector.IsDictionary(property, componentType)) { - MapDictionary(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapDictionary(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsArray(property)) + else if (modelInspector.IsArray(property, componentType)) { throw new NotSupportedException(); } - else if (modelInspector.IsList(property)) + else if (modelInspector.IsList(property, componentType)) { - MapList(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapList(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsIdBag(property)) + else if (modelInspector.IsIdBag(property, componentType)) { - MapIdBag(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapIdBag(memberPath, propertyType, propertiesContainer, propertiesContainerType); } - else if (modelInspector.IsBag(property)) + else if (modelInspector.IsBag(property, componentType)) { - MapBag(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapBag(memberPath, propertyType, propertiesContainer, propertiesContainerType); } else if (modelInspector.IsComponent(propertyType)) { - MapComponent(member, memberPath, propertyType, propertiesContainer, propertiesContainerType); + MapComponent(memberPath, propertyType, propertiesContainer, propertiesContainerType); } else { - MapProperty(member, memberPath, propertiesContainer); + MapProperty(memberPath, propertiesContainer); } } } - private void MapDynamicComponent(MemberInfo member, PropertyPath memberPath, System.Type propertyType, IBasePlainPropertyContainerMapper propertiesContainer) + private void MapDynamicComponent(PropertyPath memberPath, System.Type propertyType, IBasePlainPropertyContainerMapper propertiesContainer) { + MemberInfo member = memberPath.LocalMember; propertiesContainer.Component(member, (IDynamicComponentMapper componentMapper) => { System.Type componentType = modelInspector.GetDynamicComponentTemplate(member); IEnumerable persistentProperties = membersProvider.GetComponentMembers(componentType); - ForEachMemberPath(member, memberPath, pp => customizerHolder.InvokeCustomizers(pp, componentMapper)); + ForEachMemberPath(memberPath, pp => customizerHolder.InvokeCustomizers(pp, componentMapper)); - MapProperties(propertyType, persistentProperties, componentMapper, memberPath); + MapProperties(propertyType, persistentProperties, componentMapper, memberPath, componentType); }); } - private void MapAny(MemberInfo member, PropertyPath memberPath, IBasePlainPropertyContainerMapper propertiesContainer) + private void MapAny(PropertyPath memberPath, IBasePlainPropertyContainerMapper propertiesContainer) { + MemberInfo member = memberPath.LocalMember; propertiesContainer.Any(member, typeof (int), anyMapper => { InvokeBeforeMapAny(memberPath, anyMapper); + var declaringType = memberPath.GetRootMember().DeclaringType; MemberInfo poidPropertyOrField = - membersProvider.GetEntityMembersForPoid(memberPath.GetRootMember().DeclaringType).FirstOrDefault( - mi => modelInspector.IsPersistentId(mi)); + membersProvider.GetEntityMembersForPoid(declaringType).FirstOrDefault( + mi => modelInspector.IsPersistentId(mi, declaringType)); if (poidPropertyOrField != null) { anyMapper.IdType(poidPropertyOrField.GetPropertyOrFieldType()); } - ForEachMemberPath(member, memberPath, pp => customizerHolder.InvokeCustomizers(pp, anyMapper)); + ForEachMemberPath(memberPath, pp => customizerHolder.InvokeCustomizers(pp, anyMapper)); InvokeAfterMapAny(memberPath, anyMapper); }); } - private void MapProperty(MemberInfo member, PropertyPath propertyPath, IMinimalPlainPropertyContainerMapper propertiesContainer) + private void MapProperty(PropertyPath propertyPath, IMinimalPlainPropertyContainerMapper propertiesContainer) { + MemberInfo member = propertyPath.LocalMember; propertiesContainer.Property(member, propertyMapper => { InvokeBeforeMapProperty(propertyPath, propertyMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, propertyMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, propertyMapper)); InvokeAfterMapProperty(propertyPath, propertyMapper); }); } - protected void ForEachMemberPath(MemberInfo member, PropertyPath progressivePath, Action invoke) + protected void ForEachMemberPath(PropertyPath progressivePath, Action invoke) { // This method will "fail" if the IModelInspector is based only on IModelExplicitDeclarationsHolder and will work // when IModelInspector has the capability to distinguish entities form explicit mappings @@ -1103,20 +1109,21 @@ protected void ForEachMemberPath(MemberInfo member, PropertyPath progressivePath // The full-progressive-path of the property is : X.Collection->C1.C2.C3.MyProp // I have to execute the customization at each possible level (a,b,c,d). + MemberInfo member = progressivePath.LocalMember; var invokedPaths = new HashSet(); // paths on interfaces (note: when a property is the implementation of more then one interface a specific order can't be applied...AFAIK) - IEnumerable propertiesOnInterfaces = member.GetPropertyFromInterfaces(); + IEnumerable propertiesOnInterfaces = member.GetPropertyFromInterfaces(progressivePath.ComponentType); foreach (MemberInfo propertyOnInterface in propertiesOnInterfaces) { - var propertyPathInterfaceLevel = new PropertyPath(null, propertyOnInterface); + var propertyPathInterfaceLevel = new PropertyPath(null, propertyOnInterface, propertyOnInterface.DeclaringType); invoke(propertyPathInterfaceLevel); } // path on declaring type - var propertyPathLevel0 = new PropertyPath(null, member.GetMemberFromDeclaringType()); + var propertyPathLevel0 = new PropertyPath(null, member.GetMemberFromDeclaringType(progressivePath.ComponentType), member.DeclaringType); // path on reflected type - var propertyPathLevel1 = new PropertyPath(null, member); + var propertyPathLevel1 = new PropertyPath(null, member, progressivePath.ComponentType); invoke(propertyPathLevel0); invokedPaths.Add(propertyPathLevel0); @@ -1137,109 +1144,115 @@ protected void ForEachMemberPath(MemberInfo member, PropertyPath progressivePath } } - private void MapComponent(MemberInfo member, PropertyPath memberPath, System.Type propertyType, IBasePlainPropertyContainerMapper propertiesContainer, + private void MapComponent(PropertyPath memberPath, System.Type propertyType, IBasePlainPropertyContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = memberPath.LocalMember; propertiesContainer.Component(member, componentMapper => { InvokeBeforeMapComponent(memberPath, componentMapper); // <<== perhaps is better after find the parent System.Type componentType = propertyType; IEnumerable persistentProperties = - membersProvider.GetComponentMembers(componentType).Where(p => modelInspector.IsPersistentProperty(p)); + membersProvider.GetComponentMembers(componentType).Where(p => modelInspector.IsPersistentProperty(p, componentType)); - MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, propertiesContainerType); + MemberInfo parentReferenceProperty = GetComponentParentReferenceProperty(persistentProperties, propertiesContainerType, componentType); if (parentReferenceProperty != null) { componentMapper.Parent(parentReferenceProperty); } customizerHolder.InvokeCustomizers(componentType, componentMapper); - ForEachMemberPath(member, memberPath, pp => customizerHolder.InvokeCustomizers(pp, componentMapper)); + ForEachMemberPath(memberPath, pp => customizerHolder.InvokeCustomizers(pp, componentMapper)); InvokeAfterMapComponent(memberPath, componentMapper); - MapProperties(propertyType, persistentProperties.Where(pi => pi != parentReferenceProperty), componentMapper, memberPath); + MapProperties(propertyType, persistentProperties.Where(pi => pi != parentReferenceProperty), componentMapper, memberPath, componentType); }); } - protected MemberInfo GetComponentParentReferenceProperty(IEnumerable persistentProperties, System.Type propertiesContainerType) + protected MemberInfo GetComponentParentReferenceProperty(IEnumerable persistentProperties, System.Type propertiesContainerType, System.Type componentPropertyType) { // if container is component, then all properties referencing container are assumed parent reference if (modelInspector.IsComponent(propertiesContainerType)) return persistentProperties.FirstOrDefault(pp => pp.GetPropertyOrFieldType() == propertiesContainerType); // return the first non-many-to-one property - return persistentProperties.Where(pp => !modelInspector.IsManyToOne(pp)).FirstOrDefault(pp => pp.GetPropertyOrFieldType() == propertiesContainerType); + return persistentProperties.Where(pp => !modelInspector.IsManyToOne(pp, componentPropertyType)).FirstOrDefault(pp => pp.GetPropertyOrFieldType() == propertiesContainerType); } - private void MapBag(MemberInfo member, PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, + private void MapBag(PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = propertyPath.LocalMember; System.Type collectionElementType = GetCollectionElementTypeOrThrow(propertiesContainerType, member, propertyType); - ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(member, propertyPath, collectionElementType); + ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(propertyPath, collectionElementType); propertiesContainer.Bag(member, collectionPropertiesMapper => { cert.MapCollectionProperties(collectionPropertiesMapper); InvokeBeforeMapBag(propertyPath, collectionPropertiesMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); InvokeAfterMapBag(propertyPath, collectionPropertiesMapper); }, cert.Map); } - private void MapList(MemberInfo member, PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, + private void MapList(PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = propertyPath.LocalMember; System.Type collectionElementType = GetCollectionElementTypeOrThrow(propertiesContainerType, member, propertyType); - ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(member, propertyPath, collectionElementType); + ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(propertyPath, collectionElementType); propertiesContainer.List(member, collectionPropertiesMapper => { cert.MapCollectionProperties(collectionPropertiesMapper); InvokeBeforeMapList(propertyPath, collectionPropertiesMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); InvokeAfterMapList(propertyPath, collectionPropertiesMapper); }, cert.Map); } - private void MapDictionary(MemberInfo member, PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, + private void MapDictionary(PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = propertyPath.LocalMember; System.Type dictionaryKeyType = propertyType.DetermineDictionaryKeyType(); if (dictionaryKeyType == null) { throw new NotSupportedException(string.Format("Can't determine collection element relation (property {0} in {1})", member.Name, propertiesContainerType)); } - IMapKeyRelationMapper mkrm = DetermineMapKeyRelationType(member, propertyPath, dictionaryKeyType); + IMapKeyRelationMapper mkrm = DetermineMapKeyRelationType(propertyPath, dictionaryKeyType); System.Type dictionaryValueType = propertyType.DetermineDictionaryValueType(); - ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(member, propertyPath, dictionaryValueType); + ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(propertyPath, dictionaryValueType); propertiesContainer.Map(member, collectionPropertiesMapper => { cert.MapCollectionProperties(collectionPropertiesMapper); InvokeBeforeMapMap(propertyPath, collectionPropertiesMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); InvokeAfterMapMap(propertyPath, collectionPropertiesMapper); }, mkrm.Map, cert.Map); } - private void MapSet(MemberInfo member, PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, + private void MapSet(PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = propertyPath.LocalMember; System.Type collectionElementType = GetCollectionElementTypeOrThrow(propertiesContainerType, member, propertyType); - ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(member, propertyPath, collectionElementType); + ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(propertyPath, collectionElementType); propertiesContainer.Set(member, collectionPropertiesMapper => { cert.MapCollectionProperties(collectionPropertiesMapper); InvokeBeforeMapSet(propertyPath, collectionPropertiesMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); InvokeAfterMapSet(propertyPath, collectionPropertiesMapper); }, cert.Map); } - private void MapIdBag(MemberInfo member, PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, + private void MapIdBag(PropertyPath propertyPath, System.Type propertyType, ICollectionPropertiesContainerMapper propertiesContainer, System.Type propertiesContainerType) { + MemberInfo member = propertyPath.LocalMember; System.Type collectionElementType = GetCollectionElementTypeOrThrow(propertiesContainerType, member, propertyType); - ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(member, propertyPath, collectionElementType); + ICollectionElementRelationMapper cert = DetermineCollectionElementRelationType(propertyPath, collectionElementType); if(cert is OneToManyRelationMapper) { throw new NotSupportedException("id-bag does not suppot one-to-many relation"); @@ -1248,27 +1261,29 @@ private void MapIdBag(MemberInfo member, PropertyPath propertyPath, System.Type { cert.MapCollectionProperties(collectionPropertiesMapper); InvokeBeforeMapIdBag(propertyPath, collectionPropertiesMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, collectionPropertiesMapper)); InvokeAfterMapIdBag(propertyPath, collectionPropertiesMapper); }, cert.Map); } - private void MapOneToOne(MemberInfo member, PropertyPath propertyPath, IPlainPropertyContainerMapper propertiesContainer) + private void MapOneToOne(PropertyPath propertyPath, IPlainPropertyContainerMapper propertiesContainer) { + MemberInfo member = propertyPath.LocalMember; propertiesContainer.OneToOne(member, oneToOneMapper => { InvokeBeforeMapOneToOne(propertyPath, oneToOneMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, oneToOneMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, oneToOneMapper)); InvokeAfterMapOneToOne(propertyPath, oneToOneMapper); }); } - private void MapManyToOne(MemberInfo member, PropertyPath propertyPath, IMinimalPlainPropertyContainerMapper propertiesContainer) + private void MapManyToOne(PropertyPath propertyPath, IMinimalPlainPropertyContainerMapper propertiesContainer) { + MemberInfo member = propertyPath.LocalMember; propertiesContainer.ManyToOne(member, manyToOneMapper => { InvokeBeforeMapManyToOne(propertyPath, manyToOneMapper); - ForEachMemberPath(member, propertyPath, pp => customizerHolder.InvokeCustomizers(pp, manyToOneMapper)); + ForEachMemberPath(propertyPath, pp => customizerHolder.InvokeCustomizers(pp, manyToOneMapper)); InvokeAfterMapManyToOne(propertyPath, manyToOneMapper); }); } @@ -1284,17 +1299,18 @@ private System.Type GetCollectionElementTypeOrThrow(System.Type type, MemberInfo return collectionElementType; } - protected virtual ICollectionElementRelationMapper DetermineCollectionElementRelationType(MemberInfo property, PropertyPath propertyPath, System.Type collectionElementType) + protected virtual ICollectionElementRelationMapper DetermineCollectionElementRelationType(PropertyPath propertyPath, System.Type collectionElementType) { - System.Type ownerType = property.ReflectedType; - if (modelInspector.IsOneToMany(property)) + MemberInfo property = propertyPath.LocalMember; + System.Type ownerType = propertyPath.ComponentType; + if (modelInspector.IsOneToMany(property, ownerType)) { return new OneToManyRelationMapper(propertyPath, ownerType, collectionElementType, modelInspector, customizerHolder, this); } //NH-3667 & NH-3102 && NH-3741 // many to many split from key many to many so that XML mappings and Interfaces work with many to many. // MapKeyManyToManyCustomizer now registers itself as KeyManyToMany, so will return false for IsManyToMany(property). - if (modelInspector.IsManyToManyItem(property)) + if (modelInspector.IsManyToManyItem(property, ownerType)) { return new ManyToManyRelationMapper(propertyPath, customizerHolder, this); } @@ -1302,16 +1318,18 @@ protected virtual ICollectionElementRelationMapper DetermineCollectionElementRel { return new ComponentRelationMapper(propertyPath, ownerType, collectionElementType, membersProvider, modelInspector, customizerHolder, this); } - if (modelInspector.IsManyToAny(property)) + if (modelInspector.IsManyToAny(property, ownerType)) { return new ManyToAnyRelationMapper(propertyPath, customizerHolder, this); } return new ElementRelationMapper(propertyPath, customizerHolder, this); } - private IMapKeyRelationMapper DetermineMapKeyRelationType(MemberInfo member, PropertyPath propertyPath, System.Type dictionaryKeyType) + private IMapKeyRelationMapper DetermineMapKeyRelationType(PropertyPath propertyPath, System.Type dictionaryKeyType) { - if (modelInspector.IsManyToManyKey(member)) + MemberInfo member = propertyPath.LocalMember; + System.Type ownerType = propertyPath.ComponentType; + if (modelInspector.IsManyToManyKey(member, ownerType)) { // OneToMany is not possible as map-key so we map it as many-to-many instead ignore the case return new KeyManyToManyRelationMapper(propertyPath, customizerHolder, this); @@ -1355,7 +1373,7 @@ public void Map(ICollectionElementRelation relation) { IEnumerable persistentProperties = GetPersistentProperties(componentType); - MemberInfo parentReferenceProperty = modelMapper.GetComponentParentReferenceProperty(persistentProperties, ownerType); + MemberInfo parentReferenceProperty = modelMapper.GetComponentParentReferenceProperty(persistentProperties, ownerType, componentType); if (parentReferenceProperty != null) { x.Parent(parentReferenceProperty); @@ -1373,7 +1391,7 @@ public void MapCollectionProperties(ICollectionPropertiesMapper mapped) {} private IEnumerable GetPersistentProperties(System.Type type) { IEnumerable properties = membersProvider.GetComponentMembers(type); - return properties.Where(p => domainInspector.IsPersistentProperty(p)); + return properties.Where(p => domainInspector.IsPersistentProperty(p, type)); } private void MapProperties(System.Type type, PropertyPath memberPath, IComponentElementMapper propertiesContainer, IEnumerable persistentProperties) @@ -1382,14 +1400,14 @@ private void MapProperties(System.Type type, PropertyPath memberPath, IComponent { MemberInfo member = property; System.Type propertyType = property.GetPropertyOrFieldType(); - var propertyPath = new PropertyPath(memberPath, member); + var propertyPath = new PropertyPath(memberPath, member, type); - if (domainInspector.IsManyToOne(member)) + if (domainInspector.IsManyToOne(member, type)) { propertiesContainer.ManyToOne(member, manyToOneMapper => { modelMapper.InvokeBeforeMapManyToOne(propertyPath, manyToOneMapper); - modelMapper.ForEachMemberPath(member, propertyPath, pp => customizersHolder.InvokeCustomizers(pp, manyToOneMapper)); + modelMapper.ForEachMemberPath(propertyPath, pp => customizersHolder.InvokeCustomizers(pp, manyToOneMapper)); modelMapper.InvokeAfterMapManyToOne(propertyPath, manyToOneMapper); }); } @@ -1405,13 +1423,13 @@ private void MapProperties(System.Type type, PropertyPath memberPath, IComponent IEnumerable componentProperties = GetPersistentProperties(componentPropertyType); - MemberInfo parentReferenceProperty = modelMapper.GetComponentParentReferenceProperty(componentProperties, componentOwnerType); + MemberInfo parentReferenceProperty = modelMapper.GetComponentParentReferenceProperty(componentProperties, componentOwnerType, componentPropertyType); if (parentReferenceProperty != null) { x.Parent(parentReferenceProperty); } customizersHolder.InvokeCustomizers(componentPropertyType, x); - modelMapper.ForEachMemberPath(member, propertyPath, pp => customizersHolder.InvokeCustomizers(pp, x)); + modelMapper.ForEachMemberPath(propertyPath, pp => customizersHolder.InvokeCustomizers(pp, x)); modelMapper.InvokeAfterMapComponent(propertyPath, x); MapProperties(componentPropertyType, propertyPath, x, componentProperties.Where(pi => pi != parentReferenceProperty)); @@ -1422,7 +1440,7 @@ private void MapProperties(System.Type type, PropertyPath memberPath, IComponent propertiesContainer.Property(member, propertyMapper => { modelMapper.InvokeBeforeMapProperty(propertyPath, propertyMapper); - modelMapper.ForEachMemberPath(member, propertyPath, pp => customizersHolder.InvokeCustomizers(pp, propertyMapper)); + modelMapper.ForEachMemberPath(propertyPath, pp => customizersHolder.InvokeCustomizers(pp, propertyMapper)); modelMapper.InvokeAfterMapProperty(propertyPath, propertyMapper); }); } @@ -1515,7 +1533,7 @@ public void Map(IMapKeyRelation relation) { IEnumerable persistentProperties = GetPersistentProperties(dictionaryKeyType); - MapProperties(x, persistentProperties); + MapProperties(x, persistentProperties, dictionaryKeyType); }); } @@ -1524,21 +1542,21 @@ public void Map(IMapKeyRelation relation) private IEnumerable GetPersistentProperties(System.Type type) { IEnumerable properties = membersProvider.GetComponentMembers(type); - return properties.Where(p => domainInspector.IsPersistentProperty(p)); + return properties.Where(p => domainInspector.IsPersistentProperty(p, type)); } - private void MapProperties(IComponentMapKeyMapper propertiesContainer, IEnumerable persistentProperties) + private void MapProperties(IComponentMapKeyMapper propertiesContainer, IEnumerable persistentProperties, System.Type componentType) { foreach (MemberInfo property in persistentProperties) { MemberInfo member = property; - if (domainInspector.IsManyToOne(member)) + if (domainInspector.IsManyToOne(member, componentType)) { propertiesContainer.ManyToOne(member, manyToOneMapper => { - var progressivePath = new PropertyPath(propertyPath, member); + var progressivePath = new PropertyPath(propertyPath, member, componentType); modelMapper.InvokeBeforeMapManyToOne(progressivePath, manyToOneMapper); - modelMapper.ForEachMemberPath(member, progressivePath, pp => customizersHolder.InvokeCustomizers(pp, manyToOneMapper)); + modelMapper.ForEachMemberPath(progressivePath, pp => customizersHolder.InvokeCustomizers(pp, manyToOneMapper)); modelMapper.InvokeAfterMapManyToOne(progressivePath, manyToOneMapper); }); } @@ -1546,9 +1564,9 @@ private void MapProperties(IComponentMapKeyMapper propertiesContainer, IEnumerab { propertiesContainer.Property(member, propertyMapper => { - var progressivePath = new PropertyPath(propertyPath, member); + var progressivePath = new PropertyPath(propertyPath, member, componentType); modelMapper.InvokeBeforeMapProperty(progressivePath, propertyMapper); - modelMapper.ForEachMemberPath(member, progressivePath, pp => customizersHolder.InvokeCustomizers(pp, propertyMapper)); + modelMapper.ForEachMemberPath(progressivePath, pp => customizersHolder.InvokeCustomizers(pp, propertyMapper)); modelMapper.InvokeAfterMapProperty(progressivePath, propertyMapper); }); } @@ -1732,7 +1750,7 @@ public void MapCollectionProperties(ICollectionPropertiesMapper mapped) private string GetParentColumnNameInChild() { MemberInfo propertyInfo = - collectionElementType.GetProperties(FlattenHierarchyBindingFlags).FirstOrDefault(p => p.PropertyType.IsAssignableFrom(ownerType) && domainInspector.IsPersistentProperty(p)); + collectionElementType.GetProperties(FlattenHierarchyBindingFlags).FirstOrDefault(p => p.PropertyType.IsAssignableFrom(ownerType) && domainInspector.IsPersistentProperty(p, collectionElementType)); if (propertyInfo != null) { @@ -1793,7 +1811,7 @@ public void AddMappings(IEnumerable types) { throw new ArgumentNullException("types"); } - foreach (var type in types.Where(x=> typeof(IConformistHoldersProvider).IsAssignableFrom(x) && !x.IsGenericTypeDefinition)) + foreach (var type in types.Where(x=> typeof(IConformistHoldersProvider).IsAssignableFrom(x) && !x.GetTypeInfo().IsGenericTypeDefinition)) { AddMapping(type); } diff --git a/src/NHibernate/Mapping/ByCode/PropertyPath.cs b/src/NHibernate/Mapping/ByCode/PropertyPath.cs index 0303d68c432..cf1835e7753 100644 --- a/src/NHibernate/Mapping/ByCode/PropertyPath.cs +++ b/src/NHibernate/Mapping/ByCode/PropertyPath.cs @@ -11,15 +11,43 @@ public class PropertyPath private readonly int hashCode; private readonly MemberInfo localMember; private readonly PropertyPath previousPath; + private readonly System.Type componentType; public PropertyPath(PropertyPath previousPath, MemberInfo localMember) +#if FEATURE_REFLECTEDTYPE + : this(previousPath, localMember, localMember.ReflectedType) +#else + : this(previousPath, localMember, localMember.DeclaringType) +#endif + { + //if (localMember.DeclaringType != localMember.ReflectedType) + //{ + // throw new InvalidOperationException(string.Format("DeclaringType {0} not the same as ReflectedType {1}", localMember.DeclaringType, localMember.ReflectedType)); + //} + } + + public PropertyPath(PropertyPath previousPath, MemberInfo localMember, System.Type componentType) { if (localMember == null) { throw new ArgumentNullException("localMember"); } + if (componentType == null) + { + throw new ArgumentNullException("componentType"); + } + if (!localMember.DeclaringType.IsAssignableFrom(componentType)) + { + throw new ArgumentException("source Member not implemented on passed in type", "componentType"); + } + //if (componentType != localMember.ReflectedType) + //{ + // throw new ArgumentException(string.Format("componentType {0} not the same as ReflectedType {1}", componentType, localMember.ReflectedType), "componentType"); + //} this.previousPath = previousPath; this.localMember = localMember; + this.componentType = componentType; + hashCode = localMember.GetHashCode() ^ (previousPath != null ? previousPath.GetHashCode() : 41); } @@ -33,6 +61,11 @@ public MemberInfo LocalMember get { return localMember; } } + public System.Type ComponentType + { + get { return componentType; } + } + public MemberInfo GetRootMember() { PropertyPath analizing = this; @@ -84,4 +117,4 @@ public override string ToString() return PreviousPath == null ? LocalMember.Name : PreviousPath + "." + LocalMember.Name; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/PropertyPathExtensions.cs b/src/NHibernate/Mapping/ByCode/PropertyPathExtensions.cs index 17c3ff0ba67..c1cad552114 100644 --- a/src/NHibernate/Mapping/ByCode/PropertyPathExtensions.cs +++ b/src/NHibernate/Mapping/ByCode/PropertyPathExtensions.cs @@ -10,11 +10,11 @@ public static class PropertyPathExtensions public static System.Type GetContainerEntity(this PropertyPath propertyPath, IModelInspector domainInspector) { PropertyPath analizing = propertyPath; - while (analizing.PreviousPath != null && !domainInspector.IsEntity(analizing.LocalMember.ReflectedType)) + while (analizing.PreviousPath != null && !domainInspector.IsEntity(analizing.ComponentType)) { analizing = analizing.PreviousPath; } - return analizing.LocalMember.ReflectedType; + return analizing.ComponentType; } public static string ToColumnName(this PropertyPath propertyPath, string pathSeparator) @@ -42,13 +42,15 @@ public static IEnumerable InverseProgressivePath(this PropertyPath } PropertyPath analizing = source; var returnLocalMembers = new List(10); + var returnComponentTypes = new List(10); do { returnLocalMembers.Add(analizing.LocalMember); + returnComponentTypes.Add(analizing.ComponentType); PropertyPath progressivePath = null; for (int i = returnLocalMembers.Count - 1; i >= 0; i--) { - progressivePath = new PropertyPath(progressivePath, returnLocalMembers[i]); + progressivePath = new PropertyPath(progressivePath, returnLocalMembers[i], returnComponentTypes[i]); } yield return progressivePath; analizing = analizing.PreviousPath; @@ -69,4 +71,4 @@ public static PropertyPath DepureFirstLevelIfCollection(this PropertyPath source return paths[paths.Length - penultimateOffset]; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/SimpleModelInspector.cs b/src/NHibernate/Mapping/ByCode/SimpleModelInspector.cs index 21cfa2cc9b5..439d4009389 100644 --- a/src/NHibernate/Mapping/ByCode/SimpleModelInspector.cs +++ b/src/NHibernate/Mapping/ByCode/SimpleModelInspector.cs @@ -214,7 +214,7 @@ public SimpleModelInspector() private bool MatchRootEntity(System.Type type) { - return type.IsClass && typeof(object).Equals(type.BaseType) && ((IModelInspector)this).IsEntity(type); + return type.GetTypeInfo().IsClass && typeof(object).Equals(type.GetTypeInfo().BaseType) && ((IModelInspector)this).IsEntity(type); } private bool MatchTablePerClass(System.Type type) @@ -225,7 +225,11 @@ private bool MatchTablePerClass(System.Type type) private bool MatchOneToMany(MemberInfo memberInfo) { var modelInspector = (IModelInspector) this; +#if FEATURE_REFLECTEDTYPE System.Type from = memberInfo.ReflectedType; +#else + System.Type from = memberInfo.DeclaringType; +#endif System.Type to = memberInfo.GetPropertyOrFieldType().DetermineCollectionElementOrDictionaryValueType(); if(to == null) { @@ -240,12 +244,16 @@ private bool MatchOneToMany(MemberInfo memberInfo) private bool MatchManyToOne(MemberInfo memberInfo) { var modelInspector = (IModelInspector)this; +#if FEATURE_REFLECTEDTYPE System.Type from = memberInfo.ReflectedType; +#else + System.Type from = memberInfo.DeclaringType; +#endif System.Type to = memberInfo.GetPropertyOrFieldType(); bool areEntities = modelInspector.IsEntity(from) && modelInspector.IsEntity(to); bool isFromComponentToEntity = modelInspector.IsComponent(from) && modelInspector.IsEntity(to); - return isFromComponentToEntity || (areEntities && !modelInspector.IsOneToOne(memberInfo)); + return isFromComponentToEntity || (areEntities && !modelInspector.IsOneToOne(memberInfo, from)); } protected bool MatchArrayMember(MemberInfo subject) @@ -261,7 +269,7 @@ protected bool MatchDictionaryMember(MemberInfo subject) { return true; } - if (memberType.IsGenericType) + if (memberType.GetTypeInfo().IsGenericType) { return memberType.GetGenericInterfaceTypeDefinitions().Contains(typeof(IDictionary<,>)); } @@ -299,7 +307,7 @@ protected bool MatchSetMember(MemberInfo subject) { var memberType = subject.GetPropertyOrFieldType(); - if (memberType.IsGenericType) + if (memberType.GetTypeInfo().IsGenericType) { return memberType.GetGenericInterfaceTypeDefinitions().Contains(typeof(ISet<>)); } @@ -330,21 +338,33 @@ protected bool IsReadOnlyProperty(MemberInfo subject) protected bool IsAutoproperty(PropertyInfo property) { - return property.ReflectedType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance - | BindingFlags.DeclaredOnly).Any(pi => pi.Name == string.Concat("<", property.Name, ">k__BackingField")); +#if FEATURE_REFLECTEDTYPE + var reflectedType = property.ReflectedType; +#else + var reflectedType = property.DeclaringType; +#endif + return reflectedType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Any(pi => pi.Name == string.Concat("<", property.Name, ">k__BackingField")); } protected bool CanReadCantWriteInsideType(PropertyInfo property) { - return !property.CanWrite && property.CanRead && property.DeclaringType == property.ReflectedType; + return !property.CanWrite && property.CanRead +#if FEATURE_REFLECTEDTYPE + && property.DeclaringType == property.ReflectedType; +#else + ; +#endif } protected bool CanReadCantWriteInBaseType(PropertyInfo property) { +#if FEATURE_REFLECTEDTYPE if (property.DeclaringType == property.ReflectedType) { return false; } +#endif var rfprop = property.DeclaringType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).SingleOrDefault(pi => pi.Name == property.Name); return rfprop != null && !rfprop.CanWrite && rfprop.CanRead; @@ -353,10 +373,10 @@ protected bool CanReadCantWriteInBaseType(PropertyInfo property) protected bool MatchPoIdPattern(MemberInfo subject) { var name = subject.Name; - return name.Equals("id", StringComparison.InvariantCultureIgnoreCase) - || name.Equals("poid", StringComparison.InvariantCultureIgnoreCase) - || name.Equals("oid", StringComparison.InvariantCultureIgnoreCase) - || (name.StartsWith(subject.DeclaringType.Name) && name.Equals(subject.DeclaringType.Name + "id", StringComparison.InvariantCultureIgnoreCase)); + return name.Equals("id", StringComparison.OrdinalIgnoreCase) + || name.Equals("poid", StringComparison.OrdinalIgnoreCase) + || name.Equals("oid", StringComparison.OrdinalIgnoreCase) + || (name.StartsWith(subject.DeclaringType.Name) && name.Equals(subject.DeclaringType.Name + "id", StringComparison.OrdinalIgnoreCase)); } protected bool MatchComponentPattern(System.Type subject) @@ -369,10 +389,10 @@ protected bool MatchComponentPattern(System.Type subject) return false; } var modelInspector = (IModelInspector) this; - return !subject.IsEnum && (subject.Namespace == null || !subject.Namespace.StartsWith("System")) /* hack */ + return !subject.GetTypeInfo().IsEnum && (subject.Namespace == null || !subject.Namespace.StartsWith("System")) /* hack */ && !modelInspector.IsEntity(subject) && !subject.GetProperties(flattenHierarchyMembers).Cast().Concat( - subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m)); + subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m, subject)); } protected bool MatchEntity(System.Type subject) @@ -384,8 +404,8 @@ protected bool MatchEntity(System.Type subject) return false; } var modelInspector = (IModelInspector) this; - return subject.IsClass && - subject.GetProperties(flattenHierarchyMembers).Cast().Concat(subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m)); + return subject.GetTypeInfo().IsClass && + subject.GetProperties(flattenHierarchyMembers).Cast().Concat(subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m, subject)); } #region IModelExplicitDeclarationsHolder Members @@ -706,9 +726,9 @@ bool IModelInspector.IsTablePerConcreteClass(System.Type type) return isTablePerConcreteClass(type, declaredResult); } - bool IModelInspector.IsOneToOne(MemberInfo member) + bool IModelInspector.IsOneToOne(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsOneToOne(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsOneToOne(m), componentType); return isOneToOne(member, declaredResult); } @@ -718,15 +738,21 @@ bool IModelInspector.IsManyToOne(MemberInfo member) return isManyToOne(member, declaredResult); } - bool IModelInspector.IsManyToManyItem(MemberInfo member) + bool IModelInspector.IsManyToOne(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToManyItem(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToOne(m), componentType); + return isManyToOne(member, declaredResult); + } + + bool IModelInspector.IsManyToManyItem(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToManyItem(m), componentType); return isManyToMany(member, declaredResult); } - bool IModelInspector.IsManyToManyKey(MemberInfo member) + bool IModelInspector.IsManyToManyKey(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToManyKey(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToManyKey(m), componentType); return isManyToMany(member, declaredResult); } @@ -736,15 +762,21 @@ bool IModelInspector.IsOneToMany(MemberInfo member) return isOneToMany(member, declaredResult); } - bool IModelInspector.IsManyToAny(MemberInfo member) + bool IModelInspector.IsOneToMany(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToAny(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsOneToMany(m), componentType); + return isOneToMany(member, declaredResult); + } + + bool IModelInspector.IsManyToAny(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsManyToAny(m), componentType); return isManyToAny(member, declaredResult); } - bool IModelInspector.IsAny(MemberInfo member) + bool IModelInspector.IsAny(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsAny(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsAny(m), componentType); return isAny(member, declaredResult); } @@ -754,6 +786,12 @@ bool IModelInspector.IsPersistentId(MemberInfo member) return isPersistentId(member, declaredResult); } + bool IModelInspector.IsPersistentId(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsPersistentId(m), componentType); + return isPersistentId(member, declaredResult); + } + bool IModelInspector.IsMemberOfComposedId(MemberInfo member) { return declaredModel.IsMemberOfComposedId(member); @@ -765,39 +803,69 @@ bool IModelInspector.IsVersion(MemberInfo member) return isVersion(member, declaredResult); } + bool IModelInspector.IsVersion(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsVersion(m), componentType); + return isVersion(member, declaredResult); + } + bool IModelInspector.IsMemberOfNaturalId(MemberInfo member) { bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsMemberOfNaturalId(m)); return isMemberOfNaturalId(member, declaredResult); } + bool IModelInspector.IsMemberOfNaturalId(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsMemberOfNaturalId(m), componentType); + return isMemberOfNaturalId(member, declaredResult); + } + bool IModelInspector.IsPersistentProperty(MemberInfo member) { bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsPersistentProperty(m)); return isPersistentProperty(member, declaredResult); } + bool IModelInspector.IsPersistentProperty(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsPersistentProperty(m), componentType); + return isPersistentProperty(member, declaredResult); + } + bool IModelInspector.IsSet(MemberInfo role) { bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsSet(m)); return isSet(role, declaredResult); } + bool IModelInspector.IsSet(MemberInfo role, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsSet(m), componentType); + return isSet(role, declaredResult); + } + bool IModelInspector.IsBag(MemberInfo role) { bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsBag(m)); return isBag(role, declaredResult); } - bool IModelInspector.IsIdBag(MemberInfo role) + bool IModelInspector.IsBag(MemberInfo role, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsIdBag(m)); + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsBag(m), componentType); + return isBag(role, declaredResult); + } + + bool IModelInspector.IsIdBag(MemberInfo role, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsIdBag(m), componentType); return isIdBag(role, declaredResult); } - bool IModelInspector.IsList(MemberInfo role) + bool IModelInspector.IsList(MemberInfo role, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsList(m)); + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsList(m), componentType); return isList(role, declaredResult); } @@ -807,21 +875,33 @@ bool IModelInspector.IsArray(MemberInfo role) return isArray(role, declaredResult); } + bool IModelInspector.IsArray(MemberInfo role, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsArray(m), componentType); + return isArray(role, declaredResult); + } + bool IModelInspector.IsDictionary(MemberInfo role) { bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsDictionary(m)); return isDictionary(role, declaredResult); } - bool IModelInspector.IsProperty(MemberInfo member) + bool IModelInspector.IsDictionary(MemberInfo role, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsProperty(m)); + bool declaredResult = DeclaredPolymorphicMatch(role, m => declaredModel.IsDictionary(m), componentType); + return isDictionary(role, declaredResult); + } + + bool IModelInspector.IsProperty(MemberInfo member, System.Type componentType) + { + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsProperty(m), componentType); return isProperty(member, declaredResult); } - bool IModelInspector.IsDynamicComponent(MemberInfo member) + bool IModelInspector.IsDynamicComponent(MemberInfo member, System.Type componentType) { - bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsDynamicComponent(m)); + bool declaredResult = DeclaredPolymorphicMatch(member, m => declaredModel.IsDynamicComponent(m), componentType); return isDynamicComponent(member, declaredResult); } @@ -849,6 +929,13 @@ protected virtual bool DeclaredPolymorphicMatch(MemberInfo member, Func declaredMatch, System.Type componentType) + { + return declaredMatch(member) + || member.GetMemberFromDeclaringClasses(componentType).Any(declaredMatch) + || member.GetPropertyFromInterfaces(componentType).Any(declaredMatch); + } + public void IsRootEntity(Func match) { if (match == null) @@ -1083,4 +1170,4 @@ public void IsDynamicComponent(Func match) isDynamicComponent = match; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/TypeExtensions.cs b/src/NHibernate/Mapping/ByCode/TypeExtensions.cs index 89dd4a6a29d..94765eb688d 100644 --- a/src/NHibernate/Mapping/ByCode/TypeExtensions.cs +++ b/src/NHibernate/Mapping/ByCode/TypeExtensions.cs @@ -21,7 +21,7 @@ public static class TypeExtensions var analizing = type; while (analizing != null && analizing != typeof (object)) { - analizing = analizing.BaseType; + analizing = analizing.GetTypeInfo().BaseType; yield return analizing; } } @@ -33,7 +33,7 @@ public static class TypeExtensions while (analyzingType != null && analyzingType != typeof (object)) { typeHierarchy.Push(analyzingType); - analyzingType = analyzingType.BaseType; + analyzingType = analyzingType.GetTypeInfo().BaseType; } return typeHierarchy; } @@ -94,7 +94,7 @@ public static MemberInfo DecodeMemberAccessExpressionOf(Expression(Expression> expression) { var memberOfDeclaringType = DecodeMemberAccessExpression(expression); - if (typeof (TEntity).IsInterface) + if (typeof (TEntity).GetTypeInfo().IsInterface) { // Type.GetProperty(string name,Type returnType) does not work properly with interfaces return memberOfDeclaringType; @@ -103,7 +103,7 @@ public static MemberInfo DecodeMemberAccessExpressionOf(Expr var propertyInfo = memberOfDeclaringType as PropertyInfo; if (propertyInfo != null) { - return typeof (TEntity).GetProperty(propertyInfo.Name, PropertiesOfClassHierarchy, null, propertyInfo.PropertyType, new System.Type[0], null); + return typeof(TEntity).GetProperty(propertyInfo.Name, PropertiesOfClassHierarchy, null, propertyInfo.PropertyType, new System.Type[0], null); } if (memberOfDeclaringType is FieldInfo) { @@ -113,13 +113,30 @@ public static MemberInfo DecodeMemberAccessExpressionOf(Expr } public static MemberInfo GetMemberFromDeclaringType(this MemberInfo source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + //if (source.DeclaringType != source.ReflectedType) + //{ + // throw new InvalidOperationException(string.Format("DeclaringType {0} not the same as ReflectedType {1}", source.DeclaringType, source.ReflectedType)); + //} +#if FEATURE_REFLECTEDTYPE + return GetMemberFromDeclaringType(source, source.ReflectedType); +#else + return GetMemberFromDeclaringType(source, source.DeclaringType); +#endif + } + + public static MemberInfo GetMemberFromDeclaringType(this MemberInfo source, System.Type componentType) { if (source == null) { throw new ArgumentNullException("source"); } - if (source.DeclaringType.Equals(source.ReflectedType)) + if (source.DeclaringType.Equals(componentType)) { return source; } @@ -137,6 +154,23 @@ public static MemberInfo GetMemberFromDeclaringType(this MemberInfo source) } public static IEnumerable GetMemberFromDeclaringClasses(this MemberInfo source) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + //if (source.DeclaringType != source.ReflectedType) + //{ + // throw new InvalidOperationException(string.Format("DeclaringType {0} not the same as ReflectedType {1}", source.DeclaringType, source.ReflectedType)); + //} +#if FEATURE_REFLECTEDTYPE + return GetMemberFromDeclaringClasses(source, source.ReflectedType); +#else + return GetMemberFromDeclaringClasses(source, source.DeclaringType); +#endif + } + + public static IEnumerable GetMemberFromDeclaringClasses(this MemberInfo source, System.Type componentType) { if (source == null) { @@ -145,14 +179,14 @@ public static IEnumerable GetMemberFromDeclaringClasses(this MemberI if (source is PropertyInfo) { - var reflectedType = source.ReflectedType; + var reflectedType = componentType; var memberType = source.GetPropertyOrFieldType(); return reflectedType.GetPropertiesOfHierarchy().Cast().Where(x => source.Name.Equals(x.Name) && memberType.Equals(x.PropertyType)).Cast(); } if (source is FieldInfo) { - return new[] { source.GetMemberFromDeclaringType() }; + return new[] { source.GetMemberFromDeclaringType(componentType) }; } return Enumerable.Empty(); @@ -164,16 +198,41 @@ public static IEnumerable GetPropertyFromInterfaces(this MemberInfo { throw new ArgumentNullException("source"); } + //if (source.DeclaringType != source.ReflectedType) + //{ + // throw new InvalidOperationException(string.Format("DeclaringType {0} not the same as ReflectedType {1}", source.DeclaringType, source.ReflectedType)); + //} +#if FEATURE_REFLECTEDTYPE + return GetPropertyFromInterfaces(source, source.ReflectedType); +#else + return GetPropertyFromInterfaces(source, source.DeclaringType); +#endif + } + + public static IEnumerable GetPropertyFromInterfaces(this MemberInfo source, System.Type componentType) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (!source.DeclaringType.IsAssignableFrom(componentType)) + { + throw new ArgumentException("source Member not implemented on passed in type", "componentType"); + } + //if (componentType != source.ReflectedType) + //{ + // throw new InvalidOperationException(string.Format("componentType {0} not the same as ReflectedType {1}", componentType, source.ReflectedType)); + //} var propertyInfo = source as PropertyInfo; if (propertyInfo == null) { yield break; } - if (source.ReflectedType.IsInterface) + if (componentType.GetTypeInfo().IsInterface) { yield break; } - System.Type[] interfaces = source.ReflectedType.GetInterfaces(); + System.Type[] interfaces = componentType.GetInterfaces(); if (interfaces.Length == 0) { yield break; @@ -181,7 +240,7 @@ public static IEnumerable GetPropertyFromInterfaces(this MemberInfo MethodInfo propertyGetter = propertyInfo.GetGetMethod(); foreach (System.Type @interface in interfaces) { - InterfaceMapping memberMap = source.ReflectedType.GetInterfaceMap(@interface); + InterfaceMapping memberMap = componentType.GetTypeInfo().GetRuntimeInterfaceMap(@interface); PropertyInfo[] interfaceProperties = @interface.GetProperties(); for (int i = 0; i < memberMap.TargetMethods.Length; i++) { @@ -195,9 +254,9 @@ public static IEnumerable GetPropertyFromInterfaces(this MemberInfo public static System.Type DetermineCollectionElementType(this System.Type genericCollection) { - List interfaces = genericCollection.GetInterfaces().Where(t => t.IsGenericType).ToList(); + List interfaces = genericCollection.GetInterfaces().Where(t => t.GetTypeInfo().IsGenericType).ToList(); - if (genericCollection.IsGenericType) + if (genericCollection.GetTypeInfo().IsGenericType) { interfaces.Add(genericCollection); } @@ -232,10 +291,10 @@ public static System.Type DetermineRequiredCollectionElementType(this MemberInfo public static System.Type DetermineCollectionElementOrDictionaryValueType(this System.Type genericCollection) { - if (genericCollection.IsGenericType) + if (genericCollection.GetTypeInfo().IsGenericType) { - List interfaces = genericCollection.GetInterfaces().Where(t => t.IsGenericType).ToList(); - if (genericCollection.IsInterface) + List interfaces = genericCollection.GetInterfaces().Where(t => t.GetTypeInfo().IsGenericType).ToList(); + if (genericCollection.GetTypeInfo().IsInterface) { interfaces.Add(genericCollection); } @@ -255,7 +314,7 @@ public static System.Type DetermineCollectionElementOrDictionaryValueType(this S public static System.Type DetermineDictionaryKeyType(this System.Type genericDictionary) { - if (genericDictionary.IsGenericType) + if (genericDictionary.GetTypeInfo().IsGenericType) { System.Type dictionaryInterface = GetDictionaryInterface(genericDictionary); if (dictionaryInterface != null) @@ -268,8 +327,8 @@ public static System.Type DetermineDictionaryKeyType(this System.Type genericDic private static System.Type GetDictionaryInterface(System.Type genericDictionary) { - List interfaces = genericDictionary.GetInterfaces().Where(t => t.IsGenericType).ToList(); - if (genericDictionary.IsInterface) + List interfaces = genericDictionary.GetInterfaces().Where(t => t.GetTypeInfo().IsGenericType).ToList(); + if (genericDictionary.GetTypeInfo().IsInterface) { interfaces.Add(genericDictionary); } @@ -278,7 +337,7 @@ private static System.Type GetDictionaryInterface(System.Type genericDictionary) public static System.Type DetermineDictionaryValueType(this System.Type genericDictionary) { - if (genericDictionary.IsGenericType) + if (genericDictionary.GetTypeInfo().IsGenericType) { System.Type dictionaryInterface = GetDictionaryInterface(genericDictionary); if (dictionaryInterface != null) @@ -291,7 +350,7 @@ public static System.Type DetermineDictionaryValueType(this System.Type genericD public static bool IsGenericCollection(this System.Type source) { - return source.IsGenericType && typeof (IEnumerable).IsAssignableFrom(source); + return source.GetTypeInfo().IsGenericType && typeof (IEnumerable).IsAssignableFrom(source); } public static MemberInfo GetFirstPropertyOfType(this System.Type propertyContainerType, System.Type propertyType) @@ -325,7 +384,7 @@ public static MemberInfo GetFirstPropertyOfType(this System.Type propertyContain public static IEnumerable GetInterfaceProperties(this System.Type type) { - if (!type.IsInterface) + if (!type.GetTypeInfo().IsInterface) { yield break; } @@ -353,7 +412,7 @@ public static IEnumerable GetInterfaceProperties(this System.Type ty public static bool IsEnumOrNullableEnum(this System.Type type) { - return type != null && type.UnwrapIfNullable().IsEnum; + return type != null && type.UnwrapIfNullable().GetTypeInfo().IsEnum; } public static bool IsFlagEnumOrNullableFlagEnum(this System.Type type) @@ -363,16 +422,16 @@ public static bool IsFlagEnumOrNullableFlagEnum(this System.Type type) return false; } var typeofEnum = type.UnwrapIfNullable(); - return typeofEnum.IsEnum && typeofEnum.GetCustomAttributes(typeof (FlagsAttribute), false).Length > 0; + return typeofEnum.GetTypeInfo().IsEnum && typeofEnum.GetTypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false).Any(); } public static IEnumerable GetGenericInterfaceTypeDefinitions(this System.Type type) { - if (type.IsGenericType && type.IsInterface) + if (type.GetTypeInfo().IsGenericType && type.GetTypeInfo().IsInterface) { yield return type.GetGenericTypeDefinition(); } - foreach (System.Type t in type.GetInterfaces().Where(t => t.IsGenericType)) + foreach (System.Type t in type.GetInterfaces().Where(t => t.GetTypeInfo().IsGenericType)) { yield return t.GetGenericTypeDefinition(); } @@ -390,7 +449,7 @@ public static System.Type GetFirstImplementorOf(this System.Type source, System. throw new ArgumentNullException("abstractType"); } - if (source.IsInterface) + if (source.GetTypeInfo().IsInterface) { return null; } @@ -442,7 +501,7 @@ public static MemberInfo GetMemberFromReflectedType(this MemberInfo member, Syst { return member; } - if (property.DeclaringType.IsInterface) + if (property.DeclaringType.GetTypeInfo().IsInterface) { System.Type[] interfaces = reflectedType.GetInterfaces(); var @interface = property.DeclaringType; @@ -451,7 +510,7 @@ public static MemberInfo GetMemberFromReflectedType(this MemberInfo member, Syst return member; } var reflectedCandidateProps = reflectedType.GetProperties(PropertiesOfClassHierarchy); - InterfaceMapping memberMap = reflectedType.GetInterfaceMap(@interface); + InterfaceMapping memberMap = reflectedType.GetTypeInfo().GetRuntimeInterfaceMap(@interface); for (int i = 0; i < memberMap.TargetMethods.Length; i++) { if (memberMap.InterfaceMethods[i] == propertyGetter) @@ -496,7 +555,7 @@ public static MemberInfo GetPropertyOrFieldMatchingName(this System.Type source, private static IEnumerable GetPropertiesOfInterfacesImplemented(this System.Type source) { - if (source.IsInterface) + if (source.GetTypeInfo().IsInterface) { foreach (var interfaceProperty in source.GetInterfaceProperties()) { @@ -515,7 +574,7 @@ private static IEnumerable GetPropertiesOfInterfacesImplemented(this internal static IEnumerable GetPropertiesOfHierarchy(this System.Type type) { - if(type.IsInterface) + if(type.GetTypeInfo().IsInterface) { yield break; } @@ -526,13 +585,13 @@ internal static IEnumerable GetPropertiesOfHierarchy(this System.Typ { yield return propertyInfo; } - analizing = analizing.BaseType; + analizing = analizing.GetTypeInfo().BaseType; } } private static IEnumerable GetFieldsOfHierarchy(this System.Type type) { - if (type.IsInterface) + if (type.GetTypeInfo().IsInterface) { yield break; } @@ -543,7 +602,7 @@ private static IEnumerable GetFieldsOfHierarchy(this System.Type typ { yield return fieldInfo; } - analizing = analizing.BaseType; + analizing = analizing.GetTypeInfo().BaseType; } } @@ -553,4 +612,4 @@ private static IEnumerable GetUserDeclaredFields(System.Type type) return type.GetFields(PropertiesOrFieldOfClass).Where(x => !x.Name.StartsWith("<")); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ManyToOne.cs b/src/NHibernate/Mapping/ManyToOne.cs index b7d9ff5b590..da6edcbb187 100644 --- a/src/NHibernate/Mapping/ManyToOne.cs +++ b/src/NHibernate/Mapping/ManyToOne.cs @@ -73,7 +73,7 @@ public void CreatePropertyRefConstraints(IDictionary pe if (property == null) throw new MappingException("Could not find property " + ReferencedPropertyName + " on " + ReferencedEntityName); - if (!HasFormula && !"none".Equals(ForeignKeyName, StringComparison.InvariantCultureIgnoreCase)) + if (!HasFormula && !"none".Equals(ForeignKeyName, StringComparison.OrdinalIgnoreCase)) { IEnumerable ce = new SafetyEnumerable(property.ColumnIterator); @@ -92,4 +92,4 @@ public void CreatePropertyRefConstraints(IDictionary pe } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/OneToMany.cs b/src/NHibernate/Mapping/OneToMany.cs index 51dbdc4ac5f..f9caf0fd8cb 100644 --- a/src/NHibernate/Mapping/OneToMany.cs +++ b/src/NHibernate/Mapping/OneToMany.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using NHibernate.Engine; using NHibernate.Type; +using NHibernate.Util; namespace NHibernate.Mapping { @@ -48,7 +49,7 @@ public int ColumnSpan public string ReferencedEntityName { get { return referencedEntityName; } - set { referencedEntityName = value == null ? null : string.Intern(value); } + set { referencedEntityName = StringHelper.InternedIfPossible(value); } } public Table ReferencingTable @@ -161,4 +162,4 @@ public bool IsEmbedded set { embedded = value; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/PersistentClass.cs b/src/NHibernate/Mapping/PersistentClass.cs index d6f938cb8dc..6803834a5ca 100644 --- a/src/NHibernate/Mapping/PersistentClass.cs +++ b/src/NHibernate/Mapping/PersistentClass.cs @@ -71,7 +71,7 @@ public string ClassName get { return className; } set { - className = value == null ? null : string.Intern(value); + className = StringHelper.InternedIfPossible(value); mappedClass = null; } } @@ -260,7 +260,7 @@ public virtual IEnumerable DirectSubclasses public virtual string EntityName { get { return entityName; } - set { entityName = value == null ? null : String.Intern(value); } + set { entityName = StringHelper.InternedIfPossible(value); } } /// @@ -520,7 +520,7 @@ public virtual IDictionary FilterMap public string LoaderName { get { return loaderName; } - set { loaderName = value == null ? null : string.Intern(value); } + set { loaderName = StringHelper.InternedIfPossible(value); } } public virtual ISet SynchronizedTables diff --git a/src/NHibernate/Mapping/ReferenceDependantValue.cs b/src/NHibernate/Mapping/ReferenceDependantValue.cs index 52100c513d1..7f2ff5fa742 100644 --- a/src/NHibernate/Mapping/ReferenceDependantValue.cs +++ b/src/NHibernate/Mapping/ReferenceDependantValue.cs @@ -24,7 +24,7 @@ public IEnumerable ReferenceColumns public override void CreateForeignKeyOfEntity(string entityName) { - if (!HasFormula && !string.Equals("none", ForeignKeyName, StringComparison.InvariantCultureIgnoreCase)) + if (!HasFormula && !string.Equals("none", ForeignKeyName, StringComparison.OrdinalIgnoreCase)) { var referencedColumns = new List(_prototype.ColumnSpan); foreach (Column column in _prototype.ColumnIterator) diff --git a/src/NHibernate/Mapping/SimpleValue.cs b/src/NHibernate/Mapping/SimpleValue.cs index c9ad4cca562..8659ba8b2aa 100644 --- a/src/NHibernate/Mapping/SimpleValue.cs +++ b/src/NHibernate/Mapping/SimpleValue.cs @@ -75,7 +75,7 @@ public virtual bool IsComposite public virtual void CreateForeignKeyOfEntity(string entityName) { - if (!HasFormula && ! "none".Equals(ForeignKeyName, StringComparison.InvariantCultureIgnoreCase)) + if (!HasFormula && ! "none".Equals(ForeignKeyName, StringComparison.OrdinalIgnoreCase)) { ForeignKey fk = table.CreateForeignKey(ForeignKeyName, ConstraintColumns, entityName); fk.CascadeDeleteEnabled = cascadeDeleteEnabled; diff --git a/src/NHibernate/MappingException.cs b/src/NHibernate/MappingException.cs index b02ed5dc0b0..99f69acd21a 100644 --- a/src/NHibernate/MappingException.cs +++ b/src/NHibernate/MappingException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -46,6 +49,7 @@ public MappingException(string message, Exception innerException) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -61,5 +65,6 @@ protected MappingException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/NHibernate.csproj b/src/NHibernate/NHibernate.csproj index d850d9107da..30b9da6f319 100644 --- a/src/NHibernate/NHibernate.csproj +++ b/src/NHibernate/NHibernate.csproj @@ -1,1833 +1,70 @@ - - - + + - Debug - AnyCPU - 9.0.30729 - 2.0 - {5909BFE7-93CF-4E5F-BE22-6293368AF01D} - Library - Properties - NHibernate + netstandard1.6;net461 + $(NoWarn);CS3001;CS3002;CS3003;CS3005 NHibernate - - - 3.5 - - - v4.6.1 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - + NHibernate + $(PackageTargetFallback);dnxcore50;portable-net45+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1;portable-net45+wpa81+wp80+win + 1.6.1 + $(PackageTargetFallback);portable-net45+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1;portable-net45+wpa81+wp80+win + false + false + false + false + false - - true - full - false - bin\Debug-2.0\ - obj\ - obj\Debug-2.0\ - NET_4_0 - prompt - 4 - bin\Debug-2.0\NHibernate.XML - 1591%3b3001%3b3002%3b3003%3b3004%3b3005 - 1717;1574 - AllRules.ruleset - false + + + $(DefineConstants);NETSTANDARD;FEATURE_DATA_GETCOLUMNSCHEMA;FEATURE_INTERNALIZE_IESI;FEATURE_NETCORE_ICLONEABLE_API;FEATURE_NETCORE_REFLECTION_API - - pdbonly - true - bin\Release-2.0\ - obj\ - obj\Release-2.0\ - TRACE;NET_2_0;NET_4_0 - prompt - 4 - 1591;3001;3002;3003;3004;3005 - AllRules.ruleset - bin\Release-2.0\NHibernate.XML - false - - - true - - - ..\NHibernate.snk + + + $(DefineConstants);NET_4_0;FEATURE_ADONET_SQLCOMMANDSET;FEATURE_APPDOMAIN;FEATURE_ASSEMBLYBUILDER_SAVE;FEATURE_BINDINGLIST;FEATURE_CODEDOM;FEATURE_DATA_CLOSE;FEATURE_DATA_GETSCHEMATABLE;FEATURE_DBPROVIDERFACTORIES;FEATURE_ODBC_OLEDB;FEATURE_REFLECTEDTYPE;FEATURE_REMOTING;FEATURE_SECURITY_PERMISSIONS;FEATURE_SERIALIZATION;FEATURE_STRING_INTERN;FEATURE_SYSTEM_CONFIGURATION;FEATURE_SYSTEM_SERVICEMODEL;FEATURE_SYSTEM_TRANSACTIONS;FEATURE_WEB_SESSION_CONTEXT;FEATURE_XML_SCHEMAS;FEATURE_XML_VALIDATIONEVENTHANDLER + - - ..\packages\Antlr3.Runtime.3.5.1\lib\net40-client\Antlr3.Runtime.dll - True - - - ..\packages\Iesi.Collections.4.0.1.4000\lib\net40\Iesi.Collections.dll - True - - - ..\packages\Remotion.Linq.1.13.183.0\lib\net35\Remotion.Linq.dll - True - - - - - - - - - + + - - SharedAssemblyInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - NHibernate.snk - - - - - - - - + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use 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/NHibernate/NHibernateUtil.cs b/src/NHibernate/NHibernateUtil.cs index 8f96d3db854..0aa34935c9f 100644 --- a/src/NHibernate/NHibernateUtil.cs +++ b/src/NHibernate/NHibernateUtil.cs @@ -63,7 +63,7 @@ public static IType GuessType(System.Type type) if (clrTypeToNHibernateType.TryGetValue(type, out value)) return value; - if (type.IsEnum) + if (type.GetTypeInfo().IsEnum) return (IType) Activator.CreateInstance(typeof (EnumType<>).MakeGenericType(type)); if (typeof(IUserType).IsAssignableFrom(type) || @@ -258,6 +258,7 @@ public static IType GuessType(System.Type type) /// public static readonly ClassMetaType ClassMetaType = new ClassMetaType(); +#if FEATURE_SERIALIZATION /// /// NHibernate serializable type /// @@ -267,6 +268,7 @@ public static IType GuessType(System.Type type) /// NHibernate System.Object type /// public static readonly AnyType Object = new AnyType(); +#endif // /// @@ -308,6 +310,7 @@ public static IType Enum(System.Type enumClass) return new PersistentEnumType(enumClass); } +#if FEATURE_SERIALIZATION /// /// A NHibernate serializable type /// @@ -328,6 +331,7 @@ public static IType Any(IType metaType, IType identifierType) { return new AnyType(metaType, identifierType); } +#endif /// /// A NHibernate persistent object (entity) type diff --git a/src/NHibernate/NonUniqueObjectException.cs b/src/NHibernate/NonUniqueObjectException.cs index ba7f60e4ffc..9a610479f62 100644 --- a/src/NHibernate/NonUniqueObjectException.cs +++ b/src/NHibernate/NonUniqueObjectException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -56,6 +58,7 @@ public string EntityName get { return entityName; } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -88,5 +91,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/NonUniqueResultException.cs b/src/NHibernate/NonUniqueResultException.cs index fee84c0109e..9a6d6b85917 100644 --- a/src/NHibernate/NonUniqueResultException.cs +++ b/src/NHibernate/NonUniqueResultException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate @@ -23,6 +26,7 @@ public NonUniqueResultException(int resultCount) resultCount.ToString()); } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -38,5 +42,6 @@ protected NonUniqueResultException(SerializationInfo info, StreamingContext cont : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/ObjectDeletedException.cs b/src/NHibernate/ObjectDeletedException.cs index c3ee6a853c6..eb06fabafd2 100644 --- a/src/NHibernate/ObjectDeletedException.cs +++ b/src/NHibernate/ObjectDeletedException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -17,6 +20,7 @@ public ObjectDeletedException(string message, object identifier, string clazz) { } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -35,5 +39,6 @@ protected ObjectDeletedException(SerializationInfo info, StreamingContext contex } #endregion +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/ObjectNotFoundException.cs b/src/NHibernate/ObjectNotFoundException.cs index d09447b44b8..296cc15b3c2 100644 --- a/src/NHibernate/ObjectNotFoundException.cs +++ b/src/NHibernate/ObjectNotFoundException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -25,6 +28,7 @@ public ObjectNotFoundException(object identifier, System.Type type) : base(ident public ObjectNotFoundException(object identifier, string entityName) : base(identifier, entityName) {} +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -43,5 +47,6 @@ protected ObjectNotFoundException(SerializationInfo info, StreamingContext conte } #endregion +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/PersistentObjectException.cs b/src/NHibernate/PersistentObjectException.cs index 0a3d7cc7563..d437dcd1dac 100644 --- a/src/NHibernate/PersistentObjectException.cs +++ b/src/NHibernate/PersistentObjectException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -18,6 +21,7 @@ public PersistentObjectException(string message) : base(message) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -32,5 +36,6 @@ public PersistentObjectException(string message) : base(message) protected PersistentObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs index 288c018810f..c07d42b0e6a 100644 --- a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs +++ b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs @@ -1587,15 +1587,10 @@ private bool Exists(object key, object indexOrElement, IType indexOrElementType, { KeyType.NullSafeSet(st, key, 0, session); indexOrElementType.NullSafeSet(st, indexOrElement, keyColumnNames.Length, session); - rs = session.Batcher.ExecuteReader(st); - try + using (rs = session.Batcher.ExecuteReader(st)) { return rs.Read(); } - finally - { - rs.Close(); - } } catch (TransientObjectException) { @@ -1627,8 +1622,7 @@ public virtual object GetElementByIndex(object key, object index, ISessionImplem { KeyType.NullSafeSet(st, key, 0, session); IndexType.NullSafeSet(st, IncrementIndexByBase(index), keyColumnNames.Length, session); - rs = session.Batcher.ExecuteReader(st); - try + using (rs = session.Batcher.ExecuteReader(st)) { if (rs.Read()) { @@ -1639,10 +1633,6 @@ public virtual object GetElementByIndex(object key, object index, ISessionImplem return NotFoundObject; } } - finally - { - rs.Close(); - } } finally { diff --git a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs index c0b98bb0eeb..56fef2ced17 100644 --- a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs @@ -2572,7 +2572,7 @@ public object[] Hydrate(DbDataReader rs, object id, object obj, ILoadable rootLo if (sequentialResultSet != null) { - sequentialResultSet.Close(); + sequentialResultSet.Dispose(); } return values; diff --git a/src/NHibernate/Persister/PersisterFactory.cs b/src/NHibernate/Persister/PersisterFactory.cs index 1231d4181f9..f0eb0a7d523 100644 --- a/src/NHibernate/Persister/PersisterFactory.cs +++ b/src/NHibernate/Persister/PersisterFactory.cs @@ -7,6 +7,7 @@ using NHibernate.Mapping; using NHibernate.Persister.Collection; using NHibernate.Persister.Entity; +using NHibernate.Util; namespace NHibernate.Persister { @@ -149,10 +150,10 @@ public static ICollectionPersister Create(System.Type persisterClass, Mapping.Co var messageBuilder = new StringBuilder(); messageBuilder.AppendLine("Could not find a public constructor for " + persisterClass.Name +";"); messageBuilder.AppendLine("- The ctor may have " + CollectionPersisterConstructorArgs.Length + " parameters of types (in order):"); - System.Array.ForEach(CollectionPersisterConstructorArgs, t=> messageBuilder.AppendLine(t.FullName)); + CollectionPersisterConstructorArgs.ForEach(t => messageBuilder.AppendLine(t.FullName)); messageBuilder.AppendLine(); messageBuilder.AppendLine("- The ctor may have " + CollectionPersisterConstructor2Args.Length + " parameters of types (in order):"); - System.Array.ForEach(CollectionPersisterConstructor2Args, t => messageBuilder.AppendLine(t.FullName)); + CollectionPersisterConstructor2Args.ForEach(t => messageBuilder.AppendLine(t.FullName)); throw new MappingException(messageBuilder.ToString()); } try diff --git a/src/NHibernate/Properties/BasicPropertyAccessor.cs b/src/NHibernate/Properties/BasicPropertyAccessor.cs index 77ab011f58b..4246efdc820 100644 --- a/src/NHibernate/Properties/BasicPropertyAccessor.cs +++ b/src/NHibernate/Properties/BasicPropertyAccessor.cs @@ -96,7 +96,7 @@ internal static BasicGetter GetGetterOrNull(System.Type type, string propertyNam else { // recursively call this method for the base Type - BasicGetter getter = GetGetterOrNull(type.BaseType, propertyName); + BasicGetter getter = GetGetterOrNull(type.GetTypeInfo().BaseType, propertyName); // didn't find anything in the base class - check to see if there is // an explicit interface implementation. @@ -132,7 +132,7 @@ internal static BasicSetter GetSetterOrNull(System.Type type, string propertyNam BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - if (type.IsValueType) + if (type.GetTypeInfo().IsValueType) { // the BindingFlags.IgnoreCase is important here because if type is a struct, the GetProperty method does // not ignore case by default. If type is a class, it _does_ ignore case... we're better off explicitly @@ -148,7 +148,7 @@ internal static BasicSetter GetSetterOrNull(System.Type type, string propertyNam } // recursively call this method for the base Type - BasicSetter setter = GetSetterOrNull(type.BaseType, propertyName); + BasicSetter setter = GetSetterOrNull(type.GetTypeInfo().BaseType, propertyName); // didn't find anything in the base class - check to see if there is // an explicit interface implementation. diff --git a/src/NHibernate/Properties/FieldAccessor.cs b/src/NHibernate/Properties/FieldAccessor.cs index 5a4b4df3854..f62c5e53e53 100644 --- a/src/NHibernate/Properties/FieldAccessor.cs +++ b/src/NHibernate/Properties/FieldAccessor.cs @@ -114,7 +114,7 @@ private static FieldInfo GetField(System.Type type, string fieldName, System.Typ if (field == null) { // recursively call this method for the base Type - field = GetField(type.BaseType, fieldName, originalType); + field = GetField(type.GetTypeInfo().BaseType, fieldName, originalType); } return field; diff --git a/src/NHibernate/PropertyAccessException.cs b/src/NHibernate/PropertyAccessException.cs index 47666cd249a..4e65a9014cf 100644 --- a/src/NHibernate/PropertyAccessException.cs +++ b/src/NHibernate/PropertyAccessException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -9,7 +11,11 @@ namespace NHibernate /// A problem occurred accessing a property of an instance of a persistent class by reflection /// [Serializable] - public class PropertyAccessException : HibernateException, ISerializable + public class PropertyAccessException + : HibernateException +#if FEATURE_SERIALIZATION + , ISerializable +#endif { private readonly System.Type persistentType; private readonly string propertyName; @@ -68,6 +74,7 @@ public override string Message } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -109,5 +116,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/PropertyNotFoundException.cs b/src/NHibernate/PropertyNotFoundException.cs index cc3c0150ce9..f1467b5f407 100644 --- a/src/NHibernate/PropertyNotFoundException.cs +++ b/src/NHibernate/PropertyNotFoundException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -54,6 +57,7 @@ public PropertyNotFoundException(string propertyName, string fieldName, System.T accessorType = fieldName; } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -68,6 +72,7 @@ public PropertyNotFoundException(string propertyName, string fieldName, System.T protected PropertyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif public System.Type TargetType { @@ -84,4 +89,4 @@ public string AccessorType get { return accessorType; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/PropertyValueException.cs b/src/NHibernate/PropertyValueException.cs index 77c9a739636..7221d33b2c6 100644 --- a/src/NHibernate/PropertyValueException.cs +++ b/src/NHibernate/PropertyValueException.cs @@ -1,8 +1,10 @@ using System; +using NHibernate.Util; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; -using NHibernate.Util; +#endif namespace NHibernate { @@ -53,6 +55,7 @@ public override string Message } } +#if FEATURE_SERIALIZATION #region Serialization /// @@ -93,5 +96,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/Proxy/DefaultDynamicProxyMethodCheckerExtensions.cs b/src/NHibernate/Proxy/DefaultDynamicProxyMethodCheckerExtensions.cs index 5b70fc9b1a6..0eff0e19580 100644 --- a/src/NHibernate/Proxy/DefaultDynamicProxyMethodCheckerExtensions.cs +++ b/src/NHibernate/Proxy/DefaultDynamicProxyMethodCheckerExtensions.cs @@ -10,7 +10,9 @@ public static class DefaultDynamicProxyMethodCheckerExtensions public static bool IsProxiable(this MethodInfo method) { return !method.IsFinal +#if FEATURE_REMOTING && (method.DeclaringType != typeof(MarshalByRefObject)) +#endif && (method.DeclaringType != typeof(object) || !"finalize".Equals(method.Name.ToLowerInvariant())) && ( @@ -23,7 +25,10 @@ public static bool IsProxiable(this MethodInfo method) public static bool ShouldBeProxiable(this MethodInfo method) { // to use only for real methods (no getter/setter) - return (method.DeclaringType != typeof (MarshalByRefObject)) && + return +#if FEATURE_REMOTING + (method.DeclaringType != typeof (MarshalByRefObject)) && +#endif (method.DeclaringType != typeof (object) || !"finalize".Equals(method.Name.ToLowerInvariant())) && (!(method.DeclaringType == typeof (object) && "GetType".Equals(method.Name))) && (!(method.DeclaringType == typeof (object) && "obj_address".Equals(method.Name))) && // Mono-specific method @@ -48,4 +53,4 @@ private static bool IsDisposeMethod(MethodInfo method) // return method.Name.Equals("Dispose") && method.IsMethodOf(typeof(IDisposable)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynProxyTypeValidator.cs b/src/NHibernate/Proxy/DynProxyTypeValidator.cs index 03107f52b76..ae18238c6a5 100644 --- a/src/NHibernate/Proxy/DynProxyTypeValidator.cs +++ b/src/NHibernate/Proxy/DynProxyTypeValidator.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using System.Reflection; using NHibernate.Util; @@ -19,7 +20,7 @@ public class DynProxyTypeValidator : IProxyValidator public ICollection ValidateType(System.Type type) { errors.Clear(); - if (type.IsInterface) + if (type.GetTypeInfo().IsInterface) { // Any interface is valid as a proxy return null; @@ -122,4 +123,4 @@ protected void CheckNotSealed(System.Type type) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs index 95f1abda41f..0b85f21ffaf 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs @@ -63,7 +63,7 @@ public void PushArguments(ParameterInfo[] methodParameters, ILGenerator IL, bool IL.Emit(ldindInstruction); } - if (parameterType.IsValueType || param.ParameterType.IsByRef || parameterType.IsGenericParameter) + if (parameterType.GetTypeInfo().IsValueType || param.ParameterType.IsByRef || parameterType.IsGenericParameter) { IL.Emit(OpCodes.Box, parameterType); } @@ -78,4 +78,4 @@ public void PushArguments(ParameterInfo[] methodParameters, ILGenerator IL, bool #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs index 10449185a78..685f782ff59 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs @@ -8,6 +8,7 @@ using System; using System.Diagnostics; +using System.Linq; using System.Reflection; using System.Reflection.Emit; @@ -189,7 +190,7 @@ private static void PushTargetMethodInfo(ILGenerator IL, MethodBuilder generated } System.Type declaringType = method.DeclaringType; - if (declaringType.IsGenericType) + if (declaringType.GetTypeInfo().IsGenericType) { IL.Emit(OpCodes.Ldtoken, declaringType); IL.Emit(OpCodes.Call, getGenericMethodFromHandle); @@ -250,4 +251,4 @@ private void PackageReturnType(MethodInfo method, ILGenerator IL) IL.Emit(OpCodes.Unbox_Any, returnType); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs index a88f78034e8..6cde5e77a6a 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs @@ -6,19 +6,24 @@ namespace NHibernate.Proxy.DynamicProxy { public class DefaultProxyAssemblyBuilder : IProxyAssemblyBuilder { - public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) + public AssemblyBuilder DefineDynamicAssembly(AssemblyName name) { +#if FEATURE_APPDOMAIN || NET_4_0 #if DEBUG AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; #else AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; #endif + AppDomain appDomain = AppDomain.CurrentDomain; return appDomain.DefineDynamicAssembly(name, access); +#else + return AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); +#endif } public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName) { -#if DEBUG +#if DEBUG && FEATURE_APPDOMAIN ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", moduleName), true); #else diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs index 2c7ad337029..e4b3dc3fb65 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs @@ -60,17 +60,17 @@ private static MethodBuilder GenerateMethodSignature(string name, MethodInfo met var typeArgBuilder = typeArgBuilders[index]; var typeArg = typeArgs[index]; - typeArgBuilder.SetGenericParameterAttributes(typeArg.GenericParameterAttributes); + typeArgBuilder.SetGenericParameterAttributes(typeArg.GetTypeInfo().GenericParameterAttributes); // Copy generic parameter constraints (class and interfaces). - var typeConstraints = typeArg.GetGenericParameterConstraints() + var typeConstraints = typeArg.GetTypeInfo().GetGenericParameterConstraints() .Select(x => ResolveTypeConstraint(method, x)) .ToArray(); - var baseTypeConstraint = typeConstraints.SingleOrDefault(x => x.IsClass); + var baseTypeConstraint = typeConstraints.SingleOrDefault(x => x.GetTypeInfo().IsClass); typeArgBuilder.SetBaseTypeConstraint(baseTypeConstraint); - var interfaceTypeConstraints = typeConstraints.Where(x => !x.IsClass).ToArray(); + var interfaceTypeConstraints = typeConstraints.Where(x => !x.GetTypeInfo().IsClass).ToArray(); typeArgBuilder.SetInterfaceConstraints(interfaceTypeConstraints); } } @@ -79,10 +79,10 @@ private static MethodBuilder GenerateMethodSignature(string name, MethodInfo met private static System.Type ResolveTypeConstraint(MethodInfo method, System.Type typeConstraint) { - if (typeConstraint != null && typeConstraint.IsGenericType) + if (typeConstraint != null && typeConstraint.GetTypeInfo().IsGenericType) { var declaringType = method.DeclaringType; - if (declaringType != null && declaringType.IsGenericType) + if (declaringType != null && declaringType.GetTypeInfo().IsGenericType) { return BuildTypeConstraint(typeConstraint, declaringType); } @@ -143,4 +143,4 @@ public void CreateProxiedMethod(FieldInfo field, MethodInfo method, TypeBuilder MethodBodyEmitter.EmitMethodBody(proxyMethod, callbackMethod, method, field); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/IProxyAssemblyBuilder.cs b/src/NHibernate/Proxy/DynamicProxy/IProxyAssemblyBuilder.cs index 92e458b727b..fc662fbed49 100644 --- a/src/NHibernate/Proxy/DynamicProxy/IProxyAssemblyBuilder.cs +++ b/src/NHibernate/Proxy/DynamicProxy/IProxyAssemblyBuilder.cs @@ -6,7 +6,7 @@ namespace NHibernate.Proxy.DynamicProxy { public interface IProxyAssemblyBuilder { - AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name); + AssemblyBuilder DefineDynamicAssembly(AssemblyName name); ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName); void Save(AssemblyBuilder assemblyBuilder); } diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs index 9ec0cbfc2f6..ad4ec96e27c 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs @@ -11,7 +11,10 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Proxy.DynamicProxy { @@ -20,6 +23,7 @@ public sealed class ProxyFactory private static readonly ConstructorInfo defaultBaseConstructor = typeof(object).GetConstructor(new System.Type[0]); private static readonly MethodInfo getTypeFromHandle = typeof(System.Type).GetMethod("GetTypeFromHandle"); +#if FEATURE_SERIALIZATION private static readonly MethodInfo getValue = typeof (SerializationInfo).GetMethod("GetValue", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(string), typeof(System.Type) }, null); @@ -27,6 +31,7 @@ public sealed class ProxyFactory private static readonly MethodInfo addValue = typeof (SerializationInfo).GetMethod("AddValue", BindingFlags.Public | BindingFlags.Instance, null, new[] {typeof (string), typeof (object)}, null); +#endif public ProxyFactory() : this(new DefaultyProxyMethodBuilder()) {} @@ -92,13 +97,12 @@ public System.Type CreateProxyType(System.Type baseType, params System.Type[] in private System.Type CreateUncachedProxyType(System.Type baseType, System.Type[] baseInterfaces) { - AppDomain currentDomain = AppDomain.CurrentDomain; string typeName = string.Format("{0}Proxy", baseType.Name); string assemblyName = string.Format("{0}Assembly", typeName); string moduleName = string.Format("{0}Module", typeName); var name = new AssemblyName(assemblyName); - AssemblyBuilder assemblyBuilder = ProxyAssemblyBuilder.DefineDynamicAssembly(currentDomain, name); + AssemblyBuilder assemblyBuilder = ProxyAssemblyBuilder.DefineDynamicAssembly(name); ModuleBuilder moduleBuilder = ProxyAssemblyBuilder.DefineDynamicModule(assemblyBuilder, moduleName); TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | @@ -110,7 +114,7 @@ private System.Type CreateUncachedProxyType(System.Type baseType, System.Type[] // Use the proxy dummy as the base type // since we're not inheriting from any class type System.Type parentType = baseType; - if (baseType.IsInterface) + if (baseType.GetTypeInfo().IsInterface) { parentType = typeof (ProxyDummy); interfaces.Add(baseType); @@ -123,8 +127,10 @@ private System.Type CreateUncachedProxyType(System.Type baseType, System.Type[] interfaces.Merge(GetInterfaces(interfaceType)); } +#if FEATURE_SERIALIZATION // Add the ISerializable interface so that it can be implemented interfaces.Add(typeof (ISerializable)); +#endif TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaces.ToArray()); @@ -138,14 +144,21 @@ private System.Type CreateUncachedProxyType(System.Type baseType, System.Type[] // Provide a custom implementation of ISerializable // instead of redirecting it back to the interceptor - foreach (MethodInfo method in GetProxiableMethods(baseType, interfaces).Where(method => method.DeclaringType != typeof(ISerializable))) + foreach (MethodInfo method in GetProxiableMethods(baseType, interfaces) +#if FEATURE_SERIALIZATION + .Where(method => method.DeclaringType != typeof(ISerializable)) +#endif + ) { ProxyMethodBuilder.CreateProxiedMethod(interceptorField, method, typeBuilder); } +#if FEATURE_SERIALIZATION // Make the proxy serializable AddSerializationSupport(baseType, baseInterfaces, typeBuilder, interceptorField, defaultConstructor); - System.Type proxyType = typeBuilder.CreateType(); +#endif + + System.Type proxyType = typeBuilder.CreateTypeInfo().AsType(); ProxyAssemblyBuilder.Save(assemblyBuilder); return proxyType; @@ -206,6 +219,7 @@ private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, Sys return constructor; } +#if FEATURE_SERIALIZATION private static void ImplementGetObjectData(System.Type baseType, System.Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField) { const MethodAttributes attributes = MethodAttributes.Public | MethodAttributes.HideBySig | @@ -303,5 +317,6 @@ private static void AddSerializationSupport(System.Type baseType, System.Type[] DefineSerializationConstructor(typeBuilder, interceptorField, defaultConstructor); ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs index 4b6f99d2f30..7ffd028edf1 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs @@ -6,6 +6,8 @@ #endregion +#if FEATURE_SERIALIZATION + using System; using System.Collections.Generic; using System.Runtime.Serialization; @@ -46,7 +48,7 @@ protected ProxyObjectReference(SerializationInfo info, StreamingContext context) _proxy = (IProxy) Activator.CreateInstance(proxyType, args); } - #region IObjectReference Members +#region IObjectReference Members [SecurityCritical] public object GetRealObject(StreamingContext context) @@ -54,13 +56,15 @@ public object GetRealObject(StreamingContext context) return _proxy; } - #endregion +#endregion - #region ISerializable Members +#region ISerializable Members [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) {} - #endregion +#endregion } } + +#endif diff --git a/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs b/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs index 8c7aed84af4..e76a0149a0e 100644 --- a/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs +++ b/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs @@ -1,11 +1,14 @@ using System; using System.Collections; using System.Reflection; -using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.Type; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Proxy.Poco { /// Lazy initializer for POCOs @@ -32,6 +35,7 @@ protected internal BasicLazyInitializer(string entityName, System.Type persisten this.overridesEquals = overridesEquals; } +#if FEATURE_SERIALIZATION /// /// Adds all of the information into the SerializationInfo that is needed to /// reconstruct the proxy during deserialization or to replace the proxy @@ -44,6 +48,7 @@ protected internal BasicLazyInitializer(string entityName, System.Type persisten protected virtual void AddSerializationInfo(SerializationInfo info, StreamingContext context) { } +#endif public override System.Type PersistentClass { @@ -99,6 +104,7 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) return InvokeImplementation; } } +#if FEATURE_SERIALIZATION else if (paramCount == 2) { // if the Proxy Engine delegates the call of GetObjectData to the Initializer @@ -125,6 +131,7 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) return null; } } +#endif //if it is a property of an embedded component, invoke on the "identifier" if (componentIdType != null && componentIdType.IsMethodOf(method)) diff --git a/src/NHibernate/QueryException.cs b/src/NHibernate/QueryException.cs index 5d3c33476ab..40422a2eee6 100644 --- a/src/NHibernate/QueryException.cs +++ b/src/NHibernate/QueryException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -9,7 +11,11 @@ namespace NHibernate /// A problem occurred translating a Hibernate query to SQL due to invalid query syntax, etc. /// [Serializable] - public class QueryException : HibernateException, ISerializable + public class QueryException + : HibernateException +#if FEATURE_SERIALIZATION + , ISerializable +#endif { private string queryString; @@ -84,6 +90,7 @@ public override string Message } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -121,5 +128,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/QueryParameterException.cs b/src/NHibernate/QueryParameterException.cs index 959ab847de4..d3b58a7ce7a 100644 --- a/src/NHibernate/QueryParameterException.cs +++ b/src/NHibernate/QueryParameterException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -9,6 +12,8 @@ public class QueryParameterException : QueryException // TODO : without default constructor can't be serialized public QueryParameterException(string message) : base(message) { } public QueryParameterException(string message, Exception inner) : base(message, inner) { } +#if FEATURE_SERIALIZATION protected QueryParameterException(SerializationInfo info,StreamingContext context): base(info, context) { } +#endif } } diff --git a/src/NHibernate/SessionException.cs b/src/NHibernate/SessionException.cs index 96ce8ccc697..403265bf27a 100644 --- a/src/NHibernate/SessionException.cs +++ b/src/NHibernate/SessionException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -11,9 +14,11 @@ public SessionException(string message) { } +#if FEATURE_SERIALIZATION protected SessionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } } diff --git a/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs b/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs index e7b9a6065e3..43c55a584a8 100644 --- a/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs +++ b/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs @@ -134,7 +134,7 @@ private IEnumerable ParseColumnDefinitions(IEnumerator ParseColumnDefinitions(IEnumerator ParseColumnDefinitions(IEnumerator ParseOrderDefinitions(IEnumerator case SqlTokenType.Text: if (blockLevel != 0) break; - if (token.Equals("asc", StringComparison.InvariantCultureIgnoreCase) - || token.Equals("desc", StringComparison.InvariantCultureIgnoreCase)) + if (token.Equals("asc", StringComparison.OrdinalIgnoreCase) + || token.Equals("desc", StringComparison.OrdinalIgnoreCase)) { orderEndToken = prevToken; directionToken = token; @@ -272,7 +272,7 @@ private IEnumerable ParseOrderDefinitions(IEnumerator private OrderDefinition ParseOrderDefinition(SqlToken beginToken, SqlToken endToken, SqlToken directionToken) { var isDescending = directionToken != null && - directionToken.Equals("desc", StringComparison.InvariantCultureIgnoreCase); + directionToken.Equals("desc", StringComparison.OrdinalIgnoreCase); var columnNameOrIndex = beginToken == endToken ? beginToken.Value @@ -301,8 +301,8 @@ private bool TryGetColumnDefinition(string columnNameOrIndex, out ColumnDefiniti foreach (var column in _columns) { - if (columnNameOrIndex.Equals(column.Name, StringComparison.InvariantCultureIgnoreCase) - || columnNameOrIndex.Equals(column.Alias, StringComparison.InvariantCultureIgnoreCase)) + if (columnNameOrIndex.Equals(column.Name, StringComparison.OrdinalIgnoreCase) + || columnNameOrIndex.Equals(column.Alias, StringComparison.OrdinalIgnoreCase)) { result = column; return true; @@ -316,9 +316,9 @@ private bool TryGetColumnDefinition(string columnNameOrIndex, out ColumnDefiniti var text = Sql.ToString(sqlIndex, sqlLength); foreach (var column in _columns) { - if (text.Equals(column.Name, StringComparison.InvariantCultureIgnoreCase) || - text.Equals(column.Alias, StringComparison.InvariantCultureIgnoreCase) || - text.Equals(Sql.ToString(column.SqlIndex, column.SqlLength), StringComparison.InvariantCultureIgnoreCase)) + if (text.Equals(column.Name, StringComparison.OrdinalIgnoreCase) || + text.Equals(column.Alias, StringComparison.OrdinalIgnoreCase) || + text.Equals(Sql.ToString(column.SqlIndex, column.SqlLength), StringComparison.OrdinalIgnoreCase)) { result = column; return true; diff --git a/src/NHibernate/SqlCommand/Parser/SqlTokenizerExtensions.cs b/src/NHibernate/SqlCommand/Parser/SqlTokenizerExtensions.cs index 48ad9849147..3025dea2c33 100644 --- a/src/NHibernate/SqlCommand/Parser/SqlTokenizerExtensions.cs +++ b/src/NHibernate/SqlCommand/Parser/SqlTokenizerExtensions.cs @@ -22,7 +22,7 @@ public static bool TryParseUntil(this IEnumerator tokenEnum, string ke nestLevel--; break; case SqlTokenType.Text: - if (nestLevel == 0 && token.Equals(keyword, StringComparison.InvariantCultureIgnoreCase)) return true; + if (nestLevel == 0 && token.Equals(keyword, StringComparison.OrdinalIgnoreCase)) return true; break; } } @@ -49,18 +49,18 @@ public static bool TryParseUntilFirstMsSqlSelectColumn(this IEnumerator toke orderToken = tokenEnum.Current; if (tokenEnum.MoveNext()) { - return tokenEnum.Current.Equals("by", StringComparison.InvariantCultureIgnoreCase) + return tokenEnum.Current.Equals("by", StringComparison.OrdinalIgnoreCase) ? tokenEnum.MoveNext() : false; } diff --git a/src/NHibernate/SqlCommand/SqlString.cs b/src/NHibernate/SqlCommand/SqlString.cs index f81547a134b..615ec754f6c 100644 --- a/src/NHibernate/SqlCommand/SqlString.cs +++ b/src/NHibernate/SqlCommand/SqlString.cs @@ -382,7 +382,7 @@ public bool EndsWith(string value) { return value != null && value.Length <= _length - && IndexOf(value, _length - value.Length, value.Length, StringComparison.InvariantCulture) >= 0; + && IndexOf(value, _length - value.Length, value.Length, StringComparison.Ordinal) >= 0; } public bool EndsWithCaseInsensitive(string value) @@ -416,7 +416,7 @@ public int GetParameterCount() /// if not found. public int IndexOfCaseInsensitive(string text) { - return IndexOf(text, 0, _length, StringComparison.InvariantCultureIgnoreCase); + return IndexOf(text, 0, _length, StringComparison.OrdinalIgnoreCase); } /// @@ -488,7 +488,7 @@ public SqlString Insert(int index, SqlString sql) /// if not found. public int LastIndexOfCaseInsensitive(string text) { - return LastIndexOf(text, 0, _length, StringComparison.InvariantCultureIgnoreCase); + return LastIndexOf(text, 0, _length, StringComparison.OrdinalIgnoreCase); } /// @@ -583,7 +583,7 @@ private IEnumerable SplitParts(string splitter) var startIndex = 0; while (startIndex < _length) { - var splitterIndex = IndexOf(splitter, startIndex, _length - startIndex, StringComparison.InvariantCultureIgnoreCase); + var splitterIndex = IndexOf(splitter, startIndex, _length - startIndex, StringComparison.OrdinalIgnoreCase); if (splitterIndex < 0) break; yield return new SqlString(this, _sqlStartIndex + startIndex, splitterIndex - startIndex); @@ -606,7 +606,7 @@ public bool StartsWithCaseInsensitive(string value) { return value != null && value.Length <= _length - && IndexOf(value, 0, value.Length, StringComparison.InvariantCultureIgnoreCase) >= 0; + && IndexOf(value, 0, value.Length, StringComparison.OrdinalIgnoreCase) >= 0; } /// @@ -619,7 +619,7 @@ public bool EqualsCaseInsensitive(string value) { return value != null && value.Length == _length - && IndexOf(value, 0, value.Length, StringComparison.InvariantCultureIgnoreCase) >= 0; + && IndexOf(value, 0, value.Length, StringComparison.OrdinalIgnoreCase) >= 0; } /// @@ -1046,4 +1046,4 @@ public override string ToString() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/SqlTypes/SqlTypeFactory.cs b/src/NHibernate/SqlTypes/SqlTypeFactory.cs index 290d4472f5a..e9584ba165c 100644 --- a/src/NHibernate/SqlTypes/SqlTypeFactory.cs +++ b/src/NHibernate/SqlTypes/SqlTypeFactory.cs @@ -11,6 +11,8 @@ namespace NHibernate.SqlTypes [Serializable] public static class SqlTypeFactory { + private static readonly object StaticSyncRoot = new object(); + // key = typeof(sqlType).Name : ie - BinarySqlType(l), BooleanSqlType, DecimalSqlType(p,s) // value = SqlType private static readonly ConcurrentDictionary SqlTypes = @@ -79,10 +81,12 @@ public static StringClobSqlType GetStringClob(int length) return GetTypeWithLen(length, l => new StringClobSqlType(l)); } - [MethodImpl(MethodImplOptions.Synchronized)] public static SqlType GetSqlType(DbType dbType, byte precision, byte scale) { - return GetTypeWithPrecision(dbType, precision, scale); + lock (StaticSyncRoot) + { + return GetTypeWithPrecision(dbType, precision, scale); + } } private static string GetKeyForLengthBased(string name, int length) diff --git a/src/NHibernate/StaleObjectStateException.cs b/src/NHibernate/StaleObjectStateException.cs index 9cd865cb323..aa2f42a3a96 100644 --- a/src/NHibernate/StaleObjectStateException.cs +++ b/src/NHibernate/StaleObjectStateException.cs @@ -1,8 +1,10 @@ using System; +using NHibernate.Impl; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; -using NHibernate.Impl; +#endif namespace NHibernate { @@ -57,6 +59,7 @@ public override string Message } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -96,5 +99,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/StaleStateException.cs b/src/NHibernate/StaleStateException.cs index 8916a2ca520..1c87adbd0b6 100644 --- a/src/NHibernate/StaleStateException.cs +++ b/src/NHibernate/StaleStateException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -10,9 +13,11 @@ public StaleStateException(string message) : base(message) { } +#if FEATURE_SERIALIZATION protected StaleStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Stat/StatisticsImpl.cs b/src/NHibernate/Stat/StatisticsImpl.cs index 68c4d014490..db101ad9703 100644 --- a/src/NHibernate/Stat/StatisticsImpl.cs +++ b/src/NHibernate/Stat/StatisticsImpl.cs @@ -305,7 +305,6 @@ public long OptimisticFailureCount get { return optimisticFailureCount; } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Clear() { lock (SyncRoot) @@ -355,7 +354,6 @@ public void Clear() } } - [MethodImpl(MethodImplOptions.Synchronized)] public EntityStatistics GetEntityStatistics(string entityName) { lock (SyncRoot) @@ -370,7 +368,6 @@ public EntityStatistics GetEntityStatistics(string entityName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public CollectionStatistics GetCollectionStatistics(string role) { lock (SyncRoot) @@ -385,7 +382,6 @@ public CollectionStatistics GetCollectionStatistics(string role) } } - [MethodImpl(MethodImplOptions.Synchronized)] public SecondLevelCacheStatistics GetSecondLevelCacheStatistics(string regionName) { lock (SyncRoot) @@ -406,7 +402,6 @@ public SecondLevelCacheStatistics GetSecondLevelCacheStatistics(string regionNam } } - [MethodImpl(MethodImplOptions.Synchronized)] public QueryStatistics GetQueryStatistics(string queryString) { lock (SyncRoot) @@ -460,7 +455,6 @@ public TimeSpan OperationThreshold { return operationThreshold; } - [MethodImpl(MethodImplOptions.Synchronized)] set { lock (SyncRoot) @@ -474,7 +468,6 @@ public TimeSpan OperationThreshold #region IStatisticsImplementor Members - [MethodImpl(MethodImplOptions.Synchronized)] public void OpenSession() { lock (SyncRoot) @@ -483,7 +476,6 @@ public void OpenSession() } } - [MethodImpl(MethodImplOptions.Synchronized)] public void CloseSession() { lock (SyncRoot) @@ -492,7 +484,6 @@ public void CloseSession() } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Flush() { lock (SyncRoot) @@ -501,7 +492,6 @@ public void Flush() } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Connect() { lock (SyncRoot) @@ -510,7 +500,6 @@ public void Connect() } } - [MethodImpl(MethodImplOptions.Synchronized)] public void LoadEntity(string entityName, TimeSpan time) { lock (SyncRoot) @@ -524,7 +513,6 @@ public void LoadEntity(string entityName, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void FetchEntity(string entityName, TimeSpan time) { lock (SyncRoot) @@ -538,7 +526,6 @@ public void FetchEntity(string entityName, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void UpdateEntity(string entityName, TimeSpan time) { lock (SyncRoot) @@ -552,7 +539,6 @@ public void UpdateEntity(string entityName, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void InsertEntity(string entityName, TimeSpan time) { lock (SyncRoot) @@ -566,7 +552,6 @@ public void InsertEntity(string entityName, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void DeleteEntity(string entityName, TimeSpan time) { lock (SyncRoot) @@ -580,7 +565,6 @@ public void DeleteEntity(string entityName, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void LoadCollection(string role, TimeSpan time) { lock (SyncRoot) @@ -594,7 +578,6 @@ public void LoadCollection(string role, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void FetchCollection(string role, TimeSpan time) { lock (SyncRoot) @@ -608,7 +591,6 @@ public void FetchCollection(string role, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void UpdateCollection(string role, TimeSpan time) { lock (SyncRoot) @@ -622,7 +604,6 @@ public void UpdateCollection(string role, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void RecreateCollection(string role, TimeSpan time) { lock (SyncRoot) @@ -636,7 +617,6 @@ public void RecreateCollection(string role, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void RemoveCollection(string role, TimeSpan time) { lock (SyncRoot) @@ -650,7 +630,6 @@ public void RemoveCollection(string role, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void SecondLevelCachePut(string regionName) { lock (SyncRoot) @@ -664,7 +643,6 @@ public void SecondLevelCachePut(string regionName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void SecondLevelCacheHit(string regionName) { lock (SyncRoot) @@ -678,7 +656,6 @@ public void SecondLevelCacheHit(string regionName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void SecondLevelCacheMiss(string regionName) { lock (SyncRoot) @@ -692,7 +669,6 @@ public void SecondLevelCacheMiss(string regionName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void QueryExecuted(string hql, int rows, TimeSpan time) { lock (SyncRoot) @@ -715,7 +691,6 @@ public void QueryExecuted(string hql, int rows, TimeSpan time) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void QueryCacheHit(string hql, string regionName) { lock (SyncRoot) @@ -734,7 +709,6 @@ public void QueryCacheHit(string hql, string regionName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void QueryCacheMiss(string hql, string regionName) { lock (SyncRoot) @@ -753,7 +727,6 @@ public void QueryCacheMiss(string hql, string regionName) } } - [MethodImpl(MethodImplOptions.Synchronized)] public void QueryCachePut(string hql, string regionName) { lock (SyncRoot) diff --git a/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs b/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs index 50a96ebc27d..dc83e0300e6 100644 --- a/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs +++ b/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections.Generic; using System.Data; @@ -80,7 +82,7 @@ public ITableMetadata GetTableMetadata(string name, string schema, string catalo foreach (DataRow tableRow in rows) { string tableName = Convert.ToString(tableRow[meta.ColumnNameForTableName]); - if (name.Equals(tableName, StringComparison.InvariantCultureIgnoreCase)) + if (name.Equals(tableName, StringComparison.OrdinalIgnoreCase)) { table = meta.GetTableMetadata(tableRow, extras); tables[identifier] = table; @@ -170,3 +172,5 @@ public override String ToString() } } } + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/IConnectionHelper.cs b/src/NHibernate/Tool/hbm2ddl/IConnectionHelper.cs index 30882900c91..3993d6b1fcb 100644 --- a/src/NHibernate/Tool/hbm2ddl/IConnectionHelper.cs +++ b/src/NHibernate/Tool/hbm2ddl/IConnectionHelper.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Data.Common; namespace NHibernate.Tool.hbm2ddl @@ -24,3 +26,5 @@ public interface IConnectionHelper } } + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/ManagedProviderConnectionHelper.cs b/src/NHibernate/Tool/hbm2ddl/ManagedProviderConnectionHelper.cs index 9d45c84d810..b9424a7dcd0 100644 --- a/src/NHibernate/Tool/hbm2ddl/ManagedProviderConnectionHelper.cs +++ b/src/NHibernate/Tool/hbm2ddl/ManagedProviderConnectionHelper.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Collections.Generic; using System.Data.Common; using NHibernate.Connection; @@ -40,3 +42,5 @@ public void Release() } } } + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs b/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs index 742653c698b..e458f9d90e6 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections.Generic; using System.Data; @@ -298,7 +300,7 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Db { try { - exportOutput.Close(); + exportOutput.Dispose(); } catch (Exception ioe) { @@ -347,7 +349,7 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Te { if (fileOutput == null && outputFile != null) { - fileOutput = new StreamWriter(outputFile); + fileOutput = new StreamWriter(File.OpenWrite(outputFile)); } if (execute) @@ -392,4 +394,6 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Te } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaMetadataUpdater.cs b/src/NHibernate/Tool/hbm2ddl/SchemaMetadataUpdater.cs index 0b4b760f305..12f00583897 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaMetadataUpdater.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaMetadataUpdater.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using NHibernate.Cfg; using NHibernate.Engine; using NHibernate.Mapping; @@ -75,4 +77,6 @@ private static string GetNhQuoted(string name) return "`" + name + "`"; } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs b/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs index 6224e13e2d0..97b2e535d6d 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections.Generic; using System.Data.Common; @@ -220,4 +222,6 @@ public void Execute(Action scriptAction, bool doUpdate) } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs b/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs index 3f3c5a36853..bfda0d9e94e 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections.Generic; using System.Data.Common; @@ -127,4 +129,6 @@ public void Validate() } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/ScriptSplitter.cs b/src/NHibernate/Tool/hbm2ddl/ScriptSplitter.cs index a67fa223e50..7b23897f460 100644 --- a/src/NHibernate/Tool/hbm2ddl/ScriptSplitter.cs +++ b/src/NHibernate/Tool/hbm2ddl/ScriptSplitter.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System; using System.Collections; using System.Collections.Generic; @@ -403,3 +405,5 @@ protected override bool ReadNext() } } } + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionHelper.cs b/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionHelper.cs index 9b93f3f8bef..1a13ba77f0a 100644 --- a/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionHelper.cs +++ b/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionHelper.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Data.Common; namespace NHibernate.Tool.hbm2ddl @@ -30,3 +32,5 @@ public void Release() } } } + +#endif diff --git a/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.cs b/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.cs index 4d71d8b104d..ea3f6ac9480 100644 --- a/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.cs +++ b/src/NHibernate/Tool/hbm2ddl/SuppliedConnectionProviderConnectionHelper.cs @@ -1,3 +1,5 @@ +#if FEATURE_DATA_GETSCHEMATABLE + using System.Data.Common; using NHibernate.Connection; @@ -39,3 +41,5 @@ public void Release() } } } + +#endif diff --git a/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs b/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs index 2290996dd6c..f9501315df3 100644 --- a/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs +++ b/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs @@ -1,3 +1,5 @@ +#if FEATURE_SYSTEM_TRANSACTIONS + using System; using System.Collections; using System.Transactions; @@ -181,4 +183,6 @@ public void Dispose() } } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Transaction/ITransactionFactory.cs b/src/NHibernate/Transaction/ITransactionFactory.cs index 45368db661e..0f8de99bf35 100644 --- a/src/NHibernate/Transaction/ITransactionFactory.cs +++ b/src/NHibernate/Transaction/ITransactionFactory.cs @@ -1,7 +1,4 @@ using System.Collections; -using System.Transactions; -using NHibernate; -using NHibernate.AdoNet; using NHibernate.Engine; using NHibernate.Engine.Transaction; @@ -34,4 +31,4 @@ public interface ITransactionFactory void ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, bool transacted); } -} \ No newline at end of file +} diff --git a/src/NHibernate/TransactionException.cs b/src/NHibernate/TransactionException.cs index e5964844593..09212e50657 100644 --- a/src/NHibernate/TransactionException.cs +++ b/src/NHibernate/TransactionException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -30,6 +33,7 @@ public TransactionException(string message, Exception innerException) : base(mes { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -44,5 +48,6 @@ public TransactionException(string message, Exception innerException) : base(mes protected TransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Transform/AliasToBeanResultTransformer.cs b/src/NHibernate/Transform/AliasToBeanResultTransformer.cs index 8190b59147a..2de435c2e98 100644 --- a/src/NHibernate/Transform/AliasToBeanResultTransformer.cs +++ b/src/NHibernate/Transform/AliasToBeanResultTransformer.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Linq; using System.Reflection; using NHibernate.Properties; @@ -45,7 +46,7 @@ public AliasToBeanResultTransformer(System.Type resultClass) // if resultClass is a ValueType (struct), GetConstructor will return null... // in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances - if (constructor == null && resultClass.IsClass) + if (constructor == null && resultClass.GetTypeInfo().IsClass) { throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor", "resultClass"); @@ -90,7 +91,7 @@ public override object TransformTuple(object[] tuple, String[] aliases) } // if resultClass is not a class but a value type, we need to use Activator.CreateInstance - result = resultClass.IsClass + result = resultClass.GetTypeInfo().IsClass ? constructor.Invoke(null) : Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(resultClass, true); @@ -142,4 +143,4 @@ public override int GetHashCode() return resultClass.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/TransientObjectException.cs b/src/NHibernate/TransientObjectException.cs index eb55554248e..1b499fb20a6 100644 --- a/src/NHibernate/TransientObjectException.cs +++ b/src/NHibernate/TransientObjectException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -18,6 +21,7 @@ public TransientObjectException(string message) : base(message) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -32,5 +36,6 @@ public TransientObjectException(string message) : base(message) protected TransientObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Tuple/Component/ComponentEntityModeToTuplizerMapping.cs b/src/NHibernate/Tuple/Component/ComponentEntityModeToTuplizerMapping.cs index 4734e508a75..b2f0854fdd7 100644 --- a/src/NHibernate/Tuple/Component/ComponentEntityModeToTuplizerMapping.cs +++ b/src/NHibernate/Tuple/Component/ComponentEntityModeToTuplizerMapping.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using NHibernate.Mapping; using NHibernate.Util; @@ -85,7 +86,7 @@ private IComponentTuplizer BuildComponentTuplizer(string tuplizerImpl, Mapping.C try { System.Type implClass = ReflectHelper.ClassForName(tuplizerImpl); - return (IComponentTuplizer)implClass.GetConstructor(componentTuplizerCTORSignature).Invoke(new object[] { component }); + return (IComponentTuplizer)implClass.GetTypeInfo().GetConstructor(componentTuplizerCTORSignature).Invoke(new object[] { component }); } catch (Exception t) { diff --git a/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs b/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs index e94b6afc265..113d3362885 100644 --- a/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs +++ b/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs @@ -3,9 +3,12 @@ using NHibernate.Intercept; using NHibernate.Properties; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Tuple.Component { - using System.Runtime.Serialization; /// /// A specific to the POCO entity mode. @@ -20,6 +23,7 @@ public class PocoComponentTuplizer : AbstractComponentTuplizer private IReflectionOptimizer optimizer; +#if FEATURE_SERIALIZATION [OnDeserialized] internal void OnDeserialized(StreamingContext context) { @@ -34,6 +38,7 @@ internal void OnDeserialized(StreamingContext context) ClearOptimizerWhenUsingCustomAccessors(); } +#endif public PocoComponentTuplizer(Mapping.Component component) : base(component) diff --git a/src/NHibernate/Tuple/Entity/EntityEntityModeToTuplizerMapping.cs b/src/NHibernate/Tuple/Entity/EntityEntityModeToTuplizerMapping.cs index a669454e015..c22137a0637 100644 --- a/src/NHibernate/Tuple/Entity/EntityEntityModeToTuplizerMapping.cs +++ b/src/NHibernate/Tuple/Entity/EntityEntityModeToTuplizerMapping.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using NHibernate.Mapping; using NHibernate.Util; diff --git a/src/NHibernate/Tuple/Entity/EntityMetamodel.cs b/src/NHibernate/Tuple/Entity/EntityMetamodel.cs index 7e11bd4950b..09f0efa1f50 100644 --- a/src/NHibernate/Tuple/Entity/EntityMetamodel.cs +++ b/src/NHibernate/Tuple/Entity/EntityMetamodel.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using System.Runtime.CompilerServices; using NHibernate.Engine; diff --git a/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs b/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs index 2a08fff77a6..6020b101870 100644 --- a/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs +++ b/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs @@ -11,7 +11,10 @@ using NHibernate.Proxy; using NHibernate.Type; using NHibernate.Util; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Tuple.Entity { @@ -30,6 +33,7 @@ public class PocoEntityTuplizer : AbstractEntityTuplizer private IReflectionOptimizer optimizer; private readonly IProxyValidator proxyValidator; +#if FEATURE_SERIALIZATION [OnDeserialized] internal void OnDeserialized(StreamingContext context) { @@ -43,6 +47,8 @@ internal void OnDeserialized(StreamingContext context) ClearOptimizerWhenUsingCustomAccessors(); } +#endif + protected void SetReflectionOptimizer() { if (Cfg.Environment.UseReflectionOptimizer) @@ -134,7 +140,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass persistentCla if (_proxyInterface != null && !_mappedClass.Equals(_proxyInterface)) { - if (!_proxyInterface.IsInterface) + if (!_proxyInterface.GetTypeInfo().IsInterface) { throw new MappingException("proxy must be either an interface, or the class itself: " + EntityName); } @@ -142,7 +148,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass persistentCla proxyInterfaces.Add(_proxyInterface); } - if (_mappedClass.IsInterface) + if (_mappedClass.GetTypeInfo().IsInterface) { needAccesorCheck = false; // NH (the mapped class is an interface all properties can be overridden) proxyInterfaces.Add(_mappedClass); @@ -154,7 +160,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass persistentCla System.Type subclassClass = subclass.MappedClass; if (subclassProxy != null && !subclassClass.Equals(subclassProxy)) { - if (!subclassProxy.IsInterface) + if (!subclassProxy.GetTypeInfo().IsInterface) { throw new MappingException("proxy must be either an interface, or the class itself: " + subclass.EntityName); } diff --git a/src/NHibernate/Tuple/EntityModeToTuplizerMapping.cs b/src/NHibernate/Tuple/EntityModeToTuplizerMapping.cs index 14bf6a83421..0abcdf7eef7 100644 --- a/src/NHibernate/Tuple/EntityModeToTuplizerMapping.cs +++ b/src/NHibernate/Tuple/EntityModeToTuplizerMapping.cs @@ -1,13 +1,19 @@ using System; using System.Collections.Generic; -using System.Runtime.Serialization; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Tuple { /// Centralizes handling of to mappings. [Serializable] - public abstract class EntityModeToTuplizerMapping : IDeserializationCallback + public abstract class EntityModeToTuplizerMapping +#if FEATURE_SERIALIZATION + : IDeserializationCallback +#endif { // NH-1660 @@ -86,14 +92,20 @@ private void EnsureFullyDeserialized() { if (!_isFullyDeserialized) { +#if FEATURE_SERIALIZATION ((IDeserializationCallback) this).OnDeserialization(this); +#else + throw new InvalidOperationException("Should not get here without deserialization"); +#endif } } +#if FEATURE_SERIALIZATION void IDeserializationCallback.OnDeserialization(object sender) { ((IDeserializationCallback) _tuplizers).OnDeserialization(sender); _isFullyDeserialized = true; } +#endif } } diff --git a/src/NHibernate/Tuple/PocoInstantiator.cs b/src/NHibernate/Tuple/PocoInstantiator.cs index 63a5c9ba3a8..31f0b789e2e 100644 --- a/src/NHibernate/Tuple/PocoInstantiator.cs +++ b/src/NHibernate/Tuple/PocoInstantiator.cs @@ -1,17 +1,24 @@ using System; using System.Reflection; -using System.Runtime.Serialization; using NHibernate.Bytecode; using NHibernate.Mapping; using NHibernate.Proxy; using NHibernate.Util; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Tuple { /// Defines a POCO-based instantiator for use from the tuplizers. [Serializable] - public class PocoInstantiator : IInstantiator, IDeserializationCallback + public class PocoInstantiator + : IInstantiator +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(PocoInstantiator)); @@ -101,7 +108,7 @@ private object GetInstance() { return optimizer.CreateInstance(); } - if (mappedClass.IsValueType) + if (mappedClass.GetTypeInfo().IsValueType) { return Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(mappedClass, true); } @@ -126,6 +133,7 @@ public bool IsInstance(object obj) #endregion +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members public void OnDeserialization(object sender) @@ -134,6 +142,7 @@ public void OnDeserialization(object sender) } #endregion +#endif public void SetOptimizer(IInstantiationOptimizer optimizer) { diff --git a/src/NHibernate/Type/AbstractEnumType.cs b/src/NHibernate/Type/AbstractEnumType.cs index 0b6ab128392..55740f2db98 100644 --- a/src/NHibernate/Type/AbstractEnumType.cs +++ b/src/NHibernate/Type/AbstractEnumType.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using System.Text; using NHibernate.SqlTypes; @@ -15,7 +16,7 @@ public abstract class AbstractEnumType : PrimitiveType, IDiscriminatorType protected AbstractEnumType(SqlType sqlType,System.Type enumType) : base(sqlType) { - if (enumType.IsEnum) + if (enumType.GetTypeInfo().IsEnum) { this.enumType = enumType; } diff --git a/src/NHibernate/Type/AnyType.cs b/src/NHibernate/Type/AnyType.cs index fe56fa7840a..496bc93afde 100644 --- a/src/NHibernate/Type/AnyType.cs +++ b/src/NHibernate/Type/AnyType.cs @@ -57,11 +57,13 @@ internal AnyType(IType metaType, IType identifierType) this.metaType = metaType; } +#if FEATURE_SERIALIZATION /// internal AnyType() : this(NHibernateUtil.String, NHibernateUtil.Serializable) { } +#endif public override object DeepCopy(object value, EntityMode entityMode, ISessionFactoryImplementor factory) { diff --git a/src/NHibernate/Type/ByteType.cs b/src/NHibernate/Type/ByteType.cs index 9986348c90b..62b17946710 100644 --- a/src/NHibernate/Type/ByteType.cs +++ b/src/NHibernate/Type/ByteType.cs @@ -78,7 +78,7 @@ public virtual object Seed(ISessionImplementor session) public IComparer Comparator { - get { return Comparer.DefaultInvariant; } + get { return System.Collections.Generic.Comparer.Default; } } public override object DefaultValue @@ -86,4 +86,4 @@ public override object DefaultValue get { return ZERO; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/CoalesceType.cs b/src/NHibernate/Type/CoalesceType.cs new file mode 100644 index 00000000000..76247bb9215 --- /dev/null +++ b/src/NHibernate/Type/CoalesceType.cs @@ -0,0 +1,62 @@ +using System; +using System.Data; +using System.Data.Common; + +namespace NHibernate.Type +{ + /// + /// Handles any type returned from a Coalesce projection + /// + [Serializable] + public class CoalesceType : PrimitiveType + { + public CoalesceType() : base(new SqlTypes.SqlType(DbType.Object)) + { + } + + public override string Name + { + get { return "Coalesce"; } + } + + public override System.Type ReturnedClass + { + get { return typeof(object); } + } + + public override void Set(DbCommand cmd, object value, int index) + { + throw new System.NotImplementedException(); + } + + public override object Get(DbDataReader rs, int index) + { + throw new System.NotImplementedException(); + } + + public override object Get(DbDataReader rs, string name) + { + throw new System.NotImplementedException(); + } + + public override object FromStringValue(string xml) + { + throw new System.NotImplementedException(); + } + + public override System.Type PrimitiveClass + { + get { return typeof(object); } + } + + public override object DefaultValue + { + get { return null; } + } + + public override string ObjectToSQLString(object value, Dialect.Dialect dialect) + { + return value.ToString(); + } + } +} diff --git a/src/NHibernate/Type/CollectionType.cs b/src/NHibernate/Type/CollectionType.cs index 2efa1af9dbc..190d84fe147 100644 --- a/src/NHibernate/Type/CollectionType.cs +++ b/src/NHibernate/Type/CollectionType.cs @@ -10,6 +10,7 @@ using NHibernate.SqlTypes; using NHibernate.Util; using System.Collections.Generic; +using System.Reflection; using NHibernate.Impl; namespace NHibernate.Type @@ -502,7 +503,7 @@ public virtual object GetIdOfOwnerOrNull(object key, ISessionImplementor session IEntityPersister ownerPersister = GetPersister(session).OwnerEntityPersister; // TODO: Fix this so it will work for non-POJO entity mode System.Type ownerMappedClass = ownerPersister.GetMappedClass(session.EntityMode); - if (ownerMappedClass.IsAssignableFrom(keyType.ReturnedClass) && keyType.ReturnedClass.IsInstanceOfType(key)) + if (ownerMappedClass.GetTypeInfo().IsAssignableFrom(keyType.ReturnedClass) && keyType.ReturnedClass.IsInstanceOfType(key)) { // the key is the owning entity itself, so get the ID from the key ownerId = ownerPersister.GetIdentifier(key, session.EntityMode); diff --git a/src/NHibernate/Type/ComponentType.cs b/src/NHibernate/Type/ComponentType.cs index 42c81d20275..e7ab123ac6e 100644 --- a/src/NHibernate/Type/ComponentType.cs +++ b/src/NHibernate/Type/ComponentType.cs @@ -503,7 +503,7 @@ public override object Hydrate(DbDataReader rs, string[] names, ISessionImplemen begin += length; } - if (ReturnedClass.IsValueType) + if (ReturnedClass.GetTypeInfo().IsValueType) return values; else return notNull ? values : null; @@ -702,4 +702,4 @@ public int GetPropertyIndex(string name) throw new PropertyNotFoundException(ReturnedClass, name); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/CompositeCustomType.cs b/src/NHibernate/Type/CompositeCustomType.cs index 13164f11c9b..f42ac40c8f7 100644 --- a/src/NHibernate/Type/CompositeCustomType.cs +++ b/src/NHibernate/Type/CompositeCustomType.cs @@ -49,7 +49,7 @@ public CompositeCustomType(System.Type userTypeClass, IDictionary public override object FromStringValue(string xml) { - return CultureInfo.CreateSpecificCulture(xml); + return CreateSpecificCulture(xml); + } + + private static CultureInfo CreateSpecificCulture(string name) + { + var culture = new CultureInfo(name); + + return !culture.IsNeutralCulture ? culture : CultureInfo.InvariantCulture; } /// @@ -100,4 +107,4 @@ public string ObjectToSQLString(object value, Dialect.Dialect dialect) return ((ILiteralType) NHibernateUtil.String).ObjectToSQLString(value.ToString(), dialect); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/CustomCollectionType.cs b/src/NHibernate/Type/CustomCollectionType.cs index 9ce032c6040..6b57d23e065 100644 --- a/src/NHibernate/Type/CustomCollectionType.cs +++ b/src/NHibernate/Type/CustomCollectionType.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Reflection; using NHibernate.Collection; using NHibernate.Engine; using NHibernate.Persister.Collection; @@ -87,4 +88,4 @@ public override object ReplaceElements(object original, object target, object ow return userType.ReplaceElements(original, target, cp, owner, copyCache, session); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/CustomType.cs b/src/NHibernate/Type/CustomType.cs index 6e9f8c51f78..5dac171d83f 100644 --- a/src/NHibernate/Type/CustomType.cs +++ b/src/NHibernate/Type/CustomType.cs @@ -267,4 +267,4 @@ public virtual string ToXMLString(object value, ISessionFactoryImplementor facto } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/DateType.cs b/src/NHibernate/Type/DateType.cs index 1447dcb8638..c78b20be5c2 100644 --- a/src/NHibernate/Type/DateType.cs +++ b/src/NHibernate/Type/DateType.cs @@ -96,7 +96,7 @@ public override int GetHashCode(object x, EntityMode entityMode) public override string ToString(object val) { - return ((DateTime) val).ToShortDateString(); + return ((DateTime) val).ToString("d"); } public override object FromStringValue(string xml) @@ -121,7 +121,7 @@ public override object DefaultValue public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { - return "\'" + ((DateTime)value).ToShortDateString() + "\'"; + return "\'" + ((DateTime)value).ToString("d") + "\'"; } public void SetParameterValues(IDictionary parameters) @@ -137,4 +137,4 @@ public void SetParameterValues(IDictionary parameters) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/EnumStringType.cs b/src/NHibernate/Type/EnumStringType.cs index 665dde131aa..b6924d089df 100644 --- a/src/NHibernate/Type/EnumStringType.cs +++ b/src/NHibernate/Type/EnumStringType.cs @@ -1,6 +1,7 @@ using System; using System.Data; using System.Data.Common; +using System.Reflection; using NHibernate.Engine; using NHibernate.SqlTypes; @@ -220,7 +221,7 @@ public EnumStringType() : base(typeof (T)) { System.Type type = GetType(); - typeName = type.FullName + ", " + type.Assembly.GetName().Name; + typeName = type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name; } public override string Name @@ -228,4 +229,4 @@ public override string Name get { return typeName; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/PersistentEnumType.cs b/src/NHibernate/Type/PersistentEnumType.cs index f5fab6876da..e94f1291e28 100644 --- a/src/NHibernate/Type/PersistentEnumType.cs +++ b/src/NHibernate/Type/PersistentEnumType.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Data.Common; +using System.Reflection; using NHibernate.Engine; using NHibernate.SqlTypes; @@ -286,7 +287,7 @@ public class EnumType : PersistentEnumType public EnumType() : base(typeof (T)) { System.Type type = GetType(); - typeName = type.FullName + ", " + type.Assembly.GetName().Name; + typeName = type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name; } public override string Name diff --git a/src/NHibernate/Type/SerializableType.cs b/src/NHibernate/Type/SerializableType.cs index 5fe2f1deedb..0f71bb4072f 100644 --- a/src/NHibernate/Type/SerializableType.cs +++ b/src/NHibernate/Type/SerializableType.cs @@ -1,3 +1,5 @@ +#if FEATURE_SERIALIZATION + using System; using System.Data; using System.Data.Common; @@ -163,4 +165,6 @@ public override object Disassemble(object value, ISessionImplementor session, ob return (value == null) ? null : ToBytes(value); } } -} \ No newline at end of file +} + +#endif diff --git a/src/NHibernate/Type/SerializationException.cs b/src/NHibernate/Type/SerializationException.cs index 1118dbf5487..8785d8dc4a5 100644 --- a/src/NHibernate/Type/SerializationException.cs +++ b/src/NHibernate/Type/SerializationException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Type { @@ -38,6 +41,7 @@ public SerializationException(string message, Exception e) : base(message, e) { } +#if FEATURE_SERIALIZATION /// /// Initializes a new instance of the class /// with serialized data. @@ -52,5 +56,6 @@ public SerializationException(string message, Exception e) : base(message, e) protected SerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/TimeType.cs b/src/NHibernate/Type/TimeType.cs index dd74cae61b9..5c3035bdbd8 100644 --- a/src/NHibernate/Type/TimeType.cs +++ b/src/NHibernate/Type/TimeType.cs @@ -131,7 +131,7 @@ public override object DefaultValue public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { - return "'" + ((DateTime)value).ToShortTimeString() + "'"; + return "'" + ((DateTime)value).ToString("t") + "'"; } } } diff --git a/src/NHibernate/Type/TimestampType.cs b/src/NHibernate/Type/TimestampType.cs index bd24650b718..38768b7a698 100644 --- a/src/NHibernate/Type/TimestampType.cs +++ b/src/NHibernate/Type/TimestampType.cs @@ -101,7 +101,7 @@ public virtual object Seed(ISessionImplementor session) public IComparer Comparator { - get { return Comparer.DefaultInvariant; } + get { return System.Collections.Generic.Comparer.Default; } } #endregion @@ -126,4 +126,4 @@ public override string ObjectToSQLString(object value, Dialect.Dialect dialect) return '\'' + value.ToString() + '\''; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/TypeFactory.cs b/src/NHibernate/Type/TypeFactory.cs index 4a95b4dba19..8699c7c2995 100644 --- a/src/NHibernate/Type/TypeFactory.cs +++ b/src/NHibernate/Type/TypeFactory.cs @@ -33,6 +33,7 @@ private enum TypeClassification PrecisionScale } + private static readonly object StaticSyncRoot = new object(); private static readonly string[] EmptyAliases= new string[0]; private static readonly char[] PrecisionScaleSplit = new[] { '(', ')', ',' }; private static readonly char[] LengthSplit = new[] { '(', ')' }; @@ -107,7 +108,7 @@ private static IEnumerable GetClrTypeAliases(System.Type systemType) systemType.FullName, systemType.AssemblyQualifiedName, }; - if (systemType.IsValueType) + if (systemType.GetTypeInfo().IsValueType) { // Also register Nullable for ValueTypes var nullableType = typeof(Nullable<>).MakeGenericType(systemType); @@ -216,9 +217,11 @@ private static void RegisterDefaultNetTypes() RegisterType(typeof(XDocument), NHibernateUtil.XDoc, new[] { "xdoc", "xdocument" }); +#if FEATURE_SERIALIZATION // object needs to have both class and serializable setup before it can // be created. RegisterType(typeof (Object), NHibernateUtil.Object, new[] {"object"}); +#endif } /// @@ -256,10 +259,13 @@ private static void RegisterBuiltInTypes() (p, s) => GetType(NHibernateUtil.Currency, p, s, st => new CurrencyType(st))); RegisterType(NHibernateUtil.DateTime2, new[] { "datetime2" }); + +#if FEATURE_SERIALIZATION RegisterType(NHibernateUtil.Serializable, new[] {"Serializable", "serializable"}, l => GetType(NHibernateUtil.Serializable, l, len => new SerializableType(typeof (object), SqlTypeFactory.GetBinary(len)))); +#endif } public ICollectionTypeFactory CollectionTypeFactory @@ -535,14 +541,15 @@ public static IType HeuristicType(string typeName, IDictionary p } var unwrapped = typeClass.UnwrapIfNullable(); - if (unwrapped.IsEnum) + if (unwrapped.GetTypeInfo().IsEnum) { return (IType) Activator.CreateInstance(typeof (EnumType<>).MakeGenericType(unwrapped)); } - if (!typeClass.IsSerializable) + if (!typeClass.GetTypeInfo().IsSerializable) return null; +#if FEATURE_SERIALIZATION if (typeClassification == TypeClassification.Length) return GetSerializableType(typeClass, Int32.Parse(parsedTypeName[1])); @@ -550,21 +557,26 @@ public static IType HeuristicType(string typeName, IDictionary p return GetSerializableType(typeClass, length.Value); return GetSerializableType(typeClass); +#else + throw new NotImplementedException("Serializable types not valid with .NET Core"); +#endif } - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetAnsiStringType(int length) { - string key = GetKeyForLengthBased(NHibernateUtil.AnsiString.Name, length); - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new AnsiStringType(SqlTypeFactory.GetAnsiString(length)); - AddToTypeOfNameWithLength(key, returnType); + string key = GetKeyForLengthBased(NHibernateUtil.AnsiString.Name, length); + + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new AnsiStringType(SqlTypeFactory.GetAnsiString(length)); + AddToTypeOfNameWithLength(key, returnType); + } + return (NullableType)returnType; } - return (NullableType)returnType; } /// @@ -577,54 +589,62 @@ public static NullableType GetAnsiStringType(int length) /// been added to the basicNameMap with the keys Byte[](length) and /// NHibernate.Type.BinaryType(length). /// - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetBinaryType(int length) { - //HACK: don't understand why SerializableType calls this with length=0 - if (length == 0) + lock (StaticSyncRoot) { - return NHibernateUtil.Binary; - } + //HACK: don't understand why SerializableType calls this with length=0 + if (length == 0) + { + return NHibernateUtil.Binary; + } - string key = GetKeyForLengthBased(NHibernateUtil.Binary.Name, length); - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) - { - returnType = new BinaryType(SqlTypeFactory.GetBinary(length)); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(NHibernateUtil.Binary.Name, length); + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new BinaryType(SqlTypeFactory.GetBinary(length)); + AddToTypeOfNameWithLength(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + } } - [MethodImpl(MethodImplOptions.Synchronized)] private static NullableType GetType(NullableType defaultUnqualifiedType, int length, GetNullableTypeWithLength ctorDelegate) { - string key = GetKeyForLengthBased(defaultUnqualifiedType.Name, length); - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = ctorDelegate(length); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(defaultUnqualifiedType.Name, length); + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = ctorDelegate(length); + AddToTypeOfNameWithLength(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + } } - [MethodImpl(MethodImplOptions.Synchronized)] private static NullableType GetType(NullableType defaultUnqualifiedType, byte precision, byte scale, NullableTypeCreatorDelegate ctor) { - string key = GetKeyForPrecisionScaleBased(defaultUnqualifiedType.Name, precision, scale); - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = ctor(SqlTypeFactory.GetSqlType(defaultUnqualifiedType.SqlType.DbType, precision, scale)); - AddToTypeOfNameWithPrecision(key, returnType); - } + string key = GetKeyForPrecisionScaleBased(defaultUnqualifiedType.Name, precision, scale); + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = ctor(SqlTypeFactory.GetSqlType(defaultUnqualifiedType.SqlType.DbType, precision, scale)); + AddToTypeOfNameWithPrecision(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + + } } +#if FEATURE_SERIALIZATION /// /// Gets the SerializableType for the specified Type /// @@ -644,79 +664,91 @@ private static NullableType GetType(NullableType defaultUnqualifiedType, byte pr /// with the default length, those keys will also be added. /// /// - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetSerializableType(System.Type serializableType) { - string key = serializableType.AssemblyQualifiedName; - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new SerializableType(serializableType); - AddToTypeOfName(key, returnType); - } + string key = serializableType.AssemblyQualifiedName; + + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new SerializableType(serializableType); + AddToTypeOfName(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + + } } - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetSerializableType(System.Type serializableType, int length) { - string key = GetKeyForLengthBased(serializableType.AssemblyQualifiedName, length); - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new SerializableType(serializableType, SqlTypeFactory.GetBinary(length)); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(serializableType.AssemblyQualifiedName, length); + + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new SerializableType(serializableType, SqlTypeFactory.GetBinary(length)); + AddToTypeOfNameWithLength(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + } } - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetSerializableType(int length) { - string key = GetKeyForLengthBased(NHibernateUtil.Serializable.Name, length); - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new SerializableType(typeof(object), SqlTypeFactory.GetBinary(length)); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(NHibernateUtil.Serializable.Name, length); + + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new SerializableType(typeof(object), SqlTypeFactory.GetBinary(length)); + AddToTypeOfNameWithLength(key, returnType); + } - return (NullableType)returnType; + return (NullableType)returnType; + } } +#endif - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetStringType(int length) { - string key = GetKeyForLengthBased(NHibernateUtil.String.Name, length); - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new StringType(SqlTypeFactory.GetString(length)); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(NHibernateUtil.String.Name, length); - return (NullableType)returnType; + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new StringType(SqlTypeFactory.GetString(length)); + AddToTypeOfNameWithLength(key, returnType); + } + + return (NullableType)returnType; + } } - [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetTypeType(int length) { - string key = GetKeyForLengthBased(typeof(TypeType).FullName, length); - - IType returnType; - if (!typeByTypeOfName.TryGetValue(key, out returnType)) + lock (StaticSyncRoot) { - returnType = new TypeType(SqlTypeFactory.GetString(length)); - AddToTypeOfNameWithLength(key, returnType); - } + string key = GetKeyForLengthBased(typeof(TypeType).FullName, length); - return (NullableType)returnType; + IType returnType; + if (!typeByTypeOfName.TryGetValue(key, out returnType)) + { + returnType = new TypeType(SqlTypeFactory.GetString(length)); + AddToTypeOfNameWithLength(key, returnType); + } + + return (NullableType)returnType; + } } // Association Types diff --git a/src/NHibernate/TypeMismatchException.cs b/src/NHibernate/TypeMismatchException.cs index 5e511d6dadc..3bf8a594d53 100644 --- a/src/NHibernate/TypeMismatchException.cs +++ b/src/NHibernate/TypeMismatchException.cs @@ -1,5 +1,8 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate { @@ -11,6 +14,8 @@ public class TypeMismatchException : HibernateException { public TypeMismatchException(string message) : base(message) { } public TypeMismatchException(string message, Exception inner) : base(message, inner) { } +#if FEATURE_SERIALIZATION protected TypeMismatchException(SerializationInfo info,StreamingContext context): base(info, context) { } +#endif } } diff --git a/src/NHibernate/UnresolvableObjectException.cs b/src/NHibernate/UnresolvableObjectException.cs index d766bf2881a..1e2a5d4d67a 100644 --- a/src/NHibernate/UnresolvableObjectException.cs +++ b/src/NHibernate/UnresolvableObjectException.cs @@ -1,8 +1,10 @@ using System; +using NHibernate.Impl; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; -using NHibernate.Impl; +#endif namespace NHibernate { @@ -90,6 +92,7 @@ public static void ThrowIfNull(object o, object id, string entityName) } } +#if FEATURE_SERIALIZATION #region ISerializable Members [SecurityCritical] @@ -110,5 +113,6 @@ protected UnresolvableObjectException(SerializationInfo info, StreamingContext c } #endregion +#endif } } diff --git a/src/NHibernate/Util/ArrayHelper.cs b/src/NHibernate/Util/ArrayHelper.cs index 395e0c792d8..0924bd7f87c 100644 --- a/src/NHibernate/Util/ArrayHelper.cs +++ b/src/NHibernate/Util/ArrayHelper.cs @@ -105,7 +105,7 @@ public static void AddAll(IList to, IList from) if (addNull == null) { var toType = to.GetType(); - if (toType.IsGenericType && + if (toType.GetTypeInfo().IsGenericType && toType.GetGenericTypeDefinition() == typeof(List<>) && toType.GetGenericArguments()[0].IsNullable()) { diff --git a/src/NHibernate/Util/CollectionHelper.cs b/src/NHibernate/Util/CollectionHelper.cs index b8f78c5bef0..4e8842a1bb6 100644 --- a/src/NHibernate/Util/CollectionHelper.cs +++ b/src/NHibernate/Util/CollectionHelper.cs @@ -340,7 +340,7 @@ public static int GetHashCode(IEnumerable coll) /// public static IDictionary CreateCaseInsensitiveHashtable() { - return new Dictionary(StringComparer.InvariantCultureIgnoreCase); + return new Dictionary(StringComparer.OrdinalIgnoreCase); } /// @@ -353,7 +353,7 @@ public static IDictionary CreateCaseInsensitiveHashtable() /// public static IDictionary CreateCaseInsensitiveHashtable(IDictionary dictionary) { - return new Dictionary(dictionary, StringComparer.InvariantCultureIgnoreCase); + return new Dictionary(dictionary, StringComparer.OrdinalIgnoreCase); } // ~~~~~~~~~~~~~~~~~~~~~~ Generics ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/NHibernate/Util/IdentityMap.cs b/src/NHibernate/Util/IdentityMap.cs index 3b6667a2ea3..8921d836a9b 100644 --- a/src/NHibernate/Util/IdentityMap.cs +++ b/src/NHibernate/Util/IdentityMap.cs @@ -1,8 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Runtime.Serialization; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif namespace NHibernate.Util { @@ -27,7 +29,11 @@ namespace NHibernate.Util /// /// [Serializable] - public sealed class IdentityMap : IDictionary, IDeserializationCallback + public sealed class IdentityMap + : IDictionary +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { // key = IdentityKey of the passed in Key // value = object passed in @@ -271,9 +277,11 @@ public static IDictionary Invert(IDictionary map) return result; } +#if FEATURE_SERIALIZATION public void OnDeserialization(object sender) { ((IDeserializationCallback)map).OnDeserialization(sender); } +#endif } -} \ No newline at end of file +} diff --git a/src/NHibernate/Util/LinkedHashMap.cs b/src/NHibernate/Util/LinkedHashMap.cs index 772a8819960..35e99063a40 100644 --- a/src/NHibernate/Util/LinkedHashMap.cs +++ b/src/NHibernate/Util/LinkedHashMap.cs @@ -2,10 +2,13 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; using System.Text; using NHibernate.DebugHelpers; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Util { /// @@ -19,7 +22,11 @@ namespace NHibernate.Util /// [DebuggerTypeProxy(typeof(CollectionProxy<>))] [Serializable] - public class LinkedHashMap : IDictionary, IDeserializationCallback + public class LinkedHashMap + : IDictionary +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { [Serializable] protected class Entry @@ -360,10 +367,12 @@ private bool RemoveImpl(TKey key) return result; } +#if FEATURE_SERIALIZATION void IDeserializationCallback.OnDeserialization(object sender) { ((IDeserializationCallback)entries).OnDeserialization(sender); } +#endif #region System.Object Members diff --git a/src/NHibernate/Util/ReflectHelper.cs b/src/NHibernate/Util/ReflectHelper.cs index 8814f780fe3..7cfb0299302 100644 --- a/src/NHibernate/Util/ReflectHelper.cs +++ b/src/NHibernate/Util/ReflectHelper.cs @@ -9,6 +9,10 @@ using NHibernate.Type; using NHibernate.Engine; +#if NETSTANDARD +using Microsoft.Extensions.DependencyModel; +#endif + namespace NHibernate.Util { /// @@ -41,7 +45,7 @@ private static bool OverrideMethod(System.Type clazz, string methodName, System. { try { - MethodInfo method = !clazz.IsInterface + MethodInfo method = !clazz.GetTypeInfo().IsInterface ? clazz.GetMethod(methodName, parametersTypes) : GetMethodFromInterface(clazz, methodName, parametersTypes); if (method == null) @@ -199,38 +203,42 @@ public static System.Type ClassForFullName(string classFullName) } /// - /// Load a System.Type given its name. - /// - /// The class FullName or AssemblyQualifiedName - /// The System.Type or null - /// - /// If the don't represent an - /// the method try to find the System.Type scanning all Assemblies of the . - /// - public static System.Type ClassForFullNameOrNull(string classFullName) + /// Load a System.Type given its name. + /// + /// The class FullName or AssemblyQualifiedName + /// The System.Type or null + /// + /// If the don't represent an + /// the method try to find the System.Type scanning all Assemblies of the . + /// + public static System.Type ClassForFullNameOrNull(string classFullName) + { + System.Type result = null; + AssemblyQualifiedTypeName parsedName = TypeNameParser.Parse(classFullName); + if (!string.IsNullOrEmpty(parsedName.Assembly)) + { + result = TypeFromAssembly(parsedName, false); + } + else + { + if (!string.IsNullOrEmpty(classFullName)) { - System.Type result = null; - AssemblyQualifiedTypeName parsedName = TypeNameParser.Parse(classFullName); - if (!string.IsNullOrEmpty(parsedName.Assembly)) - { - result = TypeFromAssembly(parsedName, false); - } - else +#if NETSTANDARD + Assembly[] ass = DependencyContext.Default.RuntimeLibraries.SelectMany(l => l.Assemblies).Select(x => Assembly.Load(x.Name)).ToArray(); +#else + Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); +#endif + foreach (Assembly a in ass) { - if (!string.IsNullOrEmpty(classFullName)) - { - Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); - foreach (Assembly a in ass) - { - result = a.GetType(classFullName, false, false); - if (result != null) - break; //<<<<<================ - } - } + result = a.GetType(classFullName, false, false); + if (result != null) + break; //<<<<<================ } - - return result; } + } + + return result; + } public static System.Type TypeFromAssembly(string type, string assembly, bool throwIfError) { @@ -274,7 +282,7 @@ public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool return null; } - Assembly assembly = Assembly.Load(name.Assembly); + Assembly assembly = Assembly.Load(new AssemblyName(name.Assembly)); if (assembly == null) { @@ -311,7 +319,7 @@ public static bool TryLoadAssembly(string assemblyName) bool result = true; try { - Assembly.Load(assemblyName); + Assembly.Load(new AssemblyName(assemblyName)); } catch (Exception) { @@ -441,12 +449,12 @@ private static string FormatConstructorNotFoundMessage(IEnumerable types) /// if the is an Abstract Class or an Interface. public static bool IsAbstractClass(System.Type type) { - return (type.IsAbstract || type.IsInterface); + return (type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface); } public static bool IsFinalClass(System.Type type) { - return type.IsSealed; + return type.GetTypeInfo().IsSealed; } /// @@ -510,7 +518,7 @@ private static MethodInfo SafeGetMethod(System.Type type, MethodInfo method, Sys { typesToSearch.Add(type); - if (type.IsInterface) + if (type.GetTypeInfo().IsInterface) { // Methods on parent interfaces are not actually inherited // by child interfaces, so we have to use GetInterfaces to @@ -654,10 +662,10 @@ public static System.Type GetCollectionElementType(System.Type collectionType) { return collectionType.GetElementType(); } - if (collectionType.IsGenericType) + if (collectionType.GetTypeInfo().IsGenericType) { - List interfaces = collectionType.GetInterfaces().Where(t => t.IsGenericType).ToList(); - if (collectionType.IsInterface) + List interfaces = collectionType.GetInterfaces().Where(t => t.GetTypeInfo().IsGenericType).ToList(); + if (collectionType.GetTypeInfo().IsInterface) { interfaces.Add(collectionType); } @@ -697,7 +705,7 @@ public static bool HasProperty(this System.Type source, string propertyName) { return true; } - return HasProperty(source.BaseType, propertyName) || source.GetInterfaces().Any(@interface => HasProperty(@interface, propertyName)); + return HasProperty(source.GetTypeInfo().BaseType, propertyName) || source.GetInterfaces().Any(@interface => HasProperty(@interface, propertyName)); } /// @@ -721,27 +729,27 @@ public static bool IsMethodOf(this MethodInfo source, System.Type realDeclaringT { return true; } - if (methodDeclaringType.IsGenericType && !methodDeclaringType.IsGenericTypeDefinition && + if (methodDeclaringType.GetTypeInfo().IsGenericType && !methodDeclaringType.GetTypeInfo().IsGenericTypeDefinition && realDeclaringType == methodDeclaringType.GetGenericTypeDefinition()) { return true; } - if (realDeclaringType.IsInterface) + if (realDeclaringType.GetTypeInfo().IsInterface) { var declaringTypeInterfaces = methodDeclaringType.GetInterfaces(); if(declaringTypeInterfaces.Contains(realDeclaringType)) { - var methodsMap = methodDeclaringType.GetInterfaceMap(realDeclaringType); + InterfaceMapping methodsMap = methodDeclaringType.GetTypeInfo().GetRuntimeInterfaceMap(realDeclaringType); if(methodsMap.TargetMethods.Contains(source)) { return true; } } - if (realDeclaringType.IsGenericTypeDefinition) + if (realDeclaringType.GetTypeInfo().IsGenericTypeDefinition) { bool implements = declaringTypeInterfaces - .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == realDeclaringType) - .Select(implementedGenericInterface => methodDeclaringType.GetInterfaceMap(implementedGenericInterface)) + .Where(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == realDeclaringType) + .Select(implementedGenericInterface => methodDeclaringType.GetTypeInfo().GetRuntimeInterfaceMap(implementedGenericInterface)) .Any(methodsMap => methodsMap.TargetMethods.Contains(source)); if (implements) { diff --git a/src/NHibernate/Util/SequencedHashMap.cs b/src/NHibernate/Util/SequencedHashMap.cs index 1f9a539c0ac..75d76466c13 100644 --- a/src/NHibernate/Util/SequencedHashMap.cs +++ b/src/NHibernate/Util/SequencedHashMap.cs @@ -66,7 +66,10 @@ using System.Diagnostics; using System.Text; using NHibernate.DebugHelpers; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; +#endif namespace NHibernate.Util { @@ -79,7 +82,11 @@ namespace NHibernate.Util /// [DebuggerTypeProxy(typeof(CollectionProxy<>))] [Serializable] - public class SequencedHashMap : IDictionary, IDeserializationCallback + public class SequencedHashMap + : IDictionary +#if FEATURE_SERIALIZATION + , IDeserializationCallback +#endif { [Serializable] private class Entry @@ -482,10 +489,12 @@ public virtual object LastValue get { return (Last == null) ? null : Last.Value; } } +#if FEATURE_SERIALIZATION public void OnDeserialization(object sender) { _entries.OnDeserialization(sender); } +#endif /// /// Remove the Entry identified by the Key if it exists. diff --git a/src/NHibernate/Util/SimpleMRUCache.cs b/src/NHibernate/Util/SimpleMRUCache.cs index 06c66679d9f..77930522d1b 100644 --- a/src/NHibernate/Util/SimpleMRUCache.cs +++ b/src/NHibernate/Util/SimpleMRUCache.cs @@ -1,8 +1,11 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Threading; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Util { /// @@ -15,7 +18,10 @@ namespace NHibernate.Util /// the cache. Thus the size of this cache never grows beyond the stated size. /// [Serializable] - public class SimpleMRUCache : IDeserializationCallback + public class SimpleMRUCache +#if FEATURE_SERIALIZATION + : IDeserializationCallback +#endif { private const int DefaultStrongRefCount = 128; @@ -46,6 +52,7 @@ private object SyncRoot } } +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) @@ -54,10 +61,10 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif public object this[object key] { - [MethodImpl(MethodImplOptions.Synchronized)] get { lock (SyncRoot) @@ -67,7 +74,6 @@ public object this[object key] } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Put(object key, object value) { lock (SyncRoot) @@ -78,7 +84,6 @@ public void Put(object key, object value) public int Count { - [MethodImpl(MethodImplOptions.Synchronized)] get { lock (SyncRoot) @@ -88,7 +93,6 @@ public int Count } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Clear() { lock (SyncRoot) diff --git a/src/NHibernate/Util/SoftLimitMRUCache.cs b/src/NHibernate/Util/SoftLimitMRUCache.cs index bd232103246..3b237d43a3d 100644 --- a/src/NHibernate/Util/SoftLimitMRUCache.cs +++ b/src/NHibernate/Util/SoftLimitMRUCache.cs @@ -1,9 +1,12 @@ using System; using System.Collections; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Threading; +#if FEATURE_SERIALIZATION +using System.Runtime.Serialization; +#endif + namespace NHibernate.Util { /// @@ -22,7 +25,10 @@ namespace NHibernate.Util /// enqueuement. /// [Serializable] - public class SoftLimitMRUCache : IDeserializationCallback + public class SoftLimitMRUCache +#if FEATURE_SERIALIZATION + : IDeserializationCallback +#endif { private const int DefaultStrongRefCount = 128; private object _syncRoot; @@ -61,6 +67,7 @@ private object SyncRoot } } +#if FEATURE_SERIALIZATION #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) @@ -69,10 +76,10 @@ void IDeserializationCallback.OnDeserialization(object sender) } #endregion +#endif public object this[object key] { - [MethodImpl(MethodImplOptions.Synchronized)] get { lock (SyncRoot) @@ -87,7 +94,6 @@ public object this[object key] } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Put(object key, object value) { lock (SyncRoot) @@ -99,7 +105,6 @@ public void Put(object key, object value) public int Count { - [MethodImpl(MethodImplOptions.Synchronized)] get { lock (SyncRoot) @@ -111,7 +116,6 @@ public int Count public int SoftCount { - [MethodImpl(MethodImplOptions.Synchronized)] get { lock (SyncRoot) @@ -121,7 +125,6 @@ public int SoftCount } } - [MethodImpl(MethodImplOptions.Synchronized)] public void Clear() { lock (SyncRoot) diff --git a/src/NHibernate/Util/StringHelper.cs b/src/NHibernate/Util/StringHelper.cs index 6e88b149530..b1d43935970 100644 --- a/src/NHibernate/Util/StringHelper.cs +++ b/src/NHibernate/Util/StringHelper.cs @@ -387,7 +387,10 @@ public static string LinesToString(this string[] text) return text[0]; } var sb = new StringBuilder(200); - Array.ForEach(text, t => sb.AppendLine(t)); + foreach (var t in text) + { + sb.AppendLine(t); + } return sb.ToString(); } @@ -631,32 +634,32 @@ public static string Unroot(string qualifiedName) public static bool EqualsCaseInsensitive(string a, string b) { - return StringComparer.InvariantCultureIgnoreCase.Compare(a, b) == 0; + return StringComparer.OrdinalIgnoreCase.Compare(a, b) == 0; } public static int IndexOfCaseInsensitive(string source, string value) { - return source.IndexOf(value, StringComparison.InvariantCultureIgnoreCase); + return source.IndexOf(value, StringComparison.OrdinalIgnoreCase); } public static int IndexOfCaseInsensitive(string source, string value, int startIndex) { - return source.IndexOf(value, startIndex, StringComparison.InvariantCultureIgnoreCase); + return source.IndexOf(value, startIndex, StringComparison.OrdinalIgnoreCase); } public static int IndexOfCaseInsensitive(string source, string value, int startIndex, int count) { - return source.IndexOf(value, startIndex, count, StringComparison.InvariantCultureIgnoreCase); + return source.IndexOf(value, startIndex, count, StringComparison.OrdinalIgnoreCase); } public static int LastIndexOfCaseInsensitive(string source, string value) { - return source.LastIndexOf(value, StringComparison.InvariantCultureIgnoreCase); + return source.LastIndexOf(value, StringComparison.OrdinalIgnoreCase); } public static bool StartsWithCaseInsensitive(string source, string prefix) { - return source.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase); + return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } /// @@ -672,11 +675,13 @@ public static string InternedIfPossible(string str) return null; } +#if FEATURE_STRING_INTERN string interned = string.IsInterned(str); if (interned != null) { return interned; } +#endif return str; } diff --git a/src/NHibernate/Util/TypeExtensions.cs b/src/NHibernate/Util/TypeExtensions.cs index 71bf854957f..65f2d7c7a58 100644 --- a/src/NHibernate/Util/TypeExtensions.cs +++ b/src/NHibernate/Util/TypeExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Reflection; namespace NHibernate.Util { @@ -8,17 +9,17 @@ public static class TypeExtensions { public static bool IsEnumerableOfT(this System.Type type) { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>); } public static bool IsNullable(this System.Type type) { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool IsNullableOrReference(this System.Type type) { - return !type.IsValueType || type.IsNullable(); + return !type.GetTypeInfo().IsValueType || type.IsNullable(); } public static System.Type NullableOf(this System.Type type) @@ -28,7 +29,7 @@ public static System.Type NullableOf(this System.Type type) public static bool IsPrimitive(this System.Type type) { - return (type.IsValueType || type.IsNullable() || type == typeof(string)); + return (type.GetTypeInfo().IsValueType || type.IsNullable() || type == typeof(string)); } public static bool IsNonPrimitive(this System.Type type) diff --git a/src/NHibernate/Util/TypeNameParser.cs b/src/NHibernate/Util/TypeNameParser.cs index 737ac05e2ed..21c522421fc 100644 --- a/src/NHibernate/Util/TypeNameParser.cs +++ b/src/NHibernate/Util/TypeNameParser.cs @@ -6,7 +6,7 @@ namespace NHibernate.Util { - public class ParserException : ApplicationException + public class ParserException : Exception { public ParserException(string message) : base(message) { } } @@ -232,4 +232,4 @@ private static bool NeedDefaultAssembly(string typeFullName) return NeedDefaultNamespaceOrDefaultAssembly(typeFullName) && typeFullName.IndexOf(',') < 0; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/WrongClassException.cs b/src/NHibernate/WrongClassException.cs index 90c7f1024dc..9495e1ea6f5 100644 --- a/src/NHibernate/WrongClassException.cs +++ b/src/NHibernate/WrongClassException.cs @@ -1,7 +1,9 @@ using System; + +#if FEATURE_SERIALIZATION using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +#endif namespace NHibernate { @@ -10,7 +12,11 @@ namespace NHibernate /// but the row's discriminator value specifies a different subclass from the one requested /// [Serializable] - public class WrongClassException : HibernateException, ISerializable + public class WrongClassException + : HibernateException +#if FEATURE_SERIALIZATION + , ISerializable +#endif { private readonly object identifier; private readonly string entityName; @@ -56,6 +62,7 @@ public override string Message } } +#if FEATURE_SERIALIZATION #region ISerializable Members /// @@ -95,5 +102,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endregion +#endif } } diff --git a/src/NHibernate/packages.config b/src/NHibernate/packages.config deleted file mode 100644 index 8412c0a386f..00000000000 --- a/src/NHibernate/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file