diff --git a/build-common/nhibernate-properties.xml b/build-common/nhibernate-properties.xml index 4b62e992a55..d01178e24d1 100644 --- a/build-common/nhibernate-properties.xml +++ b/build-common/nhibernate-properties.xml @@ -2,6 +2,6 @@ - + diff --git a/build-common/teamcity-hibernate.cfg.xml b/build-common/teamcity-hibernate.cfg.xml index 0e038aa76ea..61ec5097cda 100644 --- a/build-common/teamcity-hibernate.cfg.xml +++ b/build-common/teamcity-hibernate.cfg.xml @@ -15,7 +15,7 @@ true - NHibernate.Driver.Sql2008ClientDriver + NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer NHibernate.Dialect.MsSql2008Dialect Server=.\SQLExpress;initial catalog=nhibernate;Integrated Security=SSPI false diff --git a/default.build b/default.build index 997a8d5ac26..5994113eb05 100644 --- a/default.build +++ b/default.build @@ -138,6 +138,7 @@ + @@ -169,7 +170,11 @@ - + + + + + diff --git a/doc/reference/modules/configuration.xml b/doc/reference/modules/configuration.xml index 5c2e4024d74..c0e6d9a932d 100644 --- a/doc/reference/modules/configuration.xml +++ b/doc/reference/modules/configuration.xml @@ -227,6 +227,13 @@ var session = sessions.OpenSession(conn); take care of setting the IDriver using a sensible default. See the API documentation of the specific dialect for the defaults. + + Since NHibernate v5.1, drivers having a NuGet package for their data provider have a + NHibernate.Driver dedicated assembly, which have to be referenced by your project. + Those assemblies are also available as NuGet packages. + If an obsolete driver is configured, NHibernate will issue a warning log when building the session + factory. + @@ -1186,9 +1193,13 @@ in the parameter binding. Firebird NHibernate.Dialect.FirebirdDialect - Set driver_class to - NHibernate.Driver.FirebirdClientDriver - for Firebird ADO.NET provider 2.0. + Install NuGet package + NHibernate.Driver.Firebird + and set driver_class to + NHibernate.Driver.FirebirdDriver, NHibernate.Driver.Firebird + with a fallback on the built-in reflection based + NHibernate.Driver.FirebirdClientDriver. + Both use Firebird ADO.NET provider. @@ -1219,65 +1230,99 @@ in the parameter binding. Microsoft SQL Server 7 NHibernate.Dialect.MsSql7Dialect - + Use the same default driver as NHibernate.Dialect.MsSql2000Dialect. Microsoft SQL Server 2000 NHibernate.Dialect.MsSql2000Dialect - + + Install NuGet package + NHibernate.Driver.SqlServer + and set driver_class to + NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer + with a fallback on the built-in reflection based + NHibernate.Driver.SqlClientDriver. + Both use System.Data.SqlClient. + Microsoft SQL Server 2005 NHibernate.Dialect.MsSql2005Dialect - + Use the same default driver as NHibernate.Dialect.MsSql2000Dialect. Microsoft SQL Server 2008 NHibernate.Dialect.MsSql2008Dialect - + + Install NuGet package + NHibernate.Driver.SqlServer + and set driver_class to + NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer + with a fallback on the built-in reflection based + NHibernate.Driver.Sql2008ClientDriver. + Both use System.Data.SqlClient. + Microsoft SQL Azure Server 2008 NHibernate.Dialect.MsSqlAzure2008Dialect - + Use the same default driver as NHibernate.Dialect.MsSql2008Dialect. Microsoft SQL Server 2012 NHibernate.Dialect.MsSql2012Dialect - + Use the same default driver as NHibernate.Dialect.MsSql2008Dialect. Microsoft SQL Server Compact Edition NHibernate.Dialect.MsSqlCeDialect + + Install NuGet package + NHibernate.Driver.SqlServer.Compact + and set driver_class to + NHibernate.Driver.SqlServerCompactDriver, NHibernate.Driver.SqlServer.Compact + with a fallback on the built-in reflection based + NHibernate.Driver.SqlServerCeDriver. + Both use System.Data.SqlServerCe. + Microsoft SQL Server Compact Edition 4.0 NHibernate.Dialect.MsSqlCe40Dialect + Use the same default driver as NHibernate.Dialect.MsSqlCeDialect. - MySQL 3 or 4 + MySQL 3 or 4 NHibernate.Dialect.MySQLDialect - + + Install NuGet package + NHibernate.Driver.MySql + and set driver_class to + NHibernate.Driver.MySqlDriver, NHibernate.Driver.MySql + with a fallback on the built-in reflection based + NHibernate.Driver.MySqlDataDriver. + Both use MySql.Data. + MySQL 5 NHibernate.Dialect.MySQL5Dialect - + Use the same default driver as NHibernate.Dialect.MySQLDialect. MySQL 5 Inno DB NHibernate.Dialect.MySQL5InnoDBDialect - + Use the same default driver as NHibernate.Dialect.MySQLDialect. MySQL 5.5 NHibernate.Dialect.MySQL55Dialect - + Use the same default driver as NHibernate.Dialect.MySQLDialect. MySQL 5.5 Inno DB NHibernate.Dialect.MySQL55InnoDBDialect - + Use the same default driver as NHibernate.Dialect.MySQLDialect. Oracle @@ -1299,15 +1344,17 @@ in the parameter binding. NHibernate.Dialect.Oracle12cDialect - - PostgreSQL - NHibernate.Dialect.PostgreSQLDialect - - PostgreSQL NHibernate.Dialect.PostgreSQLDialect + Install NuGet package + NHibernate.Driver.PostgreSql + and set driver_class to + NHibernate.Driver.PostgreSqlDriver, NHibernate.Driver.PostgreSql + with a fallback on the built-in reflection based + NHibernate.Driver.NpgsqlDriver. + Both use Npgsql. @@ -1316,6 +1363,7 @@ in the parameter binding. This dialect supports FOR UPDATE NOWAIT available in PostgreSQL 8.1. + Use the same default driver as NHibernate.Dialect.PostgreSQLDialect. @@ -1325,6 +1373,7 @@ in the parameter binding. This dialect supports IF EXISTS keyword in DROP TABLE and DROP SEQUENCE available in PostgreSQL 8.2. + Use the same default driver as NHibernate.Dialect.PostgreSQLDialect. @@ -1332,15 +1381,20 @@ in the parameter binding. NHibernate.Dialect.PostgreSQL83Dialect This dialect supports XML type. + Use the same default driver as NHibernate.Dialect.PostgreSQLDialect. SQLite NHibernate.Dialect.SQLiteDialect - Set driver_class to - NHibernate.Driver.SQLite20Driver - for System.Data.SQLite provider for .NET 2.0. + Install NuGet package + NHibernate.Driver.SQLite + and set driver_class to + NHibernate.Driver.SQLiteDriver, NHibernate.Driver.SQLite + with a fallback on the built-in reflection based + NHibernate.Driver.SQLite20Driver. + Both use System.Data.SQLite. Due to the diff --git a/src/NHibernate.Config.Templates/FireBird.cfg.xml b/src/NHibernate.Config.Templates/FireBird.cfg.xml index d621978174f..61e5f0dcc38 100644 --- a/src/NHibernate.Config.Templates/FireBird.cfg.xml +++ b/src/NHibernate.Config.Templates/FireBird.cfg.xml @@ -16,7 +16,7 @@ for your own use before compile tests in VisualStudio. --> - NHibernate.Driver.FirebirdClientDriver + NHibernate.Driver.FirebirdDriver, NHibernate.Driver.Firebird DataSource=localhost; Database=nhibernate; diff --git a/src/NHibernate.Config.Templates/MSSQL.cfg.xml b/src/NHibernate.Config.Templates/MSSQL.cfg.xml index 8e5706a5c56..4aea9caec11 100644 --- a/src/NHibernate.Config.Templates/MSSQL.cfg.xml +++ b/src/NHibernate.Config.Templates/MSSQL.cfg.xml @@ -7,7 +7,7 @@ for your own use before compile tests in VisualStudio. - NHibernate.Driver.Sql2008ClientDriver + NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer Server=(local);initial catalog=nhibernate;Integrated Security=SSPI diff --git a/src/NHibernate.Config.Templates/MySql.cfg.xml b/src/NHibernate.Config.Templates/MySql.cfg.xml index be2366cd660..ef246809489 100644 --- a/src/NHibernate.Config.Templates/MySql.cfg.xml +++ b/src/NHibernate.Config.Templates/MySql.cfg.xml @@ -6,11 +6,11 @@ for your own use before compile tests in VisualStudio. --> - NHibernate.Driver.MySqlDataDriver + NHibernate.Driver.MySqlDriver, NHibernate.Driver.MySql Database=nhibernate;Data Source=localhost;User Id=nhibernate;Password=; Protocol=memory;Old Guids=True; NHibernate.Dialect.MySQL5Dialect - \ No newline at end of file + diff --git a/src/NHibernate.Config.Templates/Oracle-Managed.cfg.xml b/src/NHibernate.Config.Templates/Oracle-Managed.cfg.xml index 24b71f31b21..21fa80ea8ce 100644 --- a/src/NHibernate.Config.Templates/Oracle-Managed.cfg.xml +++ b/src/NHibernate.Config.Templates/Oracle-Managed.cfg.xml @@ -7,7 +7,7 @@ for your own use before compile tests in VisualStudio. - NHibernate.Driver.OracleManagedDataClientDriver + NHibernate.Driver.OracleManagedDriver, NHibernate.Driver.Oracle.Managed User ID=nhibernate;Password=nhibernate;Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ORCL))) diff --git a/src/NHibernate.Config.Templates/PostgreSQL.cfg.xml b/src/NHibernate.Config.Templates/PostgreSQL.cfg.xml index 459543f2bbf..219fbbcc6be 100644 --- a/src/NHibernate.Config.Templates/PostgreSQL.cfg.xml +++ b/src/NHibernate.Config.Templates/PostgreSQL.cfg.xml @@ -6,7 +6,7 @@ for your own use before compile tests in VisualStudio. --> - NHibernate.Driver.NpgsqlDriver + NHibernate.Driver.PostgreSqlDriver, NHibernate.Driver.PostgreSql Server=localhost;Database=nhibernate;User ID=nhibernate;Password=nhibernate;Enlist=true; diff --git a/src/NHibernate.Config.Templates/SQLite.cfg.xml b/src/NHibernate.Config.Templates/SQLite.cfg.xml index 50890aea597..559f9312d7e 100644 --- a/src/NHibernate.Config.Templates/SQLite.cfg.xml +++ b/src/NHibernate.Config.Templates/SQLite.cfg.xml @@ -6,7 +6,7 @@ for your own use before compile tests in VisualStudio. --> - NHibernate.Driver.SQLite20Driver + NHibernate.Driver.SQLiteDriver, NHibernate.Driver.SQLite + + + true + build\ + + + + + + + false + %(RecursiveDir)%(Filename)%(Extension) + PreserveNewest + + + + + + NHibernate.license.txt + + + + diff --git a/src/NHibernate.Driver.SqlServer.Compact/Properties/AssemblyInfo.cs b/src/NHibernate.Driver.SqlServer.Compact/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..71b3de6ca17 --- /dev/null +++ b/src/NHibernate.Driver.SqlServer.Compact/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +using System; +using System.Reflection; +using System.Security; + +[assembly: CLSCompliantAttribute(true)] +[assembly: AssemblyDelaySignAttribute(false)] +[assembly: AllowPartiallyTrustedCallersAttribute()] +[assembly: SecurityRulesAttribute(SecurityRuleSet.Level1)] diff --git a/src/NHibernate.Driver.SqlServer.Compact/build/NHibernate.Driver.SqlServer.Compact.targets b/src/NHibernate.Driver.SqlServer.Compact/build/NHibernate.Driver.SqlServer.Compact.targets new file mode 100644 index 00000000000..1bafcf18130 --- /dev/null +++ b/src/NHibernate.Driver.SqlServer.Compact/build/NHibernate.Driver.SqlServer.Compact.targets @@ -0,0 +1,22 @@ + + + + + + + + %(RecursiveDir)%(Filename)%(Extension) + PreserveNewest + false + + + + + $(ResolveAssemblyReferencesDependsOn);InjectReference_eb5aa2e4-6c92-4a75-85b8-1348b65397d1 + + \ No newline at end of file diff --git a/src/NHibernate.Driver.SqlServer/Cfg/ConnectionConfigurationExtensionSqlServer.cs b/src/NHibernate.Driver.SqlServer/Cfg/ConnectionConfigurationExtensionSqlServer.cs new file mode 100644 index 00000000000..b49c46e79a2 --- /dev/null +++ b/src/NHibernate.Driver.SqlServer/Cfg/ConnectionConfigurationExtensionSqlServer.cs @@ -0,0 +1,28 @@ +using NHibernate.Cfg.Loquacious; +using NHibernate.Driver; + +namespace NHibernate.Cfg +{ + public static class ConnectionConfigurationExtensionSqlServer + { + public static IConnectionConfiguration BySqlServer2000Driver(this IConnectionConfiguration cfg) + { + return cfg.By(); + } + + public static void SqlServer2000Driver(this IDbIntegrationConfigurationProperties cfg) + { + cfg.Driver(); + } + + public static IConnectionConfiguration BySqlServer2008Driver(this IConnectionConfiguration cfg) + { + return cfg.By(); + } + + public static void SqlServer2008Driver(this IDbIntegrationConfigurationProperties cfg) + { + cfg.Driver(); + } + } +} diff --git a/src/NHibernate.Driver.SqlServer/NHibernate.Driver.SqlServer.csproj b/src/NHibernate.Driver.SqlServer/NHibernate.Driver.SqlServer.csproj new file mode 100644 index 00000000000..76cc2ec447b --- /dev/null +++ b/src/NHibernate.Driver.SqlServer/NHibernate.Driver.SqlServer.csproj @@ -0,0 +1,49 @@ + + + + + Driver for Microsoft SQL Server to be used with NHibernate 5. + NHibernate; Driver; SqlClient; SqlServer; SQL Server; ADO.Net; Core + + netstandard2.0;net461 + true + $(NoWarn);3001;3002;3003;3005;1591 + True + true + ..\NHibernate.snk + true + True + + + true + + + + $(DefineConstants);DRIVER_PACKAGE + NHibernate + + + + + + + + + + + + + + + + + + + + + + NHibernate.license.txt + + + + diff --git a/src/NHibernate.Driver.SqlServer/Properties/AssemblyInfo.cs b/src/NHibernate.Driver.SqlServer/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..71b3de6ca17 --- /dev/null +++ b/src/NHibernate.Driver.SqlServer/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +using System; +using System.Reflection; +using System.Security; + +[assembly: CLSCompliantAttribute(true)] +[assembly: AssemblyDelaySignAttribute(false)] +[assembly: AllowPartiallyTrustedCallersAttribute()] +[assembly: SecurityRulesAttribute(SecurityRuleSet.Level1)] diff --git a/src/NHibernate.Everything.sln b/src/NHibernate.Everything.sln index 234a401f88f..6770d479795 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 15 -VisualStudioVersion = 15.0.26730.12 +VisualStudioVersion = 15.0.27004.2010 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Support", "Support", "{9BDB5C84-14EC-4384-B423-9E319675B3CA}" ProjectSection(SolutionItems) = preProject @@ -71,6 +71,22 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Tool.HbmXsd", "N EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "NHibernate.Test.VisualBasic", "NHibernate.Test.VisualBasic\NHibernate.Test.VisualBasic.vbproj", "{7C2EF610-BCA0-4D1F-898A-DE9908E4970C}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Drivers", "Drivers", "{A47739AF-6D04-45AA-B688-4E39CDE48FFD}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.Firebird", "NHibernate.Driver.Firebird\NHibernate.Driver.Firebird.csproj", "{DADD54C1-3679-4672-9774-9362428EB9E0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.MySql", "NHibernate.Driver.MySql\NHibernate.Driver.MySql.csproj", "{4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.PostgreSql", "NHibernate.Driver.PostgreSql\NHibernate.Driver.PostgreSql.csproj", "{C7C835DC-0A59-4227-9C3C-0AF0633CD68C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.Oracle.Managed", "NHibernate.Driver.Oracle.Managed\NHibernate.Driver.Oracle.Managed.csproj", "{22409381-1808-4F0A-9C42-9FAA6B3BCFA2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SQLite", "NHibernate.Driver.SQLite\NHibernate.Driver.SQLite.csproj", "{99FE5A5C-F732-40A3-BEE6-ED5ADC393862}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SqlServer", "NHibernate.Driver.SqlServer\NHibernate.Driver.SqlServer.csproj", "{CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SqlServer.Compact", "NHibernate.Driver.SqlServer.Compact\NHibernate.Driver.SqlServer.Compact.csproj", "{11B3C504-D501-4766-AC36-0CF1A813815B}" +EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Example.Web", "NHibernate.Example.Web\NHibernate.Example.Web.csproj", "{B291C1C1-599B-418E-8591-8A8CF1CAA188}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.TestDatabaseSetup", "NHibernate.TestDatabaseSetup\NHibernate.TestDatabaseSetup.csproj", "{783DB85E-2EED-4377-8EF4-8D6EFE042007}" @@ -134,6 +150,90 @@ 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 + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|.NET.ActiveCfg = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|.NET.Build.0 = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|.NET.ActiveCfg = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|.NET.Build.0 = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Any CPU.Build.0 = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|.NET.ActiveCfg = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|.NET.Build.0 = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|.NET.ActiveCfg = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|.NET.Build.0 = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Any CPU.Build.0 = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|.NET.ActiveCfg = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|.NET.Build.0 = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|.NET.ActiveCfg = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|.NET.Build.0 = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Any CPU.Build.0 = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|.NET.ActiveCfg = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|.NET.Build.0 = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|.NET.ActiveCfg = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|.NET.Build.0 = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Any CPU.Build.0 = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|.NET.ActiveCfg = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|.NET.Build.0 = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Any CPU.Build.0 = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|.NET.ActiveCfg = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|.NET.Build.0 = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Any CPU.ActiveCfg = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Any CPU.Build.0 = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|.NET.ActiveCfg = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|.NET.Build.0 = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|.NET.ActiveCfg = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|.NET.Build.0 = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Any CPU.Build.0 = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|.NET.ActiveCfg = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|.NET.Build.0 = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|.NET.ActiveCfg = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|.NET.Build.0 = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Any CPU.Build.0 = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Mixed Platforms.Build.0 = Release|Any CPU {B291C1C1-599B-418E-8591-8A8CF1CAA188}.Debug|.NET.ActiveCfg = Debug|Any CPU {B291C1C1-599B-418E-8591-8A8CF1CAA188}.Debug|.NET.Build.0 = Debug|Any CPU {B291C1C1-599B-418E-8591-8A8CF1CAA188}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -173,6 +273,14 @@ Global {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} + {A47739AF-6D04-45AA-B688-4E39CDE48FFD} = {28EA2C84-8295-49ED-BC67-803B7778513E} + {DADD54C1-3679-4672-9774-9362428EB9E0} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} + {11B3C504-D501-4766-AC36-0CF1A813815B} = {A47739AF-6D04-45AA-B688-4E39CDE48FFD} {783DB85E-2EED-4377-8EF4-8D6EFE042007} = {094F74CD-2DD7-496F-BC48-A6D357BF33FD} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs b/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs index 38265648eda..f783e670153 100644 --- a/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs +++ b/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs @@ -24,7 +24,7 @@ public AppSessionFactory(Microsoft.Extensions.Logging.ILoggerFactory loggerFacto { db.ConnectionString = @"Server=(local)\SQLEXPRESS;initial catalog=nhibernate;Integrated Security=true"; db.Dialect(); - db.Driver(); + db.SqlServer2008Driver(); }) .AddMapping(domainMapping); Configuration.SessionFactory().GenerateStatistics(); diff --git a/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj b/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj index 72eaca60cb2..f08d2ed5700 100644 --- a/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj +++ b/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj @@ -1,7 +1,8 @@ - net461 + netcoreapp2.0;net461 + true @@ -14,6 +15,7 @@ + @@ -23,6 +25,7 @@ + diff --git a/src/NHibernate.Example.Web/Pages/_Layout.cshtml b/src/NHibernate.Example.Web/Pages/_Layout.cshtml index 55a0c2f1ba1..7db516fb7d5 100644 --- a/src/NHibernate.Example.Web/Pages/_Layout.cshtml +++ b/src/NHibernate.Example.Web/Pages/_Layout.cshtml @@ -32,6 +32,10 @@ @RenderBody() - @RenderSection("Scripts", required: false) +

+ @Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.RuntimeFramework +

+ +@RenderSection("Scripts", required: false) diff --git a/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj b/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj index d95d8dd583e..571df46e5c9 100644 --- a/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj +++ b/src/NHibernate.Test.VisualBasic/NHibernate.Test.VisualBasic.vbproj @@ -2,12 +2,15 @@ The Visual Basic Unit Tests for NHibernate. - net461 + netcoreapp2.0;net461 true $(NoWarn);3001;3002;3003;3005 On On + + + @@ -19,6 +22,9 @@ + + + diff --git a/src/NHibernate.Test/Ado/BatcherFixture.cs b/src/NHibernate.Test/Ado/BatcherFixture.cs index c3ddc1dd8f8..bb337051b7e 100644 --- a/src/NHibernate.Test/Ado/BatcherFixture.cs +++ b/src/NHibernate.Test/Ado/BatcherFixture.cs @@ -90,8 +90,12 @@ public void OneRoundTripUpdate() [Description("SqlClient: The batcher should run all different INSERT queries in only one roundtrip.")] public void SqlClientOneRoundTripForUpdateAndInsert() { +#if !NETCOREAPP2_0 if (Sfi.Settings.BatcherFactory is SqlClientBatchingBatcherFactory == false) +#endif + { Assert.Ignore("This test is for SqlClientBatchingBatcher only"); + } FillDb(); @@ -128,8 +132,12 @@ public void SqlClientOneRoundTripForUpdateAndInsert() [Description("SqlClient: The batcher log output should be formatted")] public void BatchedoutputShouldBeFormatted() { +#if !NETCOREAPP2_0 if (Sfi.Settings.BatcherFactory is SqlClientBatchingBatcherFactory == false) +#endif + { Assert.Ignore("This test is for SqlClientBatchingBatcher only"); + } using (var sqlLog = new SqlLogSpy()) { diff --git a/src/NHibernate.Test/App.config b/src/NHibernate.Test/App.config index 0db5a1028c3..f4d83fa9a47 100644 --- a/src/NHibernate.Test/App.config +++ b/src/NHibernate.Test/App.config @@ -30,8 +30,8 @@ NHibernate.Dialect.MsSql2008Dialect - NHibernate.Driver.Sql2008ClientDriver - TestConnectionString + NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer + Server=localhost\sqlexpress;Database=nhibernate;Integrated Security=SSPI NHibernate.Test.DebugConnectionProvider, NHibernate.Test ReadCommitted @@ -50,53 +50,10 @@ false 444 -
+
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + diff --git a/src/NHibernate.Test/Async/Ado/BatcherFixture.cs b/src/NHibernate.Test/Async/Ado/BatcherFixture.cs index 36ab6e40928..b3672bfe5a7 100644 --- a/src/NHibernate.Test/Async/Ado/BatcherFixture.cs +++ b/src/NHibernate.Test/Async/Ado/BatcherFixture.cs @@ -102,8 +102,12 @@ public async Task OneRoundTripUpdateAsync() [Description("SqlClient: The batcher should run all different INSERT queries in only one roundtrip.")] public async Task SqlClientOneRoundTripForUpdateAndInsertAsync() { +#if !NETCOREAPP2_0 if (Sfi.Settings.BatcherFactory is SqlClientBatchingBatcherFactory == false) +#endif + { Assert.Ignore("This test is for SqlClientBatchingBatcher only"); + } await (FillDbAsync()); @@ -140,8 +144,12 @@ public async Task SqlClientOneRoundTripForUpdateAndInsertAsync() [Description("SqlClient: The batcher log output should be formatted")] public async Task BatchedoutputShouldBeFormattedAsync() { +#if !NETCOREAPP2_0 if (Sfi.Settings.BatcherFactory is SqlClientBatchingBatcherFactory == false) +#endif + { Assert.Ignore("This test is for SqlClientBatchingBatcher only"); + } using (var sqlLog = new SqlLogSpy()) { diff --git a/src/NHibernate.Test/Async/CfgTest/ConfigurationFixture.cs b/src/NHibernate.Test/Async/CfgTest/ConfigurationFixture.cs index 9855db73094..8a4e813eab4 100644 --- a/src/NHibernate.Test/Async/CfgTest/ConfigurationFixture.cs +++ b/src/NHibernate.Test/Async/CfgTest/ConfigurationFixture.cs @@ -44,7 +44,7 @@ public async Task ManualConfigurationAsync() props[Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider"; props[Environment.Dialect] = "NHibernate.Dialect.MsSql2000Dialect"; - props[Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver"; + props[Environment.ConnectionDriver] = "NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer"; props[Environment.ConnectionString] = "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI"; diff --git a/src/NHibernate.Test/Async/Component/Basic/ComponentWithUniqueConstraintTests.cs b/src/NHibernate.Test/Async/Component/Basic/ComponentWithUniqueConstraintTests.cs index 67b894915fb..79bb93c6ce1 100644 --- a/src/NHibernate.Test/Async/Component/Basic/ComponentWithUniqueConstraintTests.cs +++ b/src/NHibernate.Test/Async/Component/Basic/ComponentWithUniqueConstraintTests.cs @@ -10,7 +10,6 @@ using System; using System.Data.Common; -using System.Data.Odbc; using System.Data.SqlClient; using System.Linq; using NHibernate.Cfg.MappingSchema; diff --git a/src/NHibernate.Test/Async/ConnectionTest/AggressiveReleaseTest.cs b/src/NHibernate.Test/Async/ConnectionTest/AggressiveReleaseTest.cs index 5f96e80f92d..37d0e5a1c68 100644 --- a/src/NHibernate.Test/Async/ConnectionTest/AggressiveReleaseTest.cs +++ b/src/NHibernate.Test/Async/ConnectionTest/AggressiveReleaseTest.cs @@ -56,6 +56,9 @@ protected override void Done() // Some additional tests specifically for the aggressive-Release functionality... [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public async Task SerializationOnAfterStatementAggressiveReleaseAsync() { Prepare(); @@ -77,6 +80,9 @@ public async Task SerializationOnAfterStatementAggressiveReleaseAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public async Task SerializationFailsOnAfterStatementAggressiveReleaseWithOpenResourcesAsync() { Prepare(); @@ -258,4 +264,4 @@ public async Task ConnectionMaintanenceDuringFlushAsync() Done(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/DriverTest/FirebirdClientDriverFixture.cs b/src/NHibernate.Test/Async/DriverTest/FirebirdClientDriverFixture.cs index 734866bda0c..cb0ab53d9cc 100644 --- a/src/NHibernate.Test/Async/DriverTest/FirebirdClientDriverFixture.cs +++ b/src/NHibernate.Test/Async/DriverTest/FirebirdClientDriverFixture.cs @@ -21,10 +21,10 @@ namespace NHibernate.Test.DriverTest using System.Threading.Tasks; using System.Threading; [TestFixture] - public class FirebirdClientDriverFixtureAsync + public class FirebirdDriverFixtureAsync { private string _connectionString; - private FirebirdClientDriver _driver; + private FirebirdDriver _driver; [OneTimeSetUp] public void OneTimeSetup() @@ -35,7 +35,7 @@ public void OneTimeSetup() if (!dlct.Contains("Firebird")) Assert.Ignore("Applies only to Firebird"); - _driver = new FirebirdClientDriver(); + _driver = new FirebirdDriver(); _driver.Configure(cfg.Properties); _connectionString = cfg.GetProperty("connection.connection_string"); } diff --git a/src/NHibernate.Test/Async/DriverTest/ObsoleteDriverFixture.cs b/src/NHibernate.Test/Async/DriverTest/ObsoleteDriverFixture.cs new file mode 100644 index 00000000000..09fa703e1da --- /dev/null +++ b/src/NHibernate.Test/Async/DriverTest/ObsoleteDriverFixture.cs @@ -0,0 +1,101 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by AsyncGenerator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +using System; +using System.Collections; +using System.Linq.Dynamic.Core; +using NHibernate.Cfg; +using NHibernate.Connection; +using NHibernate.Dialect; +using NHibernate.DomainModel; +using NHibernate.Driver; +using NHibernate.Util; +using NUnit.Framework; + +namespace NHibernate.Test.DriverTest +{ + using System.Threading.Tasks; + [TestFixture, Obsolete] + public class ObsoleteDriverFixtureAsync : TestCase + { + protected override IList Mappings => new [] {"Simple.hbm.xml"}; + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + switch (dialect) + { + case FirebirdDialect _: + case MsSql2000Dialect _: + case MsSqlCeDialect _: + case MySQLDialect _: + case PostgreSQLDialect _: + case SQLiteDialect _: + System.Type driverType = ReflectHelper.ClassForName(cfg.GetProperty(Cfg.Environment.ConnectionDriver)); + return !(driverType.IsOdbcDriver() || driverType.IsOleDbDriver()); + default: + return false; + } + } + + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + + System.Type driverType = ReflectHelper.ClassForName(cfg.GetProperty(Cfg.Environment.ConnectionDriver)); + if (driverType.IsOdbcDriver() || driverType.IsOleDbDriver()) + { + // ODBC and OLE DB drivers are not obsoleted, do not switch it. + return; + } + + var dialect = NHibernate.Dialect.Dialect.GetDialect(configuration.Properties); + System.Type driver; + switch (dialect) + { + case FirebirdDialect _: + driver = typeof(FirebirdClientDriver); + break; + case MsSql2008Dialect _: + driver = typeof(Sql2008ClientDriver); + break; + case MsSql2000Dialect _: + driver = typeof(SqlClientDriver); + break; + case MsSqlCeDialect _: + driver = typeof(SqlServerCeDriver); + break; + case MySQLDialect _: + driver = typeof(MySqlDataDriver); + break; + case PostgreSQLDialect _: + driver = typeof(NpgsqlDriver); + break; + case SQLiteDialect _: + driver = typeof(SQLite20Driver); + break; + default: + return; + } + configuration.SetProperty(Cfg.Environment.ConnectionDriver, driver.FullName); + } + + [Test] + public async Task CanUseObsoleteDriverAsync() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var count = s.Query().Count(); + Assert.That(count, Is.Zero); + await (t.CommitAsync()); + } + } + } +} diff --git a/src/NHibernate.Test/Async/DriverTest/OdbcDriverFixture.cs b/src/NHibernate.Test/Async/DriverTest/OdbcDriverFixture.cs index a0f0f8664f9..c84f4526918 100644 --- a/src/NHibernate.Test/Async/DriverTest/OdbcDriverFixture.cs +++ b/src/NHibernate.Test/Async/DriverTest/OdbcDriverFixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +#if !NETCOREAPP2_0 using System; using System.Collections; using NHibernate.Dialect; @@ -115,3 +116,4 @@ public async Task CrudAsync() } } } +#endif diff --git a/src/NHibernate.Test/Async/DriverTest/SqlClientDriverFixture.cs b/src/NHibernate.Test/Async/DriverTest/SqlServerDriverFixture.cs similarity index 97% rename from src/NHibernate.Test/Async/DriverTest/SqlClientDriverFixture.cs rename to src/NHibernate.Test/Async/DriverTest/SqlServerDriverFixture.cs index 62fe9232900..53b45fef2ea 100644 --- a/src/NHibernate.Test/Async/DriverTest/SqlClientDriverFixture.cs +++ b/src/NHibernate.Test/Async/DriverTest/SqlServerDriverFixture.cs @@ -23,7 +23,7 @@ namespace NHibernate.Test.DriverTest using System.Threading.Tasks; [TestFixture] - public class SqlClientDriverFixtureAsync : TestCase + public class SqlServerDriverFixtureAsync : TestCase { protected override string MappingsAssembly => "NHibernate.Test"; @@ -36,7 +36,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void OnTearDown() diff --git a/src/NHibernate.Test/Async/DynamicProxyTests/PeVerifyFixture.cs b/src/NHibernate.Test/Async/DynamicProxyTests/PeVerifyFixture.cs index eaaead249a5..b84cd37ce81 100644 --- a/src/NHibernate.Test/Async/DynamicProxyTests/PeVerifyFixture.cs +++ b/src/NHibernate.Test/Async/DynamicProxyTests/PeVerifyFixture.cs @@ -27,6 +27,9 @@ public class PeVerifyFixtureAsync private const string assemblyFileName = "peVerifyAssembly.dll"; [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public Task VerifyClassWithPublicConstructorAsync() { try @@ -47,6 +50,9 @@ public Task VerifyClassWithPublicConstructorAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public Task VerifyClassWithProtectedConstructorAsync() { try @@ -113,18 +119,30 @@ public SavingProxyAssemblyBuilder(string assemblyName) public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AppDomain.DefineDynamicModule not supported on this platform."); +#else AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; return appDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), access, TestContext.CurrentContext.TestDirectory); +#endif } public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AssemblyBuilder.DefineDynamicModule not supported on this platform."); +#else return assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", assemblyName), true); +#endif } public void Save(AssemblyBuilder assemblyBuilder) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AssemblyBuilder.Save not supported on this platform."); +#else assemblyBuilder.Save(assemblyName + ".dll"); +#endif } } diff --git a/src/NHibernate.Test/Async/ExceptionsTest/SQLExceptionConversionTest.cs b/src/NHibernate.Test/Async/ExceptionsTest/SQLExceptionConversionTest.cs index fd65322ce8a..0903a901929 100644 --- a/src/NHibernate.Test/Async/ExceptionsTest/SQLExceptionConversionTest.cs +++ b/src/NHibernate.Test/Async/ExceptionsTest/SQLExceptionConversionTest.cs @@ -13,7 +13,6 @@ using System.Data; using System.Data.Common; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Exceptions; using NHibernate.Util; @@ -43,7 +42,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { var driver = factory.ConnectionProvider.Driver; - return !(driver is OracleDataClientDriver) && !(driver is OracleManagedDataClientDriver) && !(driver is OracleLiteDataClientDriver) && !(driver is OdbcDriver) && !(driver is OleDbDriver); + return !(driver.IsOracleDataClientDriver()) && !(driver.IsOracleManagedDriver()) && !(driver.IsOracleLiteDataClientDriver()) && !(driver.IsOdbcDriver()) && !(driver.IsOleDbDriver()); } protected override void Configure(Cfg.Configuration configuration) @@ -57,9 +56,13 @@ protected override void Configure(Cfg.Configuration configuration) if (Dialect is Oracle8iDialect) { +#if !NETCOREAPP2_0 configuration.SetProperty( Cfg.Environment.SqlExceptionConverter, typeof(OracleClientExceptionConverterExample).AssemblyQualifiedName); +#else + throw new InvalidOperationException("Oracle8iDialect not valid in NETCOREAPP2_0"); +#endif } if (Dialect is PostgreSQLDialect) diff --git a/src/NHibernate.Test/Async/Futures/FallbackFixture.cs b/src/NHibernate.Test/Async/Futures/FallbackFixture.cs index 80a2d1b6156..5447431883e 100644 --- a/src/NHibernate.Test/Async/Futures/FallbackFixture.cs +++ b/src/NHibernate.Test/Async/Futures/FallbackFixture.cs @@ -24,7 +24,7 @@ namespace NHibernate.Test.Futures using System.Threading; /// - /// I'm using a Driver which derives from SqlClientDriver to + /// I'm using a Driver which derives from SqlServer2000Driver to /// return false for the SupportsMultipleQueries property. This is purely to test the way NHibernate /// will behave when the driver that's being used does not support multiple queries... so even though /// the test is using MsSql, it's only relevant for databases that don't support multiple queries @@ -46,7 +46,7 @@ protected override void Configure(Configuration configuration) base.Configure(configuration); using (var cp = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties)) { - if (cp.Driver is SqlClientDriver) + if (cp.Driver.IsSqlServerDriver()) { configuration.Properties[Environment.ConnectionDriver] = typeof(TestDriverThatDoesntSupportQueryBatching).AssemblyQualifiedName; diff --git a/src/NHibernate.Test/Async/Hql/Ast/LimitClauseFixture.cs b/src/NHibernate.Test/Async/Hql/Ast/LimitClauseFixture.cs index 90d885db753..f9ceb3a0c7e 100644 --- a/src/NHibernate.Test/Async/Hql/Ast/LimitClauseFixture.cs +++ b/src/NHibernate.Test/Async/Hql/Ast/LimitClauseFixture.cs @@ -10,7 +10,6 @@ using System.Linq; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Hql.Ast.ANTLR; using NHibernate.Util; using NUnit.Framework; @@ -25,7 +24,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) { return dialect.SupportsVariableLimit && !(Dialect is Dialect.MsSql2000Dialect && // don't know why, but these tests don't work on SQL Server using ODBC - typeof(OdbcDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))); + ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Async/Insertordering/InsertOrderingFixture.cs b/src/NHibernate.Test/Async/Insertordering/InsertOrderingFixture.cs index 79382c114d1..7b6d8f5b865 100644 --- a/src/NHibernate.Test/Async/Insertordering/InsertOrderingFixture.cs +++ b/src/NHibernate.Test/Async/Insertordering/InsertOrderingFixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +#if !NETCOREAPP2_0 using System; using System.Collections; using System.Collections.Generic; @@ -18,7 +19,6 @@ using NHibernate.AdoNet; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.SqlTypes; @@ -52,7 +52,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Custom batcher does not support oledb driver. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void Configure(Configuration configuration) @@ -733,3 +733,4 @@ protected override System.Threading.Tasks.Task DoExecuteBatchAsync(DbCommand ps, } } +#endif diff --git a/src/NHibernate.Test/Async/Legacy/FooBarTest.cs b/src/NHibernate.Test/Async/Legacy/FooBarTest.cs index ce7e63c27ec..b8381cc8ed7 100644 --- a/src/NHibernate.Test/Async/Legacy/FooBarTest.cs +++ b/src/NHibernate.Test/Async/Legacy/FooBarTest.cs @@ -2842,6 +2842,13 @@ public async Task PersistCollectionsAsync() // serialize and then deserialize the session. Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); + +#if NETCOREAPP2_0 + var ss = new SurrogateSelector(); + CultureInfoSerializationSurrogate.Add(ss); + formatter.SurrogateSelector = ss; +#endif + formatter.Serialize(stream, s); s.Close(); @@ -4652,6 +4659,9 @@ public async Task SaveDeleteAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public async Task ProxyArrayAsync() { ISession s = OpenSession(); diff --git a/src/NHibernate.Test/Async/Legacy/MasterDetailTest.cs b/src/NHibernate.Test/Async/Legacy/MasterDetailTest.cs index bd003e036e5..658061c2d10 100644 --- a/src/NHibernate.Test/Async/Legacy/MasterDetailTest.cs +++ b/src/NHibernate.Test/Async/Legacy/MasterDetailTest.cs @@ -638,6 +638,9 @@ public async Task NamedQueryAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public async Task SerializationAsync() { ISession s = OpenSession(); diff --git a/src/NHibernate.Test/Async/Linq/ByMethod/GroupByTests.cs b/src/NHibernate.Test/Async/Linq/ByMethod/GroupByTests.cs index ca1c7c8985d..ac24728d7fb 100644 --- a/src/NHibernate.Test/Async/Linq/ByMethod/GroupByTests.cs +++ b/src/NHibernate.Test/Async/Linq/ByMethod/GroupByTests.cs @@ -15,7 +15,6 @@ using System.Text.RegularExpressions; using NHibernate.Dialect; using NHibernate.DomainModel.Northwind.Entities; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -562,7 +561,7 @@ public async Task GroupByComputedValueAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.Orders.GroupBy(o => o.Customer.CustomerId == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -574,7 +573,7 @@ public async Task GroupByComputedValueInAnonymousTypeAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.Orders.GroupBy(o => new { Key = o.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -586,7 +585,7 @@ public async Task GroupByComputedValueInObjectArrayAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.Orders.GroupBy(o => new[] { o.Customer.CustomerId == null ? 0 : 1, }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -715,7 +714,7 @@ public async Task GroupByComputedValueWithJoinOnObjectAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => o.Order.Customer == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -727,7 +726,7 @@ public async Task GroupByComputedValueWithJoinOnIdAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => o.Order.Customer.CustomerId == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -739,7 +738,7 @@ public async Task GroupByComputedValueInAnonymousTypeWithJoinOnObjectAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => new { Key = o.Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -751,7 +750,7 @@ public async Task GroupByComputedValueInAnonymousTypeWithJoinOnIdAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => new { Key = o.Order.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -763,7 +762,7 @@ public async Task GroupByComputedValueInObjectArrayWithJoinOnObjectAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => new[] { o.Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -775,7 +774,7 @@ public async Task GroupByComputedValueInObjectArrayWithJoinOnIdAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => new[] { o.Order.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -787,7 +786,7 @@ public async Task GroupByComputedValueInObjectArrayWithJoinInRightSideOfCaseAsyn { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.GroupBy(o => new[] { o.Order.Customer.CustomerId == null ? "unknown" : o.Order.Customer.CompanyName }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -799,7 +798,7 @@ public async Task GroupByComputedValueFromNestedArraySelectAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.Select(o => new object[] { o }).GroupBy(x => new object[] { ((OrderLine)x[0]).Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); @@ -811,7 +810,7 @@ public async Task GroupByComputedValueFromNestedObjectSelectAsync() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = await (db.OrderLines.Select(o => new { OrderLine = (object)o }).GroupBy(x => new object[] { ((OrderLine)x.OrderLine).Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToListAsync()); diff --git a/src/NHibernate.Test/Async/Linq/FunctionTests.cs b/src/NHibernate.Test/Async/Linq/FunctionTests.cs index 9562531698c..3aeec24ec0a 100644 --- a/src/NHibernate.Test/Async/Linq/FunctionTests.cs +++ b/src/NHibernate.Test/Async/Linq/FunctionTests.cs @@ -323,6 +323,11 @@ public async Task TrimAsync() Assert.AreEqual(1, await (session.Query().CountAsync(e => e.Input.TrimStart('h') == "eh"))); Assert.AreEqual(1, await (session.Query().CountAsync(e => e.Input.TrimEnd('h') == "he"))); + // Check when passed as array (new overloads in .NET Core App 2.0). + Assert.AreEqual(1, await (session.Query().CountAsync(e => e.Input.Trim(new [] { 'h' }) == "e"))); + Assert.AreEqual(1, await (session.Query().CountAsync(e => e.Input.TrimStart(new[] { 'h' }) == "eh"))); + Assert.AreEqual(1, await (session.Query().CountAsync(e => e.Input.TrimEnd(new[] { 'h' }) == "he"))); + // Let it rollback to get rid of temporary changes. } } diff --git a/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetFixture.cs index 587100668c1..d0508910baa 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetFixture.cs @@ -14,7 +14,6 @@ using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; -using NHibernate.Driver; using NHibernate.Type; using NUnit.Framework; @@ -33,7 +32,7 @@ protected override IList Mappings protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - if (factory.ConnectionProvider.Driver is OdbcDriver) + if (factory.ConnectionProvider.Driver.IsOdbcDriver()) return false; return base.AppliesTo(factory); diff --git a/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs index 3af6e8995e8..f2ec239effe 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs @@ -12,7 +12,6 @@ using System.Collections; using System.Data; using System.Linq; -using NHibernate.Driver; using NHibernate.Type; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -32,7 +31,7 @@ protected override IList Mappings protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - if (factory.ConnectionProvider.Driver is OdbcDriver) + if (factory.ConnectionProvider.Driver.IsOdbcDriver()) return false; return base.AppliesTo(factory); diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs index 1e8dc255183..74ab0f13fc1 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs @@ -11,7 +11,6 @@ using log4net.Core; using NHibernate.AdoNet; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Util; using NUnit.Framework; @@ -37,7 +36,7 @@ protected override void Configure(Configuration configuration) [Test] public async Task CanSaveInSingleBatchAsync() { - if (!typeof(OracleDataClientDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))) + if (!ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsOracleDataClientDriver()) { Assert.Ignore("Only applicable for Oracle Data Client driver"); } diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1507/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1507/Fixture.cs index 48a864ef62c..73d2eb90247 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1507/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1507/Fixture.cs @@ -10,7 +10,6 @@ using System; using System.Collections; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1507 @@ -21,7 +20,7 @@ public class FixtureAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -128,4 +127,4 @@ public async Task ImplicitJoinFailingTestAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs index ad82ceb33c0..0c3cc4ed7a1 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs @@ -11,7 +11,6 @@ using System.Data; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; using NUnit.Framework.Constraints; @@ -156,7 +155,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) { // SQLUpdateConflictToStaleStateExceptionConverter is specific to Sql client driver, and does not work // with Odbc (and likeley Oledb). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } private void SetAllowSnapshotIsolation(bool on) @@ -206,4 +205,4 @@ protected override void Configure(Configuration configuration) typeof (SQLUpdateConflictToStaleStateExceptionConverter).AssemblyQualifiedName); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1632/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1632/Fixture.cs index d1b38098ad5..5bf96343e07 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1632/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1632/Fixture.cs @@ -37,6 +37,9 @@ protected override void Configure(Configuration configuration) } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task When_using_DTC_HiLo_knows_to_create_isolated_DTC_transactionAsync() { if (!Dialect.SupportsConcurrentWritingConnections) @@ -76,8 +79,10 @@ public async Task When_using_DTC_HiLo_knows_to_create_isolated_DTC_transactionAs Assert.AreNotEqual(scalar1, scalar2, "HiLo must run with in its own transaction"); } - [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task When_commiting_items_in_DTC_transaction_will_add_items_to_2nd_level_cacheAsync() { using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) @@ -131,6 +136,9 @@ public async Task When_commiting_items_in_DTC_transaction_will_add_items_to_2nd_ } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task When_committing_transaction_scope_will_commit_transactionAsync() { object id; @@ -178,6 +186,9 @@ public async Task Will_not_save_when_flush_mode_is_neverAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task When_using_two_sessions_with_explicit_flushAsync() { if (!Dialect.SupportsConcurrentWritingConnectionsInSameTransaction) @@ -218,6 +229,9 @@ public async Task When_using_two_sessions_with_explicit_flushAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task When_using_two_sessionsAsync() { if (!Dialect.SupportsConcurrentWritingConnectionsInSameTransaction) diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1756/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1756/Fixture.cs index ae654b85b77..933c703d5a0 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1756/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1756/Fixture.cs @@ -10,7 +10,6 @@ using System.Collections.Generic; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -41,7 +40,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) // N'@P1 nvarchar(18),@P2 int,@P3 datetime2',N'modified test book',1,'2017-08-02 16:37:16.0630000' // Setting the scale to 2 still causes failure for two thirds of tries, due to 3ms/7ms being truncated in such case // with ODBC and SQL Server 2008+ Client, which is rejected by ODBC. - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1850/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1850/Fixture.cs index ba9f0a8f99a..797f3dce0b2 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1850/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1850/Fixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +#if !NETCOREAPP2_0 using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1850 @@ -106,3 +107,4 @@ public async Task CanGetQueryDurationForSelectAsync() } } } +#endif diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2020/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2020/Fixture.cs index f3376f32a6d..13ba3c2e024 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2020/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2020/Fixture.cs @@ -10,7 +10,6 @@ using NUnit.Framework; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Test.ExceptionsTest; using NHibernate.Engine; @@ -37,7 +36,7 @@ protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Use a SQL Server Client exception converter, cannot work for ODBC or OleDb - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void OnTearDown() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2057/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2057/Fixture.cs index 866d12ad443..f333c98d4fa 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2057/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2057/Fixture.cs @@ -19,6 +19,9 @@ namespace NHibernate.Test.NHSpecificTest.NH2057 public class FixtureAsync : BugTestCase { [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task WillCloseWhenUsingDTCAsync() { ISession s; diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2176/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2176/Fixture.cs index ad9036fc089..5bcc85e1e75 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2176/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2176/Fixture.cs @@ -56,6 +56,9 @@ protected override void OnTearDown() // Whilst this bug seems specific to Oracle I think it is valid to run the // test against all database types. [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task MultipleConsecutiveTransactionScopesCanBeUsedInsideASingleSessionAsync() { using (var s = OpenSession()) @@ -84,4 +87,4 @@ public async Task MultipleConsecutiveTransactionScopesCanBeUsedInsideASingleSess } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2207/SampleTest.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2207/SampleTest.cs index dd26d362887..328cab94add 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2207/SampleTest.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2207/SampleTest.cs @@ -11,7 +11,6 @@ using System; using System.Data; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -29,7 +28,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is Sql2008ClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServer2008Driver(); } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2296/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2296/Fixture.cs index 28a2d60d9c5..792fcbe4924 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2296/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2296/Fixture.cs @@ -9,7 +9,6 @@ using System.Linq; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH2296 @@ -20,7 +19,7 @@ public class FixtureAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -84,4 +83,4 @@ public async Task TestAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2302/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2302/Fixture.cs index df16c52023c..2ca311d4ae5 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2302/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2302/Fixture.cs @@ -10,7 +10,6 @@ using System.Data; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Mapping; using NUnit.Framework; @@ -49,7 +48,7 @@ protected override void OnTearDown() [Test] public async Task StringHugeLengthAsync() { - if (Sfi.ConnectionProvider.Driver is OdbcDriver || Dialect is MsSqlCeDialect) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver() || Dialect is MsSqlCeDialect) Assert.Ignore("NH-4065, not fixed for Odbc and MsSqlCe"); int id; diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2420/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2420/Fixture.cs index 906b69792ae..d82c823cb14 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2420/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2420/Fixture.cs @@ -9,12 +9,13 @@ using System.Data.Common; +#if !NETCOREAPP2_0 using System.Data.Odbc; +#endif using System.Data.SqlClient; using System.Configuration; using System.Transactions; using NHibernate.Dialect; -using NHibernate.Driver; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -60,6 +61,9 @@ private string FetchConnectionStringFromConfiguration() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransactionAsync() { string connectionString = FetchConnectionStringFromConfiguration(); @@ -76,10 +80,16 @@ public async Task ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransac new DummyEnlistment(), EnlistmentOptions.None); - if (Sfi.ConnectionProvider.Driver.GetType() == typeof(OdbcDriver)) +#if !NETCOREAPP2_0 + if (Sfi.ConnectionProvider.Driver.GetType().IsOdbcDriver()) + { connection = new OdbcConnection(connectionString); + } else +#endif + { connection = new SqlConnection(connectionString); + } await (connection.OpenAsync()); using (s = Sfi.WithOptions().Connection(connection).OpenSession()) diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2660And2661/Test.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2660And2661/Test.cs index d13589002f3..8cc9f87f061 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2660And2661/Test.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2660And2661/Test.cs @@ -50,7 +50,7 @@ protected override void Configure(Configuration configuration) { // to be sure we are using the new drive base.Configure(configuration); - configuration.DataBaseIntegration(x=> x.Driver()); + configuration.DataBaseIntegration(x=> x.Driver()); } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2846/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2846/Fixture.cs index 71a6dd7fb6d..b81144cdfcc 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2846/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2846/Fixture.cs @@ -9,7 +9,6 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -21,7 +20,7 @@ public class FixtureAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2852/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2852/Fixture.cs index 4bd4d82cabe..439c59616f7 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2852/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2852/Fixture.cs @@ -9,7 +9,6 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -21,7 +20,7 @@ public class FixtureAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -92,4 +91,4 @@ public async Task AlsoFailsAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs index 75f13d1a623..2f58671b46c 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs @@ -20,7 +20,6 @@ using log4net.Repository.Hierarchy; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -43,7 +42,7 @@ protected override void Configure(Configuration configuration) // Uses directly SqlConnection. protected override bool AppliesTo(ISessionFactoryImplementor factory) - => factory.ConnectionProvider.Driver is SqlClientDriver && base.AppliesTo(factory); + => factory.ConnectionProvider.Driver.IsSqlServerDriver() && base.AppliesTo(factory); protected override bool AppliesTo(Dialect.Dialect dialect) => dialect is MsSql2000Dialect && base.AppliesTo(dialect); @@ -76,6 +75,19 @@ protected override void OnTearDown() [Theory] public async Task ConnectionPoolCorruptionAfterDeadlockAsync(bool distributed, bool disposeSessionBeforeScope) { + if (distributed) + { +#if NETCOREAPP2_0 + Assert.Ignore("This platform does not support distributed transactions."); +#endif + } + else + { +#if NETCOREAPP2_0 + Assert.Ignore("Enlisting in Ambient transactions is not supported by System.Data.SqlClient."); +#endif + } + var tryCount = 0; var id = 1; do diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3121/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3121/Fixture.cs index 525c4b3d6c2..8649da6a362 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3121/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3121/Fixture.cs @@ -13,7 +13,6 @@ using System.Linq; using System.Reflection; using NHibernate.Dialect; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3121 @@ -36,10 +35,10 @@ protected override bool AppliesTo(Dialect.Dialect dialect) [Test] public void ShouldThrowWhenByteArrayTooLongAsync() { - // For SQL Server only the SqlClientDriver sets parameter lengths + // For SQL Server only the SqlServer2000Driver sets parameter lengths // even when there is no length specified in the mapping. The ODBC // driver won't cause the truncation issue and hence not the exception. - if (!(Sfi.ConnectionProvider.Driver is SqlClientDriver)) + if (!(Sfi.ConnectionProvider.Driver.IsSqlServerDriver())) Assert.Ignore("Test limited to drivers that sets parameter length even with no length specified in the mapping."); const int reportSize = 17158; diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3142/ChildrenTest.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3142/ChildrenTest.cs index c5f420db6de..bf9b00d308a 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3142/ChildrenTest.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3142/ChildrenTest.cs @@ -11,7 +11,6 @@ using System; using System.Collections; using System.Collections.Generic; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3142 @@ -22,7 +21,7 @@ public class ChildrenTestAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3202/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3202/Fixture.cs index 61a8bf45526..68d83fb35dd 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3202/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3202/Fixture.cs @@ -27,7 +27,7 @@ protected override void Configure(Configuration configuration) if (!(Dialect is MsSql2008Dialect)) Assert.Ignore("Test is for MS SQL Server dialect only (custom dialect)."); - if (!typeof(SqlClientDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))) + if (!ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsSqlServerDriver()) Assert.Ignore("Test is for MS SQL Server driver only (custom driver is used)."); cfg.SetProperty(Environment.Dialect, typeof(OffsetStartsAtOneTestDialect).AssemblyQualifiedName); diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3252/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3252/Fixture.cs index 3f2dd8084a8..7f14e8aff3a 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3252/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3252/Fixture.cs @@ -10,7 +10,6 @@ using System; using System.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NUnit.Framework; @@ -23,7 +22,7 @@ public class FixtureAsync : BugTestCase { protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3518/XmlColumnTest.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3518/XmlColumnTest.cs index 31b08659374..556e07df1f0 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3518/XmlColumnTest.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3518/XmlColumnTest.cs @@ -11,7 +11,6 @@ using System.Xml; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -38,7 +37,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void Configure(Configuration configuration) diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3583/AutoFlushFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3583/AutoFlushFixture.cs index 1b3d8a12d40..f05fbf95f62 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3583/AutoFlushFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3583/AutoFlushFixture.cs @@ -61,7 +61,11 @@ public async Task ShouldAutoFlushWhenInExplicitTransactionAsync() Assert.That(result.Count, Is.EqualTo(1)); } } + [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task ShouldAutoFlushWhenInDistributedTransactionAsync() { using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3620/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3620/Fixture.cs index 076371afdfa..f68f378605f 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3620/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3620/Fixture.cs @@ -9,7 +9,6 @@ using System; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3620 { @@ -17,7 +16,7 @@ namespace NHibernate.Test.NHSpecificTest.NH3620 { [TestFixture] public class FixtureAsync : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return (factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return (factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnTearDown() { @@ -52,4 +51,4 @@ private void CleanupData() { } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3844/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3844/Fixture.cs index 006536ab127..461c718c0d0 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3844/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3844/Fixture.cs @@ -9,7 +9,6 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NUnit.Framework; @@ -28,7 +27,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // SQL Server seems unable to match complex group by and select list arguments when running over ODBC."; - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3850/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3850/Fixture.cs index c0ee2b089dd..e95b1dd4740 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3850/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3850/Fixture.cs @@ -15,7 +15,6 @@ using System.Linq; using System.Reflection; using System.Text; -using NHibernate.Driver; using NHibernate.Linq; using NHibernate.SqlTypes; using NHibernate.Util; @@ -42,7 +41,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3912/ReusableBatcherFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3912/ReusableBatcherFixture.cs index d5bbb05a2be..5640cd7e228 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3912/ReusableBatcherFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3912/ReusableBatcherFixture.cs @@ -13,7 +13,6 @@ using NHibernate.AdoNet; using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NHibernate.Mapping.ByCode; @@ -28,9 +27,9 @@ public class ReusableBatcherFixtureAsync : TestCaseMappingByCode protected override bool AppliesTo(ISessionFactoryImplementor factory) { var driver = factory.ConnectionProvider.Driver; - return driver is OracleDataClientDriver || - driver is OracleLiteDataClientDriver || - driver is OracleManagedDataClientDriver; + return driver.IsOracleDataClientDriver() || + driver.IsOracleLiteDataClientDriver() || + driver.IsOracleManagedDriver(); } protected override HbmMapping GetMappings() diff --git a/src/NHibernate.Test/Async/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs index fc8c339848e..9377b0b029f 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs @@ -9,7 +9,6 @@ using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -32,7 +31,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) // tend to (validly) send InvalidOperationException during prepare phase due to the closed // connection, which get not converted. For testing other case, maybe a failure caused by a // schema mismatch (like done in transaction tests) would be better. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/Async/Pagination/CustomDialectFixture.cs b/src/NHibernate.Test/Async/Pagination/CustomDialectFixture.cs index 49bd4e48bfb..e134610cda8 100644 --- a/src/NHibernate.Test/Async/Pagination/CustomDialectFixture.cs +++ b/src/NHibernate.Test/Async/Pagination/CustomDialectFixture.cs @@ -13,7 +13,6 @@ using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Util; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -40,7 +39,7 @@ protected override void Configure(Configuration configuration) if (!(Dialect is MsSql2005Dialect)) Assert.Ignore("Test is for SQL dialect only"); var driverClass = ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)); - if (!typeof(SqlClientDriver).IsAssignableFrom(driverClass)) + if (!driverClass.IsSqlServerDriver()) Assert.Ignore("Test is compatible only with Sql Server Client driver connection strings"); cfg.SetProperty(Environment.Dialect, typeof(CustomMsSqlDialect).AssemblyQualifiedName); @@ -134,4 +133,4 @@ public async Task LimitFirstMultiCriteriaAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/ReadOnly/ReadOnlyCriteriaQueryTest.cs b/src/NHibernate.Test/Async/ReadOnly/ReadOnlyCriteriaQueryTest.cs index 9e070d7cd62..ab1c8659e0a 100644 --- a/src/NHibernate.Test/Async/ReadOnly/ReadOnlyCriteriaQueryTest.cs +++ b/src/NHibernate.Test/Async/ReadOnly/ReadOnlyCriteriaQueryTest.cs @@ -1066,6 +1066,9 @@ public async Task SubselectAsync() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public async Task DetachedCriteriaAsync() { DetachedCriteria dc = NHibernate.Criterion.DetachedCriteria.For() diff --git a/src/NHibernate.Test/Async/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs b/src/NHibernate.Test/Async/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs index c8c2ec8e31b..759606691fa 100644 --- a/src/NHibernate.Test/Async/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs +++ b/src/NHibernate.Test/Async/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs @@ -25,7 +25,7 @@ protected override IList Mappings protected override bool AppliesTo(NHibernate.Engine.ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is Driver.OracleDataClientDriver; + return factory.ConnectionProvider.Driver.IsOracleDataClientDriver(); } protected override bool AppliesTo(Dialect.Dialect dialect) @@ -68,4 +68,4 @@ public async Task RefCursorOutStoredProcedureAsync() } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs b/src/NHibernate.Test/Async/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs index 82c57049d41..f7abdb4e73b 100644 --- a/src/NHibernate.Test/Async/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs +++ b/src/NHibernate.Test/Async/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs @@ -10,7 +10,6 @@ using System.Collections; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -28,7 +27,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Tested resulting SQL depends on driver. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override string GetExpectedInsertOrgLogStatement(string orgName) diff --git a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs index d7080e398ac..de06bae9d66 100644 --- a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs +++ b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs @@ -12,7 +12,6 @@ using System.Collections.Generic; using System.Linq; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Mapping; using NHibernate.Tool.hbm2ddl; @@ -116,7 +115,7 @@ public async Task EnsureReservedWordsHardCodedInDialectAsync() } } - if (sf.ConnectionProvider.Driver is OdbcDriver) + if (sf.ConnectionProvider.Driver.IsOdbcDriver()) { Assert.Inconclusive("ODBC has excess keywords reserved"); } @@ -252,7 +251,7 @@ public async Task WhenConfiguredOnlyExplicitAutoQuoteAsync() var configuration = TestConfigurationHelper.GetDefaultConfiguration(); var driverClass = ReflectHelper.ClassForName(configuration.GetProperty(Environment.ConnectionDriver)); // Test uses the default dialect driver, which will not accept Odbc or OleDb connection strings. - if (typeof(OdbcDriver).IsAssignableFrom(driverClass) || typeof(OleDbDriver).IsAssignableFrom(driverClass)) + if (driverClass.IsOdbcDriver() || driverClass.IsOleDbDriver()) Assert.Ignore("Test is not compatible with OleDb or ODBC driver connection strings"); var configuredDialect = Dialect.Dialect.GetDialect(); diff --git a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs index 6dee59c9771..9b5f2960157 100644 --- a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs +++ b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs @@ -12,7 +12,6 @@ using System.IO; using System.Reflection; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Tool.hbm2ddl; using NHibernate.Util; using NUnit.Framework; @@ -31,7 +30,7 @@ public class MigrationFixtureAsync var driverClass = ReflectHelper.ClassForName(v1cfg.GetProperty(Environment.ConnectionDriver)); // Odbc is not supported by schema update: System.Data.Odbc.OdbcConnection.GetSchema("ForeignKeys") fails with an ArgumentException: ForeignKeys is undefined. // It seems it would require its own DataBaseSchema, but this is bound to the dialect, not the driver. - if (typeof(OdbcDriver).IsAssignableFrom(driverClass)) + if (driverClass.IsOdbcDriver()) Assert.Ignore("Test is not compatible with ODBC"); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1)) @@ -91,4 +90,4 @@ public Task SimpleColumnReplaceAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs index eb1d7d68b18..bdba68e467e 100644 --- a/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs +++ b/src/NHibernate.Test/Async/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs @@ -59,6 +59,7 @@ public Task ShouldVerifySameTableAsync() } } +#if !NETCOREAPP2_0 [Test, SetCulture("tr-TR"), SetUICulture("tr-TR")] public async Task ShouldVerifySameTableTurkishAsync() { @@ -87,6 +88,7 @@ public async Task ShouldVerifySameTableTurkishAsync() await (export.DropAsync(true, true)); } } +#endif [Test] public void ShouldNotVerifyModifiedTableAsync() diff --git a/src/NHibernate.Test/Async/TypesTest/DateTime2TypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/DateTime2TypeFixture.cs index e30eaa872aa..6751cca00c4 100644 --- a/src/NHibernate.Test/Async/TypesTest/DateTime2TypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/DateTime2TypeFixture.cs @@ -9,7 +9,6 @@ using System; -using NHibernate.Driver; using NHibernate.SqlTypes; using NHibernate.Type; using NUnit.Framework; @@ -29,7 +28,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTime2 via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override string TypeName => "DateTime2"; protected override AbstractDateTimeType Type => NHibernateUtil.DateTime2; @@ -44,7 +43,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTime2 via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override string TypeName => "DateTime2WithScale"; protected override AbstractDateTimeType Type => (AbstractDateTimeType)TypeFactory.GetDateTime2Type(3); diff --git a/src/NHibernate.Test/Async/TypesTest/DateTimeOffsetTypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/DateTimeOffsetTypeFixture.cs index a6ef854fad2..bab0c914f73 100644 --- a/src/NHibernate.Test/Async/TypesTest/DateTimeOffsetTypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/DateTimeOffsetTypeFixture.cs @@ -12,7 +12,6 @@ using System.Data; using System.Linq; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.SqlTypes; using NHibernate.Tool.hbm2ddl; using NHibernate.Type; @@ -38,7 +37,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTimeOffset via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override void Configure(Configuration configuration) { diff --git a/src/NHibernate.Test/Async/TypesTest/StringTypeWithLengthFixture.cs b/src/NHibernate.Test/Async/TypesTest/StringTypeWithLengthFixture.cs index be75a5c5805..d75cb3b086c 100644 --- a/src/NHibernate.Test/Async/TypesTest/StringTypeWithLengthFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/StringTypeWithLengthFixture.cs @@ -13,7 +13,6 @@ using NHibernate.Cfg.MappingSchema; using NHibernate.Criterion; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Mapping.ByCode; using NUnit.Framework; @@ -81,7 +80,7 @@ public Task ShouldPreventInsertionOfVeryLongStringThatWouldBeTruncatedAsync() try { // This test case is for when the current driver will use a parameter size - // that is significantly larger than the mapped column size (e.g. SqlClientDriver currently). + // that is significantly larger than the mapped column size (e.g. SqlServer2000Driver currently). // Note: This test could possible be written as // "database must raise an error OR it must store and return the full value" @@ -139,7 +138,7 @@ public async Task CanCompareLongValueWithLongStringAsync() { var maxStringLength = GetLongStringMappedLength(); - if (Sfi.ConnectionProvider.Driver is OdbcDriver && maxStringLength >= 2000) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver() && maxStringLength >= 2000) Assert.Ignore("Odbc wrecks nvarchar parameter types when they are longer than 2000, it switch them to ntext"); var longString = new string('x', maxStringLength); diff --git a/src/NHibernate.Test/Async/TypesTest/XDocTypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/XDocTypeFixture.cs index b7fae9dc5c2..28821d4acaa 100644 --- a/src/NHibernate.Test/Async/TypesTest/XDocTypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/XDocTypeFixture.cs @@ -10,7 +10,6 @@ using System.Data; using System.Xml.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.Type; @@ -35,7 +34,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // No Xml support with Odbc (and likely OleDb too). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/Async/TypesTest/XmlDocTypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/XmlDocTypeFixture.cs index bc975d62590..4ae1da2a9f0 100644 --- a/src/NHibernate.Test/Async/TypesTest/XmlDocTypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/XmlDocTypeFixture.cs @@ -10,7 +10,6 @@ using System.Data; using System.Xml; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.Type; @@ -35,7 +34,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // No Xml support with Odbc (and likely OleDb too). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/CfgTest/ConfigurationFixture.cs b/src/NHibernate.Test/CfgTest/ConfigurationFixture.cs index 73a2b9671f4..a12d520cd85 100644 --- a/src/NHibernate.Test/CfgTest/ConfigurationFixture.cs +++ b/src/NHibernate.Test/CfgTest/ConfigurationFixture.cs @@ -52,7 +52,7 @@ public void ManualConfiguration() props[Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider"; props[Environment.Dialect] = "NHibernate.Dialect.MsSql2000Dialect"; - props[Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver"; + props[Environment.ConnectionDriver] = "NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer"; props[Environment.ConnectionString] = "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI"; @@ -236,7 +236,7 @@ public void InvalidXmlInHbmFile() Configuration cfg = new Configuration(); try { - cfg.Configure(); + cfg.Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); cfg.AddXmlFile("invalid.hbm.xml"); } catch (HibernateException) diff --git a/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs b/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs index f76dbecd9c0..61b7f14f3a7 100644 --- a/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs +++ b/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs @@ -25,6 +25,9 @@ public void InvalidConfig() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support automatically locating app.config from unit tests.")] +#endif public void FromAppConfigTest() { IHibernateConfiguration hc = ConfigurationManager.GetSection("hibernate-configuration") as IHibernateConfiguration; @@ -33,10 +36,19 @@ public void FromAppConfigTest() Assert.AreEqual("NHibernate.Test", hc.SessionFactory.Name); } + [Test] + public void FromConfigForExePathTest() + { + IHibernateConfiguration hc = TestsContext.GetTestAssemblyHibernateConfiguration(); + Assert.That(hc.ByteCodeProviderType, Is.EqualTo("lcg")); + Assert.IsTrue(hc.UseReflectionOptimizer); + Assert.AreEqual("NHibernate.Test", hc.SessionFactory.Name); + } + [Test] public void IgnoreSystemOutOfAppConfig() { - IHibernateConfiguration hc = ConfigurationManager.GetSection("hibernate-configuration") as IHibernateConfiguration; + IHibernateConfiguration hc = TestsContext.GetTestAssemblyHibernateConfiguration(); string xml = @" diff --git a/src/NHibernate.Test/CfgTest/DefaultFlushModeFixture.cs b/src/NHibernate.Test/CfgTest/DefaultFlushModeFixture.cs index 16502f22c5f..37c00508825 100644 --- a/src/NHibernate.Test/CfgTest/DefaultFlushModeFixture.cs +++ b/src/NHibernate.Test/CfgTest/DefaultFlushModeFixture.cs @@ -34,7 +34,7 @@ public void CanSetDefaultFlushModeThroughXmlConfiguration() [Test] public void CanSetDefaultFlushModeThroughStandardConfiguration() { - var cfg = new Configuration().Configure(); + var cfg = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); cfg.Properties[Environment.DefaultFlushMode] = FlushMode.Always.ToString(); using (var sessionFactory = cfg.BuildSessionFactory()) @@ -60,7 +60,7 @@ public void CanSetDefaultFlushModeThroughStandardConfiguration() public void CanSetDefaultFlushModeThroughLoquaciousConfiguration() { var cfg = new Configuration() - .Configure(); + .Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); cfg .SessionFactory() @@ -74,7 +74,7 @@ public void CanSetDefaultFlushModeThroughLoquaciousConfiguration() } } - cfg.Configure() + cfg.Configure(TestsContext.GetTestAssemblyHibernateConfiguration()) .SessionFactory() .DefaultFlushMode(FlushMode.Commit); diff --git a/src/NHibernate.Test/CfgTest/DefaultNsAssmFixture.cs b/src/NHibernate.Test/CfgTest/DefaultNsAssmFixture.cs index 78dda495202..0ee6bea77b3 100644 --- a/src/NHibernate.Test/CfgTest/DefaultNsAssmFixture.cs +++ b/src/NHibernate.Test/CfgTest/DefaultNsAssmFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.IO; using System.Reflection; @@ -218,3 +219,4 @@ public void MixedSubclass() } } } +#endif diff --git a/src/NHibernate.Test/CfgTest/HbmOrderingFixture.cs b/src/NHibernate.Test/CfgTest/HbmOrderingFixture.cs index 1708979ac92..2678dbacd89 100644 --- a/src/NHibernate.Test/CfgTest/HbmOrderingFixture.cs +++ b/src/NHibernate.Test/CfgTest/HbmOrderingFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.IO; using System.Reflection; @@ -256,3 +257,4 @@ public void MixedSubclass() } } } +#endif diff --git a/src/NHibernate.Test/CfgTest/Loquacious/ConfigurationFixture.cs b/src/NHibernate.Test/CfgTest/Loquacious/ConfigurationFixture.cs index adfc2715e08..30befa7fa14 100644 --- a/src/NHibernate.Test/CfgTest/Loquacious/ConfigurationFixture.cs +++ b/src/NHibernate.Test/CfgTest/Loquacious/ConfigurationFixture.cs @@ -46,12 +46,14 @@ public void CompleteConfiguration() .Using() .AutoQuoteKeywords() .EnableLogFormattedSql() +#if !NETCOREAPP2_0 .BatchingQueries .Through() .Each(15) +#endif .Connected .Through() - .By() + .By() .Releasing(ConnectionReleaseMode.AfterTransaction) .With(IsolationLevel.ReadCommitted) .Using(connectionString) @@ -80,10 +82,12 @@ public void CompleteConfiguration() Assert.That(cfg.Properties[Environment.Dialect], Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName)); Assert.That(cfg.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote")); Assert.That(cfg.Properties[Environment.FormatSql], Is.EqualTo("true")); +#if !NETCOREAPP2_0 Assert.That(cfg.Properties[Environment.BatchStrategy], Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName)); Assert.That(cfg.Properties[Environment.BatchSize], Is.EqualTo("15")); +#endif Assert.That(cfg.Properties[Environment.ConnectionProvider], Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName)); - Assert.That(cfg.Properties[Environment.ConnectionDriver], Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName)); + Assert.That(cfg.Properties[Environment.ConnectionDriver], Is.EqualTo(typeof(SqlServer2000Driver).AssemblyQualifiedName)); Assert.That(cfg.Properties[Environment.ReleaseConnections], Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction))); Assert.That(cfg.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted")); Assert.That(cfg.Properties[Environment.ConnectionString], Is.EqualTo(connectionString)); diff --git a/src/NHibernate.Test/CfgTest/Loquacious/EntityCacheConfigurationFixture.cs b/src/NHibernate.Test/CfgTest/Loquacious/EntityCacheConfigurationFixture.cs index a1b0292da74..6638534b401 100644 --- a/src/NHibernate.Test/CfgTest/Loquacious/EntityCacheConfigurationFixture.cs +++ b/src/NHibernate.Test/CfgTest/Loquacious/EntityCacheConfigurationFixture.cs @@ -12,7 +12,7 @@ public class EntityCacheConfigurationFixture [Test] public void ConfigureCacheOfClass() { - Configuration configure = new Configuration().Configure(); + Configuration configure = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly); configure.EntityCache(ce => @@ -30,7 +30,7 @@ public void ConfigureCacheOfClass() [Test] public void ConfigureCacheOfCollection() { - Configuration configure = new Configuration().Configure(); + Configuration configure = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly); configure.EntityCache(ce => @@ -54,7 +54,7 @@ public void ConfigureCacheOfCollection() [Test] public void ConfigureCacheOfCollectionWithOutEntity() { - Configuration configure = new Configuration().Configure(); + Configuration configure = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly); configure.EntityCache(ce => ce.Collection(e => e.Elements, cc => @@ -71,7 +71,7 @@ public void ConfigureCacheOfCollectionWithOutEntity() [Test] public void NotAllowRelatedCollections() { - Configuration configure = new Configuration().Configure(); + Configuration configure = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configure.AddResource("NHibernate.Test.CfgTest.Loquacious.EntityToCache.hbm.xml", GetType().Assembly); var exception = diff --git a/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs b/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs index cc464aafafa..fcc8ba172bc 100644 --- a/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs +++ b/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs @@ -46,10 +46,12 @@ public void FullConfiguration() { db.Dialect(); db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote; +#if !NETCOREAPP2_0 db.Batcher(); +#endif db.BatchSize = 15; db.ConnectionProvider(); - db.Driver(); + db.Driver(); db.ConnectionReleaseMode = ConnectionReleaseMode.AfterTransaction; db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = "The connection string"; @@ -82,13 +84,15 @@ public void FullConfiguration() Assert.That(configure.Properties[Environment.Dialect], Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName)); Assert.That(configure.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote")); +#if !NETCOREAPP2_0 Assert.That(configure.Properties[Environment.BatchStrategy], Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName)); +#endif Assert.That(configure.Properties[Environment.BatchSize], Is.EqualTo("15")); Assert.That(configure.Properties[Environment.ConnectionProvider], Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName)); Assert.That(configure.Properties[Environment.ConnectionDriver], - Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName)); + Is.EqualTo(typeof(SqlServer2000Driver).AssemblyQualifiedName)); Assert.That(configure.Properties[Environment.ReleaseConnections], Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction))); Assert.That(configure.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted")); @@ -104,4 +108,4 @@ public void FullConfiguration() Assert.That(configure.Properties[Environment.LinqToHqlGeneratorsRegistry], Is.EqualTo(typeof(DefaultLinqToHqlGeneratorsRegistry).AssemblyQualifiedName)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Component/Basic/ComponentWithUniqueConstraintTests.cs b/src/NHibernate.Test/Component/Basic/ComponentWithUniqueConstraintTests.cs index b4b3a5d0e5f..b12d265b22e 100644 --- a/src/NHibernate.Test/Component/Basic/ComponentWithUniqueConstraintTests.cs +++ b/src/NHibernate.Test/Component/Basic/ComponentWithUniqueConstraintTests.cs @@ -1,6 +1,5 @@ using System; using System.Data.Common; -using System.Data.Odbc; using System.Data.SqlClient; using System.Linq; using NHibernate.Cfg.MappingSchema; diff --git a/src/NHibernate.Test/ConnectionStringTest/NamedConnectionStringFixture.cs b/src/NHibernate.Test/ConnectionStringTest/NamedConnectionStringFixture.cs index 47c5bb86c5a..b8bad6cd571 100644 --- a/src/NHibernate.Test/ConnectionStringTest/NamedConnectionStringFixture.cs +++ b/src/NHibernate.Test/ConnectionStringTest/NamedConnectionStringFixture.cs @@ -33,6 +33,9 @@ public void ConnectionStringInSettingsOverrideNamedConnectionSTring() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support named connection strings from unit tests.")] +#endif public void CanGetNamedConnectionStringFromConfiguration() { Dictionary settings = new Dictionary(); diff --git a/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs b/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs index e2c1b6af8a1..a90a68e5130 100644 --- a/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs +++ b/src/NHibernate.Test/ConnectionTest/AggressiveReleaseTest.cs @@ -44,6 +44,9 @@ protected override void Done() // Some additional tests specifically for the aggressive-Release functionality... [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public void SerializationOnAfterStatementAggressiveRelease() { Prepare(); @@ -65,6 +68,9 @@ public void SerializationOnAfterStatementAggressiveRelease() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public void SerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources() { Prepare(); @@ -246,4 +252,4 @@ public void ConnectionMaintanenceDuringFlush() Done(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/CrossThreadTestRunner.cs b/src/NHibernate.Test/CrossThreadTestRunner.cs index e096f6b4182..2d00e8340c1 100644 --- a/src/NHibernate.Test/CrossThreadTestRunner.cs +++ b/src/NHibernate.Test/CrossThreadTestRunner.cs @@ -26,7 +26,9 @@ public CrossThreadTestRunner(ThreadStart start) { _start = start; _thread = new Thread(Run); +#if !NETCOREAPP2_0 _thread.SetApartmentState(ApartmentState.STA); +#endif } public void Start() @@ -57,7 +59,9 @@ private void Run() } } +#if !NETCOREAPP2_0 [ReflectionPermission(SecurityAction.Demand)] +#endif private static void ThrowExceptionPreservingStack(Exception exception) { if (RemoteStackTraceField != null) diff --git a/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs b/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs index 9a530f9a9a7..3e5b162a61a 100644 --- a/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs +++ b/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs @@ -100,13 +100,13 @@ public void NH2809() var t = d.GetTypeName(new BinarySqlType()); Assert.That(t, Is.EqualTo("VARBINARY(MAX)")); - t = d.GetTypeName(new BinarySqlType(), SqlClientDriver.MaxSizeForLengthLimitedBinary - 1, 0, 0); - Assert.That(t, Is.EqualTo(String.Format("VARBINARY({0})", SqlClientDriver.MaxSizeForLengthLimitedBinary - 1))); + t = d.GetTypeName(new BinarySqlType(), MsSql2000Dialect.MaxSizeForLengthLimitedBinary - 1, 0, 0); + Assert.That(t, Is.EqualTo(String.Format("VARBINARY({0})", MsSql2000Dialect.MaxSizeForLengthLimitedBinary - 1))); - t = d.GetTypeName(new BinarySqlType(), SqlClientDriver.MaxSizeForLengthLimitedBinary, 0, 0); - Assert.That(t, Is.EqualTo(String.Format("VARBINARY({0})", SqlClientDriver.MaxSizeForLengthLimitedBinary))); + t = d.GetTypeName(new BinarySqlType(), MsSql2000Dialect.MaxSizeForLengthLimitedBinary, 0, 0); + Assert.That(t, Is.EqualTo(String.Format("VARBINARY({0})", MsSql2000Dialect.MaxSizeForLengthLimitedBinary))); - t = d.GetTypeName(new BinarySqlType(), SqlClientDriver.MaxSizeForLengthLimitedBinary + 1, 0, 0); + t = d.GetTypeName(new BinarySqlType(), MsSql2000Dialect.MaxSizeForLengthLimitedBinary + 1, 0, 0); Assert.That(t, Is.EqualTo("VARBINARY(MAX)")); } diff --git a/src/NHibernate.Test/DriverTest/DbProviderFactoryDriveConnectionCommandProviderTest.cs b/src/NHibernate.Test/DriverTest/DbProviderFactoryDriveConnectionCommandProviderTest.cs index 16404a6ea6c..eb9561fce9f 100644 --- a/src/NHibernate.Test/DriverTest/DbProviderFactoryDriveConnectionCommandProviderTest.cs +++ b/src/NHibernate.Test/DriverTest/DbProviderFactoryDriveConnectionCommandProviderTest.cs @@ -11,29 +11,41 @@ public class DbProviderFactoryDriveConnectionCommandProviderTest [Test] public void WhenCreatedWithNullDbFactoryThenThrows() { +#if NETCOREAPP2_0 + Assert.Ignore("Not applicable for NETCOREAPP2_0"); +#else Assert.That(() => new DbProviderFactoryDriveConnectionCommandProvider(null), Throws.TypeOf()); +#endif } [Test] public void WhenCreatedWithDbFactoryThenCanReturnConnection() { +#if NETCOREAPP2_0 + Assert.Ignore("Not applicable for NETCOREAPP2_0"); +#else var factory = DbProviderFactories.GetFactory("System.Data.OracleClient"); var provider = new DbProviderFactoryDriveConnectionCommandProvider(factory); using(var connection =provider.CreateConnection()) { Assert.That(connection, Is.Not.Null); } +#endif } [Test] public void WhenCreatedWithDbFactoryThenCanReturnCommand() { +#if NETCOREAPP2_0 + Assert.Ignore("Not applicable for NETCOREAPP2_0"); +#else var factory = DbProviderFactories.GetFactory("System.Data.OracleClient"); var provider = new DbProviderFactoryDriveConnectionCommandProvider(factory); using (var command = provider.CreateCommand()) { Assert.That(command, Is.Not.Null); } +#endif } } } diff --git a/src/NHibernate.Test/DriverTest/FirebirdClientDriverFixture.cs b/src/NHibernate.Test/DriverTest/FirebirdClientDriverFixture.cs index 2bd4177e8db..c7a51668cb2 100644 --- a/src/NHibernate.Test/DriverTest/FirebirdClientDriverFixture.cs +++ b/src/NHibernate.Test/DriverTest/FirebirdClientDriverFixture.cs @@ -9,10 +9,10 @@ namespace NHibernate.Test.DriverTest { [TestFixture] - public class FirebirdClientDriverFixture + public class FirebirdDriverFixture { private string _connectionString; - private FirebirdClientDriver _driver; + private FirebirdDriver _driver; [OneTimeSetUp] public void OneTimeSetup() @@ -23,7 +23,7 @@ public void OneTimeSetup() if (!dlct.Contains("Firebird")) Assert.Ignore("Applies only to Firebird"); - _driver = new FirebirdClientDriver(); + _driver = new FirebirdDriver(); _driver.Configure(cfg.Properties); _connectionString = cfg.GetProperty("connection.connection_string"); } diff --git a/src/NHibernate.Test/DriverTest/ObsoleteDriverFixture.cs b/src/NHibernate.Test/DriverTest/ObsoleteDriverFixture.cs new file mode 100644 index 00000000000..5ef6726ac64 --- /dev/null +++ b/src/NHibernate.Test/DriverTest/ObsoleteDriverFixture.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections; +using System.Linq.Dynamic.Core; +using NHibernate.Cfg; +using NHibernate.Connection; +using NHibernate.Dialect; +using NHibernate.DomainModel; +using NHibernate.Driver; +using NHibernate.Util; +using NUnit.Framework; + +namespace NHibernate.Test.DriverTest +{ + [TestFixture, Obsolete] + public class ObsoleteDriverFixture : TestCase + { + protected override IList Mappings => new [] {"Simple.hbm.xml"}; + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + switch (dialect) + { + case FirebirdDialect _: + case MsSql2000Dialect _: + case MsSqlCeDialect _: + case MySQLDialect _: + case PostgreSQLDialect _: + case SQLiteDialect _: + System.Type driverType = ReflectHelper.ClassForName(cfg.GetProperty(Cfg.Environment.ConnectionDriver)); + return !(driverType.IsOdbcDriver() || driverType.IsOleDbDriver()); + default: + return false; + } + } + + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + + System.Type driverType = ReflectHelper.ClassForName(cfg.GetProperty(Cfg.Environment.ConnectionDriver)); + if (driverType.IsOdbcDriver() || driverType.IsOleDbDriver()) + { + // ODBC and OLE DB drivers are not obsoleted, do not switch it. + return; + } + + var dialect = NHibernate.Dialect.Dialect.GetDialect(configuration.Properties); + System.Type driver; + switch (dialect) + { + case FirebirdDialect _: + driver = typeof(FirebirdClientDriver); + break; + case MsSql2008Dialect _: + driver = typeof(Sql2008ClientDriver); + break; + case MsSql2000Dialect _: + driver = typeof(SqlClientDriver); + break; + case MsSqlCeDialect _: + driver = typeof(SqlServerCeDriver); + break; + case MySQLDialect _: + driver = typeof(MySqlDataDriver); + break; + case PostgreSQLDialect _: + driver = typeof(NpgsqlDriver); + break; + case SQLiteDialect _: + driver = typeof(SQLite20Driver); + break; + default: + return; + } + configuration.SetProperty(Cfg.Environment.ConnectionDriver, driver.FullName); + } + + [Test] + public void GenerateObsoleteWarning() + { + using (var spy = new LogSpy(typeof(ConnectionProvider))) + { + using (BuildSessionFactory()) + { + Assert.That(spy.GetWholeLog(), Does.Contain("Install the NHibernate.Driver.")); + } + } + } + + [Test] + public void CanUseObsoleteDriver() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var count = s.Query().Count(); + Assert.That(count, Is.Zero); + t.Commit(); + } + } + } +} diff --git a/src/NHibernate.Test/DriverTest/OdbcDriverFixture.cs b/src/NHibernate.Test/DriverTest/OdbcDriverFixture.cs index 086df5ca30b..52d78456a84 100644 --- a/src/NHibernate.Test/DriverTest/OdbcDriverFixture.cs +++ b/src/NHibernate.Test/DriverTest/OdbcDriverFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.Collections; using NHibernate.Dialect; @@ -104,3 +105,4 @@ public void Crud() } } } +#endif diff --git a/src/NHibernate.Test/DriverTest/OracleClientDriverFixture.cs b/src/NHibernate.Test/DriverTest/OracleClientDriverFixture.cs index 7306e106840..23cae71bf07 100644 --- a/src/NHibernate.Test/DriverTest/OracleClientDriverFixture.cs +++ b/src/NHibernate.Test/DriverTest/OracleClientDriverFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.Data.Common; using NHibernate.Driver; @@ -35,4 +36,5 @@ public void CommandClassName() Assert.AreEqual("System.Data.OracleClient.OracleCommand", cmd.GetType().FullName); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate.Test/DriverTest/OracleDataClientDriverFixture.cs b/src/NHibernate.Test/DriverTest/OracleDataClientDriverFixture.cs index 808a1b68dea..0fe2a377e3e 100644 --- a/src/NHibernate.Test/DriverTest/OracleDataClientDriverFixture.cs +++ b/src/NHibernate.Test/DriverTest/OracleDataClientDriverFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.Collections.Generic; using System.Data; @@ -117,7 +118,7 @@ private static OracleDataClientDriverBase GetDriver(bool managed, IDictionary "NHibernate.Test"; @@ -40,7 +40,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void OnTearDown() diff --git a/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs b/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs index 70d020796af..c2ab59acac0 100644 --- a/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs +++ b/src/NHibernate.Test/DynamicProxyTests/LazyFieldInterceptorTests.cs @@ -35,7 +35,7 @@ public void LazyFieldInterceptorIsBinarySerializable() var fieldInterceptionProxy = (IFieldInterceptorAccessor)pf.GetFieldInterceptionProxy(new MyClass()); fieldInterceptionProxy.FieldInterceptor = new DefaultFieldInterceptor(null, null, null, "MyClass", typeof(MyClass)); - Assert.That(fieldInterceptionProxy, Is.BinarySerializable); + NHAssert.IsSerializable(fieldInterceptionProxy); } diff --git a/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs b/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs index 6ffe80215e5..265ea82a96f 100644 --- a/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs +++ b/src/NHibernate.Test/DynamicProxyTests/PeVerifyFixture.cs @@ -16,6 +16,9 @@ public class PeVerifyFixture private const string assemblyFileName = "peVerifyAssembly.dll"; [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public void VerifyClassWithPublicConstructor() { var factory = new ProxyFactory(new SavingProxyAssemblyBuilder(assemblyName)); @@ -29,6 +32,9 @@ public void VerifyClassWithPublicConstructor() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public void VerifyClassWithProtectedConstructor() { var factory = new ProxyFactory(new SavingProxyAssemblyBuilder(assemblyName)); @@ -42,6 +48,9 @@ public void VerifyClassWithProtectedConstructor() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public void VerifyClassWithPrivateConstructor() { var factory = new ProxyFactory(new SavingProxyAssemblyBuilder(assemblyName)); @@ -54,6 +63,9 @@ public void VerifyClassWithPrivateConstructor() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public void VerifyClassWithNoDefaultConstructor() { var factory = new ProxyFactory(new SavingProxyAssemblyBuilder(assemblyName)); @@ -66,6 +78,9 @@ public void VerifyClassWithNoDefaultConstructor() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support saving dynamic assemblies.")] +#endif public void VerifyClassWithInternalConstructor() { var factory = new ProxyFactory(new SavingProxyAssemblyBuilder(assemblyName)); @@ -124,18 +139,30 @@ public SavingProxyAssemblyBuilder(string assemblyName) public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AppDomain.DefineDynamicModule not supported on this platform."); +#else AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; return appDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), access, TestContext.CurrentContext.TestDirectory); +#endif } public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AssemblyBuilder.DefineDynamicModule not supported on this platform."); +#else return assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", assemblyName), true); +#endif } public void Save(AssemblyBuilder assemblyBuilder) { +#if NETCOREAPP2_0 + throw new NotSupportedException("AssemblyBuilder.Save not supported on this platform."); +#else assemblyBuilder.Save(assemblyName + ".dll"); +#endif } } diff --git a/src/NHibernate.Test/ExceptionsTest/OracleClientExceptionConverterExample.cs b/src/NHibernate.Test/ExceptionsTest/OracleClientExceptionConverterExample.cs index fee49f7de7d..781527d8241 100644 --- a/src/NHibernate.Test/ExceptionsTest/OracleClientExceptionConverterExample.cs +++ b/src/NHibernate.Test/ExceptionsTest/OracleClientExceptionConverterExample.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.Data.OracleClient; using NHibernate.Exceptions; @@ -27,4 +28,5 @@ public Exception Convert(AdoExceptionContextInfo exInfo) #endregion } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate.Test/ExceptionsTest/SQLExceptionConversionTest.cs b/src/NHibernate.Test/ExceptionsTest/SQLExceptionConversionTest.cs index 179a50a862d..a407028ef11 100644 --- a/src/NHibernate.Test/ExceptionsTest/SQLExceptionConversionTest.cs +++ b/src/NHibernate.Test/ExceptionsTest/SQLExceptionConversionTest.cs @@ -3,7 +3,6 @@ using System.Data; using System.Data.Common; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Exceptions; using NHibernate.Util; @@ -32,7 +31,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { var driver = factory.ConnectionProvider.Driver; - return !(driver is OracleDataClientDriver) && !(driver is OracleManagedDataClientDriver) && !(driver is OracleLiteDataClientDriver) && !(driver is OdbcDriver) && !(driver is OleDbDriver); + return !(driver.IsOracleDataClientDriver()) && !(driver.IsOracleManagedDriver()) && !(driver.IsOracleLiteDataClientDriver()) && !(driver.IsOdbcDriver()) && !(driver.IsOleDbDriver()); } protected override void Configure(Cfg.Configuration configuration) @@ -46,9 +45,13 @@ protected override void Configure(Cfg.Configuration configuration) if (Dialect is Oracle8iDialect) { +#if !NETCOREAPP2_0 configuration.SetProperty( Cfg.Environment.SqlExceptionConverter, typeof(OracleClientExceptionConverterExample).AssemblyQualifiedName); +#else + throw new InvalidOperationException("Oracle8iDialect not valid in NETCOREAPP2_0"); +#endif } if (Dialect is PostgreSQLDialect) diff --git a/src/NHibernate.Test/ExceptionsTest/SerializationFixture.cs b/src/NHibernate.Test/ExceptionsTest/SerializationFixture.cs new file mode 100644 index 00000000000..525e82b305a --- /dev/null +++ b/src/NHibernate.Test/ExceptionsTest/SerializationFixture.cs @@ -0,0 +1,24 @@ +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using NUnit.Framework; + +namespace NHibernate.Test.ExceptionsTest +{ + [TestFixture] + public class SerializationFixture + { + [Test] + public void InstantiationExceptionSerialization() + { + var formatter = new BinaryFormatter(); + using (var memoryStream = new MemoryStream()) + { + formatter.Serialize(memoryStream, new InstantiationException("test", GetType())); + memoryStream.Position = 0; + var ex = formatter.Deserialize(memoryStream) as InstantiationException; + Assert.That(ex, Is.Not.Null); + Assert.That(ex.PersistentType, Is.EqualTo(GetType())); + } + } + } +} diff --git a/src/NHibernate.Test/Futures/FallbackFixture.cs b/src/NHibernate.Test/Futures/FallbackFixture.cs index 57992b53798..8e936b09bf0 100644 --- a/src/NHibernate.Test/Futures/FallbackFixture.cs +++ b/src/NHibernate.Test/Futures/FallbackFixture.cs @@ -10,13 +10,13 @@ namespace NHibernate.Test.Futures { - public class TestDriverThatDoesntSupportQueryBatching : SqlClientDriver + public class TestDriverThatDoesntSupportQueryBatching : SqlServer2000Driver { public override bool SupportsMultipleQueries => false; } /// - /// I'm using a Driver which derives from SqlClientDriver to + /// I'm using a Driver which derives from SqlServer2000Driver to /// return false for the SupportsMultipleQueries property. This is purely to test the way NHibernate /// will behave when the driver that's being used does not support multiple queries... so even though /// the test is using MsSql, it's only relevant for databases that don't support multiple queries @@ -38,7 +38,7 @@ protected override void Configure(Configuration configuration) base.Configure(configuration); using (var cp = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties)) { - if (cp.Driver is SqlClientDriver) + if (cp.Driver.IsSqlServerDriver()) { configuration.Properties[Environment.ConnectionDriver] = typeof(TestDriverThatDoesntSupportQueryBatching).AssemblyQualifiedName; diff --git a/src/NHibernate.Test/Hql/Ast/LimitClauseFixture.cs b/src/NHibernate.Test/Hql/Ast/LimitClauseFixture.cs index 75e6a3f8d81..7f1c9eb1a34 100644 --- a/src/NHibernate.Test/Hql/Ast/LimitClauseFixture.cs +++ b/src/NHibernate.Test/Hql/Ast/LimitClauseFixture.cs @@ -1,6 +1,5 @@ using System.Linq; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Hql.Ast.ANTLR; using NHibernate.Util; using NUnit.Framework; @@ -14,7 +13,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) { return dialect.SupportsVariableLimit && !(Dialect is Dialect.MsSql2000Dialect && // don't know why, but these tests don't work on SQL Server using ODBC - typeof(OdbcDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))); + ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/Insertordering/InsertOrderingFixture.cs b/src/NHibernate.Test/Insertordering/InsertOrderingFixture.cs index 0fa36657138..dc42d563695 100644 --- a/src/NHibernate.Test/Insertordering/InsertOrderingFixture.cs +++ b/src/NHibernate.Test/Insertordering/InsertOrderingFixture.cs @@ -1,3 +1,4 @@ +#if !NETCOREAPP2_0 using System; using System.Collections; using System.Collections.Generic; @@ -8,7 +9,6 @@ using NHibernate.AdoNet; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.SqlTypes; @@ -42,7 +42,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Custom batcher does not support oledb driver. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void Configure(Configuration configuration) @@ -632,3 +632,4 @@ public IBatcher CreateBatcher(ConnectionManager connectionManager, IInterceptor #endregion } } +#endif diff --git a/src/NHibernate.Test/Legacy/CultureInfoSerializationSurrogate.cs b/src/NHibernate.Test/Legacy/CultureInfoSerializationSurrogate.cs new file mode 100644 index 00000000000..52f3bdbdd77 --- /dev/null +++ b/src/NHibernate.Test/Legacy/CultureInfoSerializationSurrogate.cs @@ -0,0 +1,51 @@ +using System; +using System.Globalization; +using System.Runtime.Serialization; +using System.Security; +using NHibernate.Test.NHSpecificTest.NH1274ExportExclude; + +namespace NHibernate.Test.Legacy +{ + public sealed class CultureInfoSerializationSurrogate : ISerializationSurrogate + { + public static SurrogateSelector Add(SurrogateSelector ss) + { + ss.AddSurrogate(typeof(CultureInfo), new StreamingContext(StreamingContextStates.All), new CultureInfoSerializationSurrogate()); + return ss; + } + + public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) + { + var cultureInfo = (CultureInfo) obj; + info.SetType(typeof(ObjectReference)); + info.AddValue("_cultureinfoname", cultureInfo?.Name); + } + + public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) + { + throw new NotImplementedException("The object reference should be deserializing."); + } + + [Serializable] + private sealed class ObjectReference : IObjectReference, ISerializable + { + private readonly string _cultureinfoname; + + private ObjectReference(SerializationInfo info, StreamingContext context) + { + _cultureinfoname = info.GetString("_cultureinfoname"); + } + + [SecurityCritical] + public object GetRealObject(StreamingContext context) + { + return (_cultureinfoname == null) ? null : CultureInfo.GetCultureInfo(_cultureinfoname); + } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + throw new NotImplementedException("This class should not be serialized directly."); + } + } + } +} diff --git a/src/NHibernate.Test/Legacy/FooBarTest.cs b/src/NHibernate.Test/Legacy/FooBarTest.cs index 335b2cd4468..0ff2bedd2ee 100644 --- a/src/NHibernate.Test/Legacy/FooBarTest.cs +++ b/src/NHibernate.Test/Legacy/FooBarTest.cs @@ -2830,6 +2830,13 @@ public void PersistCollections() // serialize and then deserialize the session. Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); + +#if NETCOREAPP2_0 + var ss = new SurrogateSelector(); + CultureInfoSerializationSurrogate.Add(ss); + formatter.SurrogateSelector = ss; +#endif + formatter.Serialize(stream, s); s.Close(); @@ -4640,6 +4647,9 @@ public void SaveDelete() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public void ProxyArray() { ISession s = OpenSession(); diff --git a/src/NHibernate.Test/Legacy/MasterDetailTest.cs b/src/NHibernate.Test/Legacy/MasterDetailTest.cs index 9ffc61a4520..bc218d723ee 100644 --- a/src/NHibernate.Test/Legacy/MasterDetailTest.cs +++ b/src/NHibernate.Test/Legacy/MasterDetailTest.cs @@ -637,6 +637,9 @@ public void NamedQuery() } [Test] +#if NETCOREAPP2_0 + [Ignore("Serializing delegates (AfterTransactionCompletionProcessDelegate) is not supported on this platform.")] +#endif public void Serialization() { ISession s = OpenSession(); diff --git a/src/NHibernate.Test/Linq/ByMethod/GroupByTests.cs b/src/NHibernate.Test/Linq/ByMethod/GroupByTests.cs index 4601013f556..7c82722826a 100644 --- a/src/NHibernate.Test/Linq/ByMethod/GroupByTests.cs +++ b/src/NHibernate.Test/Linq/ByMethod/GroupByTests.cs @@ -5,7 +5,6 @@ using System.Text.RegularExpressions; using NHibernate.Dialect; using NHibernate.DomainModel.Northwind.Entities; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -551,7 +550,7 @@ public void GroupByComputedValue() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.Orders.GroupBy(o => o.Customer.CustomerId == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -563,7 +562,7 @@ public void GroupByComputedValueInAnonymousType() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.Orders.GroupBy(o => new { Key = o.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -575,7 +574,7 @@ public void GroupByComputedValueInObjectArray() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.Orders.GroupBy(o => new[] { o.Customer.CustomerId == null ? 0 : 1, }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -704,7 +703,7 @@ public void GroupByComputedValueWithJoinOnObject() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => o.Order.Customer == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -716,7 +715,7 @@ public void GroupByComputedValueWithJoinOnId() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => o.Order.Customer.CustomerId == null ? 0 : 1).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -728,7 +727,7 @@ public void GroupByComputedValueInAnonymousTypeWithJoinOnObject() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => new { Key = o.Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -740,7 +739,7 @@ public void GroupByComputedValueInAnonymousTypeWithJoinOnId() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => new { Key = o.Order.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -752,7 +751,7 @@ public void GroupByComputedValueInObjectArrayWithJoinOnObject() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => new[] { o.Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -764,7 +763,7 @@ public void GroupByComputedValueInObjectArrayWithJoinOnId() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => new[] { o.Order.Customer.CustomerId == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -776,7 +775,7 @@ public void GroupByComputedValueInObjectArrayWithJoinInRightSideOfCase() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.GroupBy(o => new[] { o.Order.Customer.CustomerId == null ? "unknown" : o.Order.Customer.CompanyName }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -788,7 +787,7 @@ public void GroupByComputedValueFromNestedArraySelect() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.Select(o => new object[] { o }).GroupBy(x => new object[] { ((OrderLine)x[0]).Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); @@ -800,7 +799,7 @@ public void GroupByComputedValueFromNestedObjectSelect() { if (!TestDialect.SupportsComplexExpressionInGroupBy) Assert.Ignore(Dialect.GetType().Name + " does not support complex group by expressions"); - if (Sfi.ConnectionProvider.Driver is OdbcDriver) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver()) Assert.Ignore("SQL Server seems unable to match complex group by and select list arguments when running over ODBC."); var orderGroups = db.OrderLines.Select(o => new { OrderLine = (object)o }).GroupBy(x => new object[] { ((OrderLine)x.OrderLine).Order.Customer == null ? 0 : 1 }).Select(g => new { Key = g.Key, Count = g.Count() }).ToList(); diff --git a/src/NHibernate.Test/Linq/FunctionTests.cs b/src/NHibernate.Test/Linq/FunctionTests.cs index dee4346fa4a..6a42fd29536 100644 --- a/src/NHibernate.Test/Linq/FunctionTests.cs +++ b/src/NHibernate.Test/Linq/FunctionTests.cs @@ -305,6 +305,11 @@ public void Trim() Assert.AreEqual(1, session.Query().Count(e => e.Input.TrimStart('h') == "eh")); Assert.AreEqual(1, session.Query().Count(e => e.Input.TrimEnd('h') == "he")); + // Check when passed as array (new overloads in .NET Core App 2.0). + Assert.AreEqual(1, session.Query().Count(e => e.Input.Trim(new [] { 'h' }) == "e")); + Assert.AreEqual(1, session.Query().Count(e => e.Input.TrimStart(new[] { 'h' }) == "eh")); + Assert.AreEqual(1, session.Query().Count(e => e.Input.TrimEnd(new[] { 'h' }) == "he")); + // Let it rollback to get rid of temporary changes. } } diff --git a/src/NHibernate.Test/MappingByCode/IntegrationTests/NH3667/MapFixture.cs b/src/NHibernate.Test/MappingByCode/IntegrationTests/NH3667/MapFixture.cs index 12334300ca4..88791a73f78 100644 --- a/src/NHibernate.Test/MappingByCode/IntegrationTests/NH3667/MapFixture.cs +++ b/src/NHibernate.Test/MappingByCode/IntegrationTests/NH3667/MapFixture.cs @@ -44,7 +44,7 @@ public void TestMapElementElement() [Test] public void TestMapEntityEntity() { - var cfg = new Configuration().Configure(); + var cfg = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); var mapper = new ModelMapper(); mapper.Class( @@ -123,7 +123,7 @@ public void TestMapEntityElement() [Test] public void TestMapElementEntity() { - var cfg = new Configuration().Configure(); + var cfg = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); var mapper = new ModelMapper(); mapper.Class( diff --git a/src/NHibernate.Test/MappingTest/NonReflectiveBinderFixture.cs b/src/NHibernate.Test/MappingTest/NonReflectiveBinderFixture.cs index fbe047c53c5..98b3ac55f28 100644 --- a/src/NHibernate.Test/MappingTest/NonReflectiveBinderFixture.cs +++ b/src/NHibernate.Test/MappingTest/NonReflectiveBinderFixture.cs @@ -191,7 +191,7 @@ public void XmlSerialization() using (Stream stream = GetType().Assembly.GetManifestResourceStream("NHibernate.Test.MappingTest.Wicked.hbm.xml")) { HbmMapping mapping = mdp.Parse(stream); - Assert.That(mapping, Is.XmlSerializable); + NHAssert.IsXmlSerializable(mapping); } } } diff --git a/src/NHibernate.Test/NHAssert.cs b/src/NHibernate.Test/NHAssert.cs index 79667df1086..5bb10eaac6c 100644 --- a/src/NHibernate.Test/NHAssert.cs +++ b/src/NHibernate.Test/NHAssert.cs @@ -53,7 +53,51 @@ public static void IsSerializable(object obj) public static void IsSerializable(object obj, string message, params object[] args) { - Assert.That(obj, Is.BinarySerializable, message, args); + bool succeeded = false; + var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); + var stream = new System.IO.MemoryStream(); + try + { + serializer.Serialize(stream, obj); + + stream.Seek(0, System.IO.SeekOrigin.Begin); + + succeeded = serializer.Deserialize(stream) != null; + } + catch (System.Runtime.Serialization.SerializationException) + { + // Ignore and return failure + succeeded = false; + } + Assert.That(succeeded, message ?? $"Supplied Type {obj.GetType()} is not serializable", args); + } + + public static void IsXmlSerializable(object obj) + { + IsXmlSerializable(obj, null, null); + } + + public static void IsXmlSerializable(object obj, string message, params object[] args) + { + if (obj == null) throw new ArgumentNullException(nameof(obj)); + + bool succeeded = false; + var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); + var stream = new System.IO.MemoryStream(); + try + { + serializer.Serialize(stream, obj); + + stream.Seek(0, System.IO.SeekOrigin.Begin); + + succeeded = serializer.Deserialize(stream) != null; + } + catch (System.Runtime.Serialization.SerializationException) + { + // Ignore and return failure + succeeded = false; + } + Assert.That(succeeded, message ?? $"Supplied Type {obj.GetType()} is not serializable", args); } #endregion @@ -72,4 +116,4 @@ public static void IsSerializable(object obj, string message, params object[] ar return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs index b4b80b3a979..1abf13fa653 100644 --- a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetFixture.cs @@ -4,7 +4,6 @@ using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; -using NHibernate.Driver; using NHibernate.Type; using NUnit.Framework; @@ -21,7 +20,7 @@ protected override IList Mappings protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - if (factory.ConnectionProvider.Driver is OdbcDriver) + if (factory.ConnectionProvider.Driver.IsOdbcDriver()) return false; return base.AppliesTo(factory); diff --git a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs index 5fb7bca6261..18611b1bd21 100644 --- a/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/Dates/DateTimeOffsetQueryFixture.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Data; using System.Linq; -using NHibernate.Driver; using NHibernate.Type; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -21,7 +20,7 @@ protected override IList Mappings protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - if (factory.ConnectionProvider.Driver is OdbcDriver) + if (factory.ConnectionProvider.Driver.IsOdbcDriver()) return false; return base.AppliesTo(factory); diff --git a/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs index be3b8d7a7b0..221afacfb3c 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs @@ -1,7 +1,6 @@ using log4net.Core; using NHibernate.AdoNet; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Util; using NUnit.Framework; @@ -26,7 +25,7 @@ protected override void Configure(Configuration configuration) [Test] public void CanSaveInSingleBatch() { - if (!typeof(OracleDataClientDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))) + if (!ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsOracleDataClientDriver()) { Assert.Ignore("Only applicable for Oracle Data Client driver"); } diff --git a/src/NHibernate.Test/NHSpecificTest/NH1507/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1507/Fixture.cs index 2c072d90c87..e46f0c3c58b 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1507/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1507/Fixture.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1507 @@ -10,7 +9,7 @@ public class Fixture : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -117,4 +116,4 @@ public void ImplicitJoinFailingTest() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs b/src/NHibernate.Test/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs index 357642d975d..96ca8ac199d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1553/MsSQL/SnapshotIsolationUpdateConflictTest.cs @@ -1,7 +1,6 @@ using System.Data; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; using NUnit.Framework.Constraints; @@ -131,7 +130,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) { // SQLUpdateConflictToStaleStateExceptionConverter is specific to Sql client driver, and does not work // with Odbc (and likeley Oledb). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } private void SetAllowSnapshotIsolation(bool on) @@ -181,4 +180,4 @@ protected override void Configure(Configuration configuration) typeof (SQLUpdateConflictToStaleStateExceptionConverter).AssemblyQualifiedName); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs index 6a716ce5a66..3cd34b96ca0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs @@ -17,7 +17,7 @@ public void Bug() if (TestConfigurationHelper.hibernateConfigFile != null) cfg.Configure(TestConfigurationHelper.hibernateConfigFile); cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1587.Mappings.hbm.xml", GetType().Assembly); - cfg.Configure(); + cfg.Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); bool useOptimizer= false; using (var ls = new LogSpy("NHibernate.Tuple.Entity.PocoEntityTuplizer")) diff --git a/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs index 6d56dfefd34..aad9ad65931 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs @@ -25,6 +25,9 @@ protected override void Configure(Configuration configuration) } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction() { if (!Dialect.SupportsConcurrentWritingConnections) @@ -81,8 +84,10 @@ public void Dispose_session_inside_transaction_scope() Assert.IsFalse(s.IsOpen); } - [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void When_commiting_items_in_DTC_transaction_will_add_items_to_2nd_level_cache() { using (var tx = new TransactionScope()) @@ -136,6 +141,9 @@ public void When_commiting_items_in_DTC_transaction_will_add_items_to_2nd_level_ } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void When_committing_transaction_scope_will_commit_transaction() { object id; @@ -183,6 +191,9 @@ public void Will_not_save_when_flush_mode_is_never() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void When_using_two_sessions_with_explicit_flush() { if (!Dialect.SupportsConcurrentWritingConnectionsInSameTransaction) @@ -223,6 +234,9 @@ public void When_using_two_sessions_with_explicit_flush() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void When_using_two_sessions() { if (!Dialect.SupportsConcurrentWritingConnectionsInSameTransaction) diff --git a/src/NHibernate.Test/NHSpecificTest/NH1756/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1756/Fixture.cs index 8098a37ca7a..57fcda1d470 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1756/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1756/Fixture.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -30,7 +29,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) // N'@P1 nvarchar(18),@P2 int,@P3 datetime2',N'modified test book',1,'2017-08-02 16:37:16.0630000' // Setting the scale to 2 still causes failure for two thirds of tries, due to 3ms/7ms being truncated in such case // with ODBC and SQL Server 2008+ Client, which is rejected by ODBC. - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH1850/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1850/Fixture.cs index 9fe637a681b..bc4c7cb21b2 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1850/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1850/Fixture.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +#if !NETCOREAPP2_0 +using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1850 { @@ -95,3 +96,4 @@ public void CanGetQueryDurationForSelect() } } } +#endif diff --git a/src/NHibernate.Test/NHSpecificTest/NH1867/AddMappingTest.cs b/src/NHibernate.Test/NHSpecificTest/NH1867/AddMappingTest.cs index 411e0d1d431..da8211c9d00 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1867/AddMappingTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1867/AddMappingTest.cs @@ -42,14 +42,14 @@ public class B [Test] public void NestedWithinNonGeneric() { - var configuration = new Configuration().Configure(); + var configuration = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configuration.AddXml(string.Format(mappingTemplate, typeof(A).FullName, typeof(A.B).FullName)); } [Test] public void NestedWithinGeneric() { - var configuration = new Configuration().Configure(); + var configuration = new Configuration().Configure(TestsContext.GetTestAssemblyHibernateConfiguration()); configuration.AddXml(string.Format(mappingTemplate, typeof(A).FullName, typeof(A.B).FullName)); } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH2020/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2020/Fixture.cs index c1f79a62f32..289d7cc8e23 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2020/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2020/Fixture.cs @@ -1,6 +1,5 @@ using NUnit.Framework; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Test.ExceptionsTest; using NHibernate.Engine; @@ -26,7 +25,7 @@ protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Use a SQL Server Client exception converter, cannot work for ODBC or OleDb - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void OnTearDown() diff --git a/src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs index e56ce2066c7..9bf08c252cd 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs @@ -8,6 +8,9 @@ namespace NHibernate.Test.NHSpecificTest.NH2057 public class Fixture : BugTestCase { [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void WillCloseWhenUsingDTC() { ISession s; diff --git a/src/NHibernate.Test/NHSpecificTest/NH2176/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2176/Fixture.cs index 2f5cabedad4..9254cf3def9 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2176/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2176/Fixture.cs @@ -45,6 +45,9 @@ protected override void OnTearDown() // Whilst this bug seems specific to Oracle I think it is valid to run the // test against all database types. [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void MultipleConsecutiveTransactionScopesCanBeUsedInsideASingleSession() { using (var s = OpenSession()) @@ -73,4 +76,4 @@ public void MultipleConsecutiveTransactionScopesCanBeUsedInsideASingleSession() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH2188/AppDomainWithMultipleSearchPath.cs b/src/NHibernate.Test/NHSpecificTest/NH2188/AppDomainWithMultipleSearchPath.cs index f6dcf869ca2..7e2ac83c027 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2188/AppDomainWithMultipleSearchPath.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2188/AppDomainWithMultipleSearchPath.cs @@ -19,6 +19,9 @@ public string DefaultConfigurationFilePath() [Test] public void WhenSerchInMultiplePathsThenNotThrows() { +#if NETCOREAPP2_0 + Assert.Ignore("Not applicable for NETCOREAPP2_0"); +#else // NUnit 3 sets PrivateBinPath when using an NUnit project, so we need to reset back to the correct setting when done. var privatePath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; @@ -43,6 +46,7 @@ public void WhenSerchInMultiplePathsThenNotThrows() if (privatePath != null) AppDomain.CurrentDomain.AppendPrivatePath(privatePath); } #pragma warning restore CS0618 // Type or member is obsolete +#endif } } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH2207/SampleTest.cs b/src/NHibernate.Test/NHSpecificTest/NH2207/SampleTest.cs index c84162a1e75..19b7cac1d5f 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2207/SampleTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2207/SampleTest.cs @@ -1,7 +1,6 @@ using System; using System.Data; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -17,7 +16,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is Sql2008ClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServer2008Driver(); } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH2296/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2296/Fixture.cs index 04ccee45786..c9b6a17abcc 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2296/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2296/Fixture.cs @@ -1,5 +1,4 @@ using System.Linq; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH2296 @@ -9,7 +8,7 @@ public class Fixture : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -73,4 +72,4 @@ public void Test() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH2302/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2302/Fixture.cs index fb0b651da7b..9ea7437bb9d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2302/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2302/Fixture.cs @@ -1,6 +1,5 @@ using System.Data; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Mapping; using NUnit.Framework; @@ -38,7 +37,7 @@ protected override void OnTearDown() [Test] public void StringHugeLength() { - if (Sfi.ConnectionProvider.Driver is OdbcDriver || Dialect is MsSqlCeDialect) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver() || Dialect is MsSqlCeDialect) Assert.Ignore("NH-4065, not fixed for Odbc and MsSqlCe"); int id; diff --git a/src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs index 0cde5572e99..8d6bce4e583 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2420/Fixture.cs @@ -1,10 +1,11 @@ using System.Data.Common; +#if !NETCOREAPP2_0 using System.Data.Odbc; +#endif using System.Data.SqlClient; using System.Configuration; using System.Transactions; using NHibernate.Dialect; -using NHibernate.Driver; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -49,6 +50,9 @@ private string FetchConnectionStringFromConfiguration() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransaction() { string connectionString = FetchConnectionStringFromConfiguration(); @@ -65,10 +69,16 @@ public void ShouldBeAbleToReleaseSuppliedConnectionAfterDistributedTransaction() new DummyEnlistment(), EnlistmentOptions.None); - if (Sfi.ConnectionProvider.Driver.GetType() == typeof(OdbcDriver)) +#if !NETCOREAPP2_0 + if (Sfi.ConnectionProvider.Driver.GetType().IsOdbcDriver()) + { connection = new OdbcConnection(connectionString); + } else +#endif + { connection = new SqlConnection(connectionString); + } connection.Open(); using (s = Sfi.WithOptions().Connection(connection).OpenSession()) diff --git a/src/NHibernate.Test/NHSpecificTest/NH2660And2661/Test.cs b/src/NHibernate.Test/NHSpecificTest/NH2660And2661/Test.cs index 19e7ae2a6d1..82cb3f662b2 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2660And2661/Test.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2660And2661/Test.cs @@ -39,7 +39,7 @@ protected override void Configure(Configuration configuration) { // to be sure we are using the new drive base.Configure(configuration); - configuration.DataBaseIntegration(x=> x.Driver()); + configuration.DataBaseIntegration(x=> x.Driver()); } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH2846/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2846/Fixture.cs index f20da6a7aa3..e3f8ae9de60 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2846/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2846/Fixture.cs @@ -1,5 +1,4 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -10,7 +9,7 @@ public class Fixture : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/NHSpecificTest/NH2852/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2852/Fixture.cs index 9ab184192f2..a7074c919a5 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2852/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2852/Fixture.cs @@ -1,5 +1,4 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Linq; using NUnit.Framework; @@ -10,7 +9,7 @@ public class Fixture : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() @@ -81,4 +80,4 @@ public void AlsoFails() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH2985/Model.cs b/src/NHibernate.Test/NHSpecificTest/NH2985/Model.cs index 99ba39592f2..3bb49cea6a0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2985/Model.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2985/Model.cs @@ -105,6 +105,7 @@ public virtual Guid Id /// protected internal virtual Boolean OldImage { get; set; } +#if !NETCOREAPP2_0 private Bitmap _bitmap; /// @@ -118,6 +119,7 @@ public virtual Bitmap Bitmap return _bitmap ?? CreateBitmap(); } } +#endif /// /// La url dell'immagine. @@ -125,6 +127,7 @@ public virtual Bitmap Bitmap /// The image URL. public virtual String ImageUrl { get; set; } +#if !NETCOREAPP2_0 private Bitmap CreateBitmap() { try @@ -144,6 +147,7 @@ private Bitmap CreateBitmap() } } +#endif } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH3004/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3004/Fixture.cs index 706eb379177..8ea465009c0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3004/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3004/Fixture.cs @@ -13,7 +13,7 @@ public void RemoveUnusedCommandParametersBug_1() /* UseNamedPrefixInSql is true * UseNamedPrefixInParameter is false * */ - var driver = new TestSqlClientDriver(true, false); + var driver = new TestSqlServerDriver(true, false); RunTest(driver); } @@ -24,12 +24,12 @@ public void RemoveUnusedCommandParametersBug_2() /* UseNamedPrefixInSql is true * UseNamedPrefixInParameter is true * */ - var driver = new TestSqlClientDriver(true, true); + var driver = new TestSqlServerDriver(true, true); RunTest(driver); } - private static void RunTest(TestSqlClientDriver driver) + private static void RunTest(TestSqlServerDriver driver) { var command = driver.CreateCommand(); diff --git a/src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlClientDriver.cs b/src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlServerDriver.cs similarity index 66% rename from src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlClientDriver.cs rename to src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlServerDriver.cs index 24297856ff0..961e1a30a79 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlClientDriver.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3004/TestSqlServerDriver.cs @@ -1,9 +1,3 @@ -using System.Data.SqlClient; -using NHibernate.AdoNet; -using NHibernate.Dialect; -using NHibernate.Engine; -using NHibernate.SqlCommand; -using NHibernate.SqlTypes; using NHibernate.Driver; namespace NHibernate.Test.NHSpecificTest.NH3004 @@ -11,17 +5,17 @@ namespace NHibernate.Test.NHSpecificTest.NH3004 /// /// A NHibernate Driver for using the SqlClient DataProvider /// - public class TestSqlClientDriver : SqlClientDriver + public class TestSqlServerDriver : SqlServer2000Driver { bool _UseNamedPrefixInSql = true; bool _UseNamedPrefixInParameter = false; - public TestSqlClientDriver() + public TestSqlServerDriver() { } - public TestSqlClientDriver(bool UseNamedPrefixInSql, bool UseNamedPrefixInParameter) + public TestSqlServerDriver(bool UseNamedPrefixInSql, bool UseNamedPrefixInParameter) { _UseNamedPrefixInSql = UseNamedPrefixInSql; _UseNamedPrefixInParameter = UseNamedPrefixInParameter; @@ -38,4 +32,4 @@ public override bool UseNamedPrefixInParameter get { return _UseNamedPrefixInParameter; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs b/src/NHibernate.Test/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs index 96b83b0179d..ca2c7d2623d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3023/DeadlockConnectionPoolIssueTest.cs @@ -10,7 +10,6 @@ using log4net.Repository.Hierarchy; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -32,7 +31,7 @@ protected override void Configure(Configuration configuration) // Uses directly SqlConnection. protected override bool AppliesTo(ISessionFactoryImplementor factory) - => factory.ConnectionProvider.Driver is SqlClientDriver && base.AppliesTo(factory); + => factory.ConnectionProvider.Driver.IsSqlServerDriver() && base.AppliesTo(factory); protected override bool AppliesTo(Dialect.Dialect dialect) => dialect is MsSql2000Dialect && base.AppliesTo(dialect); @@ -65,6 +64,19 @@ protected override void OnTearDown() [Theory] public void ConnectionPoolCorruptionAfterDeadlock(bool distributed, bool disposeSessionBeforeScope) { + if (distributed) + { +#if NETCOREAPP2_0 + Assert.Ignore("This platform does not support distributed transactions."); +#endif + } + else + { +#if NETCOREAPP2_0 + Assert.Ignore("Enlisting in Ambient transactions is not supported by System.Data.SqlClient."); +#endif + } + var tryCount = 0; var id = 1; do diff --git a/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs index 353d93e06fb..f7b62a7d4ec 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3121/Fixture.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Reflection; using NHibernate.Dialect; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3121 @@ -24,10 +23,10 @@ protected override bool AppliesTo(Dialect.Dialect dialect) [Test] public void ShouldThrowWhenByteArrayTooLong() { - // For SQL Server only the SqlClientDriver sets parameter lengths + // For SQL Server only the SqlServer2000Driver sets parameter lengths // even when there is no length specified in the mapping. The ODBC // driver won't cause the truncation issue and hence not the exception. - if (!(Sfi.ConnectionProvider.Driver is SqlClientDriver)) + if (!(Sfi.ConnectionProvider.Driver.IsSqlServerDriver())) Assert.Ignore("Test limited to drivers that sets parameter length even with no length specified in the mapping."); const int reportSize = 17158; diff --git a/src/NHibernate.Test/NHSpecificTest/NH3142/ChildrenTest.cs b/src/NHibernate.Test/NHSpecificTest/NH3142/ChildrenTest.cs index cc1b1d1d6d7..d194624c387 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3142/ChildrenTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3142/ChildrenTest.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3142 @@ -11,7 +10,7 @@ public class ChildrenTest : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return !(factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return !(factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/NHSpecificTest/NH3202/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3202/Fixture.cs index 8734c483c18..dd401f9316d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3202/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3202/Fixture.cs @@ -16,7 +16,7 @@ protected override void Configure(Configuration configuration) if (!(Dialect is MsSql2008Dialect)) Assert.Ignore("Test is for MS SQL Server dialect only (custom dialect)."); - if (!typeof(SqlClientDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))) + if (!ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)).IsSqlServerDriver()) Assert.Ignore("Test is for MS SQL Server driver only (custom driver is used)."); cfg.SetProperty(Environment.Dialect, typeof(OffsetStartsAtOneTestDialect).AssemblyQualifiedName); @@ -105,7 +105,7 @@ public class OffsetStartsAtOneTestDialect : MsSql2008Dialect } - public class OffsetTestDriver : SqlClientDriver + public class OffsetTestDriver : SqlServer2000Driver { public OffsetStartsAtOneTestDialect OffsetStartsAtOneTestDialect; private int _offsetParameterIndex = 1; diff --git a/src/NHibernate.Test/NHSpecificTest/NH3252/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3252/Fixture.cs index 2638158af72..7287a6efc97 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3252/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3252/Fixture.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NUnit.Framework; @@ -12,7 +11,7 @@ public class Fixture : BugTestCase { protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs b/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs index 8da471c71a2..8285d7a7046 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3383/FixtureByCode.cs @@ -83,6 +83,9 @@ public void DeserializedPropertyMapping_RefersToSameCascadeStyle() [Test] public void DeserializedPropertyMapping_CascadeStyleNotYetInitializedOnDeserialization_RefersToSameCascadeStyle() { +#if NETCOREAPP2_0 + Assert.Ignore("Not applicable for NETCOREAPP2_0"); +#else var classMapping = CreateMappingClasses(); using (MemoryStream configMemoryStream = new MemoryStream()) @@ -109,6 +112,7 @@ public void DeserializedPropertyMapping_CascadeStyleNotYetInitializedOnDeseriali AppDomain.Unload(secondAppDomain); } } +#endif } private static RootClass CreateMappingClasses() diff --git a/src/NHibernate.Test/NHSpecificTest/NH3405/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3405/Fixture.cs index d687fc1dcb5..e6bed827bac 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3405/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3405/Fixture.cs @@ -4,7 +4,6 @@ using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NHibernate.Mapping.ByCode; @@ -34,7 +33,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // No Xml support with Odbc (and likely OleDb too). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override HbmMapping GetMappings() diff --git a/src/NHibernate.Test/NHSpecificTest/NH3518/XmlColumnTest.cs b/src/NHibernate.Test/NHSpecificTest/NH3518/XmlColumnTest.cs index 832f8f30cb4..636411ffa90 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3518/XmlColumnTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3518/XmlColumnTest.cs @@ -1,7 +1,6 @@ using System.Xml; using NHibernate.Cfg; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -27,7 +26,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override void Configure(Configuration configuration) diff --git a/src/NHibernate.Test/NHSpecificTest/NH3583/AutoFlushFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3583/AutoFlushFixture.cs index 03dded82481..e23f684e831 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3583/AutoFlushFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3583/AutoFlushFixture.cs @@ -50,7 +50,11 @@ public void ShouldAutoFlushWhenInExplicitTransaction() Assert.That(result.Count, Is.EqualTo(1)); } } + [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void ShouldAutoFlushWhenInDistributedTransaction() { using (new TransactionScope()) diff --git a/src/NHibernate.Test/NHSpecificTest/NH3620/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3620/Fixture.cs index 232c5016cc9..69e0a4e7098 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3620/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3620/Fixture.cs @@ -1,12 +1,11 @@ using System; -using NHibernate.Driver; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3620 { [TestFixture] public class Fixture : BugTestCase { protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { - return (factory.ConnectionProvider.Driver is OracleManagedDataClientDriver); + return (factory.ConnectionProvider.Driver.IsOracleManagedDriver()); } protected override void OnTearDown() { @@ -40,4 +39,4 @@ private void CleanupData() { } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3844/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3844/Fixture.cs index d8cca9fe754..e4a64852bd9 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3844/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3844/Fixture.cs @@ -1,5 +1,4 @@ using System.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NUnit.Framework; @@ -17,7 +16,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // SQL Server seems unable to match complex group by and select list arguments when running over ODBC."; - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/NHSpecificTest/NH3850/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3850/Fixture.cs index cb3f7d48245..5bae8e45eba 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3850/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3850/Fixture.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Reflection; using System.Text; -using NHibernate.Driver; using NHibernate.Linq; using NHibernate.SqlTypes; using NHibernate.Util; @@ -30,7 +29,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) { // Cannot handle DbType.DateTimeOffset via ODBC. - return !(factory.ConnectionProvider.Driver is OdbcDriver); + return !(factory.ConnectionProvider.Driver.IsOdbcDriver()); } protected override void OnSetUp() diff --git a/src/NHibernate.Test/NHSpecificTest/NH3912/ReusableBatcherFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3912/ReusableBatcherFixture.cs index 396fd38a48a..76570c9b09a 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3912/ReusableBatcherFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3912/ReusableBatcherFixture.cs @@ -3,7 +3,6 @@ using NHibernate.AdoNet; using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Linq; using NHibernate.Mapping.ByCode; @@ -17,9 +16,9 @@ public class ReusableBatcherFixture : TestCaseMappingByCode protected override bool AppliesTo(ISessionFactoryImplementor factory) { var driver = factory.ConnectionProvider.Driver; - return driver is OracleDataClientDriver || - driver is OracleLiteDataClientDriver || - driver is OracleManagedDataClientDriver; + return driver.IsOracleDataClientDriver() || + driver.IsOracleLiteDataClientDriver() || + driver.IsOracleManagedDriver(); } protected override HbmMapping GetMappings() diff --git a/src/NHibernate.Test/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs index 5d822391ca9..b264cdfc1ad 100644 --- a/src/NHibernate.Test/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/SqlConverterAndMultiQuery/Fixture.cs @@ -1,5 +1,4 @@ using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -21,7 +20,7 @@ protected override bool AppliesTo(ISessionFactoryImplementor factory) // tend to (validly) send InvalidOperationException during prepare phase due to the closed // connection, which get not converted. For testing other case, maybe a failure caused by a // schema mismatch (like done in transaction tests) would be better. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index 9d04242a1d2..ed88e6966d6 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -3,7 +3,8 @@ The Unit Tests for NHibernate. - net461 + netcoreapp2.0;net461 + true true $(NoWarn);3001;3002;3003;3005 @@ -25,44 +26,43 @@ Always + + + + + + + + + + Always - - - - - - - - - - %(RecursiveDir)%(Filename)%(Extension) - PreserveNewest - - - - - - %(RecursiveDir)%(Filename)%(Extension) - PreserveNewest - + + + + + + + + - + diff --git a/src/NHibernate.Test/Pagination/CustomDialectFixture.cs b/src/NHibernate.Test/Pagination/CustomDialectFixture.cs index 3ff7517e819..c0182a827bd 100644 --- a/src/NHibernate.Test/Pagination/CustomDialectFixture.cs +++ b/src/NHibernate.Test/Pagination/CustomDialectFixture.cs @@ -3,7 +3,6 @@ using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Util; using NUnit.Framework; using Environment = NHibernate.Cfg.Environment; @@ -29,7 +28,7 @@ protected override void Configure(Configuration configuration) if (!(Dialect is MsSql2005Dialect)) Assert.Ignore("Test is for SQL dialect only"); var driverClass = ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)); - if (!typeof(SqlClientDriver).IsAssignableFrom(driverClass)) + if (!driverClass.IsSqlServerDriver()) Assert.Ignore("Test is compatible only with Sql Server Client driver connection strings"); cfg.SetProperty(Environment.Dialect, typeof(CustomMsSqlDialect).AssemblyQualifiedName); @@ -123,4 +122,4 @@ public void LimitFirstMultiCriteria() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs b/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs index 3ba118a3d7f..5c1319be06f 100644 --- a/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs +++ b/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs @@ -1,7 +1,5 @@ using System.Data.Common; -using System.Text.RegularExpressions; using NHibernate.Driver; -using NUnit.Framework; namespace NHibernate.Test.Pagination { @@ -9,7 +7,7 @@ namespace NHibernate.Test.Pagination /// Class to work with CustomMsSqlDialect to allow /// verification of simulated limit parameters /// - public class CustomMsSqlDriver : SqlClientDriver + public class CustomMsSqlDriver : SqlServer2000Driver { public CustomMsSqlDialect CustomMsSqlDialect; @@ -33,4 +31,4 @@ protected override void OnBeforePrepare(DbCommand command) base.OnBeforePrepare(command); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs b/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs index 8db55a3bdd4..518b3370793 100644 --- a/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs +++ b/src/NHibernate.Test/ReadOnly/ReadOnlyCriteriaQueryTest.cs @@ -1054,6 +1054,9 @@ public void Subselect() } [Test] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void DetachedCriteria() { DetachedCriteria dc = NHibernate.Criterion.DetachedCriteria.For() diff --git a/src/NHibernate.Test/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs b/src/NHibernate.Test/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs index d30f493cfe8..1db753cc697 100644 --- a/src/NHibernate.Test/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs +++ b/src/NHibernate.Test/SqlTest/Custom/Oracle/OracleCustomSQLFixture.cs @@ -14,7 +14,7 @@ protected override IList Mappings protected override bool AppliesTo(NHibernate.Engine.ISessionFactoryImplementor factory) { - return factory.ConnectionProvider.Driver is Driver.OracleDataClientDriver; + return factory.ConnectionProvider.Driver.IsOracleDataClientDriver(); } protected override bool AppliesTo(Dialect.Dialect dialect) @@ -57,4 +57,4 @@ public void RefCursorOutStoredProcedure() } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs b/src/NHibernate.Test/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs index ab0abc53a0c..12eb892d91b 100644 --- a/src/NHibernate.Test/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs +++ b/src/NHibernate.Test/SqlTest/Identity/MsSQL/MSSQLIdentityInsertWithStoredProcsTest.cs @@ -1,6 +1,5 @@ using System.Collections; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; @@ -17,7 +16,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // Tested resulting SQL depends on driver. - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } protected override string GetExpectedInsertOrgLogStatement(string orgName) diff --git a/src/NHibernate.Test/SystemTransactions/SystemTransactionFixtureBase.cs b/src/NHibernate.Test/SystemTransactions/SystemTransactionFixtureBase.cs index 6a13a609c2a..6b604b8cd7d 100644 --- a/src/NHibernate.Test/SystemTransactions/SystemTransactionFixtureBase.cs +++ b/src/NHibernate.Test/SystemTransactions/SystemTransactionFixtureBase.cs @@ -1,7 +1,6 @@ using System; using System.Text.RegularExpressions; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Test.TransactionTest; using NHibernate.Util; @@ -32,7 +31,7 @@ protected void DisableConnectionAutoEnlist(Configuration configuration) var autoEnlistmentKeyword = "Enlist"; var autoEnlistmentKeywordPattern = autoEnlistmentKeyword; if (configuration.GetDerivedProperties().TryGetValue(Cfg.Environment.ConnectionDriver, out var driver) && - typeof(MySqlDataDriver).IsAssignableFrom(ReflectHelper.ClassForName(driver))) + ReflectHelper.ClassForName(driver).IsMySqlDriver()) { autoEnlistmentKeyword = "AutoEnlist"; autoEnlistmentKeywordPattern = "Auto ?Enlist"; @@ -143,4 +142,4 @@ public override void AfterTransactionCompletion(ITransaction tx) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs b/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs index 416fe5b8637..1294807d5f8 100644 --- a/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs +++ b/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs @@ -164,9 +164,11 @@ public void ShouldNotifyAfterDistributedTransaction(bool doCommit) Assert.That(interceptor.afterTransactionCompletionCalled, Is.EqualTo(2)); } - [Description("NH2128")] [Theory] +#if NETCOREAPP2_0 + [Ignore("This platform does not support distributed transactions.")] +#endif public void ShouldNotifyAfterDistributedTransactionWithOwnConnection(bool doCommit) { // Note: For system transaction, calling Close() on the session isn't diff --git a/src/NHibernate.Test/TestCase.cs b/src/NHibernate.Test/TestCase.cs index 13f82daf61e..710a043ea6c 100644 --- a/src/NHibernate.Test/TestCase.cs +++ b/src/NHibernate.Test/TestCase.cs @@ -15,7 +15,6 @@ using NUnit.Framework.Interfaces; using System.Text; using NHibernate.Dialect; -using NHibernate.Driver; namespace NHibernate.Test { @@ -163,13 +162,15 @@ public void TearDown() var wereClosed = _sessionFactory.CheckSessionsWereClosed(); var wasCleaned = CheckDatabaseWasCleaned(); var wereConnectionsClosed = CheckConnectionsWereClosed(); - fail = !wereClosed || !wasCleaned || !wereConnectionsClosed; + var wereTransactionsDisposed = CheckEnlistedTransactionsWereDisposed(); + fail = !wereClosed || !wasCleaned || !wereConnectionsClosed || !wereTransactionsDisposed; if (fail) { badCleanupMessage = "Test didn't clean up after itself. session closed: " + wereClosed + "; database cleaned: " + wasCleaned - + "; connection closed: " + wereConnectionsClosed; + + "; connection closed: " + wereConnectionsClosed + + "; transactions disposed:" + wereTransactionsDisposed;; if (testResult != null && testResult.Outcome.Status == TestStatus.Failed) { // Avoid hiding a test failure (asserts are usually not hidden, but other exception would be). @@ -260,6 +261,31 @@ private bool CheckConnectionsWereClosed() return false; } + private bool CheckEnlistedTransactionsWereDisposed() + { + System.Transactions.Transaction current = System.Transactions.Transaction.Current; + bool notAborted = ((System.Transactions.Transaction.Current?.TransactionInformation.Status) ?? System.Transactions.TransactionStatus.Aborted) != System.Transactions.TransactionStatus.Aborted; + if (!notAborted) return true; + + do + { + notAborted = current.TransactionInformation.Status != System.Transactions.TransactionStatus.Aborted; + + try + { + current.Dispose(); + } + catch (Exception ex) + { + log.Error("Error disposing enlisted transaction", ex); + } + + current = System.Transactions.Transaction.Current; + } while (current != null && notAborted); + + return false; + } + /// /// (Re)Create the configuration. /// @@ -296,16 +322,13 @@ protected virtual void DropSchema() public static void DropSchema(bool useStdOut, SchemaExport export, ISessionFactoryImplementor sfi) { - if (sfi?.ConnectionProvider.Driver is FirebirdClientDriver fbDriver) - { - // Firebird will pool each connection created during the test and will marked as used any table - // referenced by queries. It will at best delays those tables drop until connections are actually - // closed, or immediately fail dropping them. - // This results in other tests failing when they try to create tables with same name. - // By clearing the connection pool the tables will get dropped. This is done by the following code. - // Moved from NH1908 test case, contributed by Amro El-Fakharany. - fbDriver.ClearPool(null); - } + // Firebird will pool each connection created during the test and will marked as used any table + // referenced by queries. It will at best delays those tables drop until connections are actually + // closed, or immediately fail dropping them. + // This results in other tests failing when they try to create tables with same name. + // By clearing the connection pool the tables will get dropped. This is done by the following code. + // Moved from NH1908 test case, contributed by Amro El-Fakharany. + sfi?.ConnectionProvider.Driver.ClearPoolForFirebirdDriver(); export.Drop(useStdOut, true); } diff --git a/src/NHibernate.Test/TestEmbeddedConfig.cfg.xml b/src/NHibernate.Test/TestEmbeddedConfig.cfg.xml index 25058dae03a..6ba543f0cb3 100644 --- a/src/NHibernate.Test/TestEmbeddedConfig.cfg.xml +++ b/src/NHibernate.Test/TestEmbeddedConfig.cfg.xml @@ -3,10 +3,10 @@ NHibernate.Test.DebugConnectionProvider, NHibernate.Test NHibernate.Cache.HashtableCacheProvider, NHibernate - NHibernate.Driver.SqlClientDriver + NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer Server=localhost;initial catalog=nhibernate;User Id=;Password= true 1, false 0, yes 1, no 0 NHibernate.Dialect.MsSql2000Dialect NHibernate.Test.CfgTest.ConfigurationFixture+SampleQueryProvider, NHibernate.Test - \ No newline at end of file + diff --git a/src/NHibernate.Test/TestingExtensions.cs b/src/NHibernate.Test/TestingExtensions.cs new file mode 100644 index 00000000000..9bc2423f383 --- /dev/null +++ b/src/NHibernate.Test/TestingExtensions.cs @@ -0,0 +1,162 @@ +using NHibernate.Driver; + +namespace NHibernate.Test +{ + public static class TestingExtensions + { + public static bool IsOdbcDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 + if (driver is OdbcDriver) return true; +#endif + return false; + } + + public static bool IsOdbcDriver(this System.Type driverClass) + { +#if !NETCOREAPP2_0 + if (typeof(OdbcDriver).IsAssignableFrom(driverClass)) return true; +#endif + return false; + } + + public static bool IsOleDbDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 + if (driver is OleDbDriver) return true; +#endif + return false; + } + + public static bool IsOleDbDriver(this System.Type driverClass) + { +#if !NETCOREAPP2_0 + if (typeof(OleDbDriver).IsAssignableFrom(driverClass)) return true; +#endif + return false; + } + + /// + /// Matches both SQL Server 2000 and 2008 drivers + /// + public static bool IsSqlServerDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (driver is SqlClientDriver) return true; +#pragma warning restore 618 +#endif + if (driver is SqlServer2000Driver) return true; + return false; + } + + /// + /// Matches both SQL Server 2000 and 2008 drivers + /// + public static bool IsSqlServerDriver(this System.Type driverClass) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (typeof(SqlClientDriver).IsAssignableFrom(driverClass)) return true; +#pragma warning restore 618 +#endif + if (typeof(SqlServer2000Driver).IsAssignableFrom(driverClass)) return true; + return false; + } + + public static bool IsSqlServer2008Driver(this IDriver driver) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (driver is Sql2008ClientDriver) return true; +#pragma warning restore 618 +#endif + if (driver is SqlServer2008Driver) return true; + return false; + } + + public static bool IsMySqlDriver(this System.Type driverClass) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (typeof(MySqlDataDriver).IsAssignableFrom(driverClass)) return true; +#pragma warning restore 618 +#endif + if (typeof(MySqlDriver).IsAssignableFrom(driverClass)) return true; + return false; + } + + + public static bool IsFirebirdDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (driver is FirebirdClientDriver) return true; +#pragma warning restore 618 +#endif + if (driver is FirebirdDriver) return true; + return false; + } + + /// + /// If driver is Firebird, clear the pool. + /// Firebird will pool each connection created during the test and will marked as used any table + /// referenced by queries. It will at best delays those tables drop until connections are actually + /// closed, or immediately fail dropping them. + /// This results in other tests failing when they try to create tables with same name. + /// By clearing the connection pool the tables will get dropped. This is done by the following code. + /// Moved from NH1908 test case, contributed by Amro El-Fakharany. + /// + public static void ClearPoolForFirebirdDriver(this IDriver driver) + { + switch (driver) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + case FirebirdClientDriver fbDriver: + fbDriver.ClearPool(null); + break; +#pragma warning restore 618 +#endif + case FirebirdDriver fbDriver2: + fbDriver2.ClearPool(null); + break; + } + } + + public static bool IsOracleDataClientDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 + if (driver is OracleDataClientDriver) return true; +#endif + return false; + } + + public static bool IsOracleDataClientDriver(this System.Type driverClass) + { +#if !NETCOREAPP2_0 + if (typeof(OracleDataClientDriver).IsAssignableFrom(driverClass)) return true; +#endif + return false; + } + + public static bool IsOracleLiteDataClientDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 + if (driver is OracleLiteDataClientDriver) return true; +#endif + return false; + } + + public static bool IsOracleManagedDriver(this IDriver driver) + { +#if !NETCOREAPP2_0 +#pragma warning disable 618 + if (driver is OracleManagedDataClientDriver) return true; +#pragma warning restore 618 + if (driver is OracleManagedDriver) return true; +#endif + return false; + } + } +} diff --git a/src/NHibernate.Test/TestsContext.cs b/src/NHibernate.Test/TestsContext.cs new file mode 100644 index 00000000000..a9c33c3fc86 --- /dev/null +++ b/src/NHibernate.Test/TestsContext.cs @@ -0,0 +1,56 @@ +using System.Configuration; +using System.IO; +using System.Xml; + +using NHibernate.Cfg.ConfigurationSchema; +using NUnit.Framework; +using log4net.Repository.Hierarchy; + +namespace NHibernate.Test +{ + [SetUpFixture] + public class TestsContext + { + [OneTimeSetUp] + public void RunBeforeAnyTests() + { + HibernateConfiguration config = GetTestAssemblyHibernateConfiguration(); + NHibernate.Cfg.Environment.InitializeGlobalProperties(config); + + ConfigureLog4Net(); + } + + public static HibernateConfiguration GetTestAssemblyHibernateConfiguration() + { + HibernateConfiguration config; + string assemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"NHibernate.Test.dll"); + var configuration = ConfigurationManager.OpenExeConfiguration(assemblyPath); + ConfigurationSection configSection = configuration.GetSection(CfgXmlHelper.CfgSectionName); + + using (XmlTextReader reader = new XmlTextReader(configSection.SectionInformation.GetRawXml(), XmlNodeType.Document, null)) + { + config = new HibernateConfiguration(reader); + } + + return config; + } + + private static void ConfigureLog4Net() + { + var hierarchy = (Hierarchy)log4net.LogManager.GetRepository(typeof(TestsContext).Assembly); + + var consoleAppender = new log4net.Appender.ConsoleAppender() + { + Layout = new log4net.Layout.PatternLayout("%d{ABSOLUTE} %-5p %c{1}:%L - %m%n"), + }; + + ((Logger)hierarchy.GetLogger("NHibernate.Hql.Ast.ANTLR")).Level = log4net.Core.Level.Off; + ((Logger)hierarchy.GetLogger("NHibernate.SQL")).Level = log4net.Core.Level.Off; + ((Logger)hierarchy.GetLogger("NHibernate.AdoNet.AbstractBatcher")).Level = log4net.Core.Level.Off; + ((Logger)hierarchy.GetLogger("NHibernate.Tool.hbm2ddl.SchemaExport")).Level = log4net.Core.Level.Error; + hierarchy.Root.Level = log4net.Core.Level.Warn; + hierarchy.Root.AddAppender(consoleAppender); + hierarchy.Configured = true; + } + } +} diff --git a/src/NHibernate.Test/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs b/src/NHibernate.Test/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs index 3d0ae2e6d9f..551e4934200 100644 --- a/src/NHibernate.Test/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs +++ b/src/NHibernate.Test/Tools/hbm2ddl/SchemaMetadataUpdaterTest/SchemaMetadataUpdaterFixture.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.Mapping; using NHibernate.Tool.hbm2ddl; @@ -104,7 +103,7 @@ public void EnsureReservedWordsHardCodedInDialect() } } - if (sf.ConnectionProvider.Driver is OdbcDriver) + if (sf.ConnectionProvider.Driver.IsOdbcDriver()) { Assert.Inconclusive("ODBC has excess keywords reserved"); } @@ -257,7 +256,7 @@ public void WhenConfiguredOnlyExplicitAutoQuote() var configuration = TestConfigurationHelper.GetDefaultConfiguration(); var driverClass = ReflectHelper.ClassForName(configuration.GetProperty(Environment.ConnectionDriver)); // Test uses the default dialect driver, which will not accept Odbc or OleDb connection strings. - if (typeof(OdbcDriver).IsAssignableFrom(driverClass) || typeof(OleDbDriver).IsAssignableFrom(driverClass)) + if (driverClass.IsOdbcDriver() || driverClass.IsOleDbDriver()) Assert.Ignore("Test is not compatible with OleDb or ODBC driver connection strings"); var configuredDialect = Dialect.Dialect.GetDialect(); diff --git a/src/NHibernate.Test/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs b/src/NHibernate.Test/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs index 7ccd282a9cb..9e20b80389b 100644 --- a/src/NHibernate.Test/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs +++ b/src/NHibernate.Test/Tools/hbm2ddl/SchemaUpdate/MigrationFixture.cs @@ -2,7 +2,6 @@ using System.IO; using System.Reflection; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.Tool.hbm2ddl; using NHibernate.Util; using NUnit.Framework; @@ -19,7 +18,7 @@ private void MigrateSchema(string resource1, string resource2) var driverClass = ReflectHelper.ClassForName(v1cfg.GetProperty(Environment.ConnectionDriver)); // Odbc is not supported by schema update: System.Data.Odbc.OdbcConnection.GetSchema("ForeignKeys") fails with an ArgumentException: ForeignKeys is undefined. // It seems it would require its own DataBaseSchema, but this is bound to the dialect, not the driver. - if (typeof(OdbcDriver).IsAssignableFrom(driverClass)) + if (driverClass.IsOdbcDriver()) Assert.Ignore("Test is not compatible with ODBC"); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1)) @@ -65,4 +64,4 @@ public void SimpleColumnReplace() MigrateSchema(resource1, resource2); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs b/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs index 72d244ca927..8a8dca49f02 100644 --- a/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs +++ b/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs @@ -41,6 +41,7 @@ public void ShouldVerifySameTable() validator.Validate(); } +#if !NETCOREAPP2_0 [Test, SetCulture("tr-TR"), SetUICulture("tr-TR")] public void ShouldVerifySameTableTurkish() { @@ -69,6 +70,7 @@ public void ShouldVerifySameTableTurkish() export.Drop(true, true); } } +#endif [Test] public void ShouldNotVerifyModifiedTable() diff --git a/src/NHibernate.Test/TypesTest/AbstractDateTimeTypeFixture.cs b/src/NHibernate.Test/TypesTest/AbstractDateTimeTypeFixture.cs index 75fc976284e..2ed4774022e 100644 --- a/src/NHibernate.Test/TypesTest/AbstractDateTimeTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/AbstractDateTimeTypeFixture.cs @@ -575,16 +575,13 @@ DbParameter IDriver.GenerateParameter(DbCommand command, string name, SqlType sq public void CleanUp() { - if (_driverImplementation is FirebirdClientDriver fbDriver) - { - // Firebird will pool each connection created during the test and will marked as used any table - // referenced by queries. It will at best delays those tables drop until connections are actually - // closed, or immediately fail dropping them. - // This results in other tests failing when they try to create tables with same name. - // By clearing the connection pool the tables will get dropped. This is done by the following code. - // Moved from NH1908 test case, contributed by Amro El-Fakharany. - fbDriver.ClearPool(null); - } + // Firebird will pool each connection created during the test and will marked as used any table + // referenced by queries. It will at best delays those tables drop until connections are actually + // closed, or immediately fail dropping them. + // This results in other tests failing when they try to create tables with same name. + // By clearing the connection pool the tables will get dropped. This is done by the following code. + // Moved from NH1908 test case, contributed by Amro El-Fakharany. + _driverImplementation.ClearPoolForFirebirdDriver(); } #endregion diff --git a/src/NHibernate.Test/TypesTest/DateTime2TypeFixture.cs b/src/NHibernate.Test/TypesTest/DateTime2TypeFixture.cs index 5eec555af67..dd703c724a4 100644 --- a/src/NHibernate.Test/TypesTest/DateTime2TypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/DateTime2TypeFixture.cs @@ -1,5 +1,4 @@ using System; -using NHibernate.Driver; using NHibernate.SqlTypes; using NHibernate.Type; using NUnit.Framework; @@ -18,7 +17,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTime2 via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override string TypeName => "DateTime2"; protected override AbstractDateTimeType Type => NHibernateUtil.DateTime2; @@ -45,7 +44,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTime2 via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override string TypeName => "DateTime2WithScale"; protected override AbstractDateTimeType Type => (AbstractDateTimeType)TypeFactory.GetDateTime2Type(3); diff --git a/src/NHibernate.Test/TypesTest/DateTimeOffsetTypeFixture.cs b/src/NHibernate.Test/TypesTest/DateTimeOffsetTypeFixture.cs index 0881a08e878..664e1635da4 100644 --- a/src/NHibernate.Test/TypesTest/DateTimeOffsetTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/DateTimeOffsetTypeFixture.cs @@ -2,7 +2,6 @@ using System.Data; using System.Linq; using NHibernate.Cfg; -using NHibernate.Driver; using NHibernate.SqlTypes; using NHibernate.Tool.hbm2ddl; using NHibernate.Type; @@ -26,7 +25,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) => protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) => // Cannot handle DbType.DateTimeOffset via .Net ODBC. - !(factory.ConnectionProvider.Driver is OdbcDriver); + !(factory.ConnectionProvider.Driver.IsOdbcDriver()); protected override void Configure(Configuration configuration) { diff --git a/src/NHibernate.Test/TypesTest/StringTypeWithLengthFixture.cs b/src/NHibernate.Test/TypesTest/StringTypeWithLengthFixture.cs index e3e2367f0ea..688cfcc0a73 100644 --- a/src/NHibernate.Test/TypesTest/StringTypeWithLengthFixture.cs +++ b/src/NHibernate.Test/TypesTest/StringTypeWithLengthFixture.cs @@ -3,7 +3,6 @@ using NHibernate.Cfg.MappingSchema; using NHibernate.Criterion; using NHibernate.Dialect; -using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Mapping.ByCode; using NUnit.Framework; @@ -66,7 +65,7 @@ protected override void OnTearDown() public void ShouldPreventInsertionOfVeryLongStringThatWouldBeTruncated() { // This test case is for when the current driver will use a parameter size - // that is significantly larger than the mapped column size (e.g. SqlClientDriver currently). + // that is significantly larger than the mapped column size (e.g. SqlServer2000Driver currently). // Note: This test could possible be written as // "database must raise an error OR it must store and return the full value" @@ -119,7 +118,7 @@ public void CanCompareLongValueWithLongString() { var maxStringLength = GetLongStringMappedLength(); - if (Sfi.ConnectionProvider.Driver is OdbcDriver && maxStringLength >= 2000) + if (Sfi.ConnectionProvider.Driver.IsOdbcDriver() && maxStringLength >= 2000) Assert.Ignore("Odbc wrecks nvarchar parameter types when they are longer than 2000, it switch them to ntext"); var longString = new string('x', maxStringLength); diff --git a/src/NHibernate.Test/TypesTest/XDocTypeFixture.cs b/src/NHibernate.Test/TypesTest/XDocTypeFixture.cs index 6d256dc556c..0810d69e930 100644 --- a/src/NHibernate.Test/TypesTest/XDocTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/XDocTypeFixture.cs @@ -1,6 +1,5 @@ using System.Data; using System.Xml.Linq; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.Type; @@ -24,7 +23,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // No Xml support with Odbc (and likely OleDb too). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/TypesTest/XmlDocTypeFixture.cs b/src/NHibernate.Test/TypesTest/XmlDocTypeFixture.cs index 128e83f63be..761baca9fe4 100644 --- a/src/NHibernate.Test/TypesTest/XmlDocTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/XmlDocTypeFixture.cs @@ -1,6 +1,5 @@ using System.Data; using System.Xml; -using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.Type; @@ -24,7 +23,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected override bool AppliesTo(ISessionFactoryImplementor factory) { // No Xml support with Odbc (and likely OleDb too). - return factory.ConnectionProvider.Driver is SqlClientDriver; + return factory.ConnectionProvider.Driver.IsSqlServerDriver(); } [Test] diff --git a/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs b/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs index a3cc098edcc..e91a819b76f 100644 --- a/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs +++ b/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs @@ -83,6 +83,9 @@ public void NoTypeFoundReturnsNull() } [Test] +#if NETCOREAPP2_0 + [Ignore("System.Web assembly on this platform.")] +#endif public void TypeFoundInNotLoadedAssembly() { System.Type httpRequest = ReflectHelper.TypeFromAssembly("System.Web.HttpRequest", "System.Web", false); @@ -185,4 +188,4 @@ public class MyImplementation: IMyInterface public string Name { get; set; } public string Description { get; set; } } -} \ No newline at end of file +} diff --git a/src/NHibernate.TestDatabaseSetup/App.config b/src/NHibernate.TestDatabaseSetup/App.config deleted file mode 100644 index 1fa471187b0..00000000000 --- a/src/NHibernate.TestDatabaseSetup/App.config +++ /dev/null @@ -1,16 +0,0 @@ - - - -
- - - - - NHibernate.Driver.Sql2008ClientDriver - - Server=.\SQLExpress;initial catalog=master;Integrated Security=SSPI - - - - diff --git a/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj b/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj index eea8bca710c..991c5a03f61 100644 --- a/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj +++ b/src/NHibernate.TestDatabaseSetup/NHibernate.TestDatabaseSetup.csproj @@ -3,10 +3,16 @@ NHibernate.TestDatabaseSetup Test Database Setup for NHibernate. - net461 + netcoreapp2.0;net461 + true true $(NoWarn);3001;3002;3003;3005 + + + + + diff --git a/src/NHibernate.TestDatabaseSetup/TestDatabaseSetup.cs b/src/NHibernate.TestDatabaseSetup/TestDatabaseSetup.cs index bc9c9a417fa..e391fa99558 100644 --- a/src/NHibernate.TestDatabaseSetup/TestDatabaseSetup.cs +++ b/src/NHibernate.TestDatabaseSetup/TestDatabaseSetup.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +#if !NETCOREAPP2_0 using System.Data.Odbc; -using System.Data.SqlClient; using System.Data.SqlServerCe; using System.Data.SQLite; +#endif +using System.Data.SqlClient; using System.IO; using FirebirdSql.Data.FirebirdClient; using NHibernate.Test; @@ -17,17 +19,19 @@ public class DatabaseSetup { private static readonly IDictionary> SetupMethods = new Dictionary> { - {"NHibernate.Driver.SqlClientDriver", SetupSqlServer}, - {"NHibernate.Driver.Sql2008ClientDriver", SetupSqlServer}, +#if !NETCOREAPP2_0 {"NHibernate.Driver.OdbcDriver", SetupSqlServerOdbc}, - {"NHibernate.Driver.FirebirdClientDriver", SetupFirebird}, - {"NHibernate.Driver.SQLite20Driver", SetupSQLite}, - {"NHibernate.Driver.NpgsqlDriver", SetupNpgsql}, + {"NHibernate.Driver.SQLiteDriver, NHibernate.Driver.SQLite", SetupSQLite}, {"NHibernate.Driver.OracleDataClientDriver", SetupOracle}, - {"NHibernate.Driver.MySqlDataDriver", SetupMySql}, {"NHibernate.Driver.OracleClientDriver", SetupOracle}, - {"NHibernate.Driver.OracleManagedDataClientDriver", SetupOracle}, - {"NHibernate.Driver.SqlServerCeDriver", SetupSqlServerCe} + {"NHibernate.Driver.OracleManagedDriver, NHibernate.Driver.Oracle.Managed", SetupOracle}, + {"NHibernate.Driver.SqlServerCompactDriver, NHibernate.Driver.SqlServer.Compact", SetupSqlServerCe}, +#endif + {"NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer", SetupSqlServer}, + {"NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer", SetupSqlServer}, + {"NHibernate.Driver.FirebirdDriver, NHibernate.Driver.Firebird", SetupFirebird}, + {"NHibernate.Driver.PostgreSqlDriver, NHibernate.Driver.PostgreSql", SetupNpgsql}, + {"NHibernate.Driver.MySqlDriver, NHibernate.Driver.MySql", SetupMySql}, }; private static void SetupMySql(Cfg.Configuration obj) @@ -74,6 +78,7 @@ private static void SetupSqlServer(Cfg.Configuration cfg) } } +#if !NETCOREAPP2_0 private static void SetupSqlServerOdbc(Cfg.Configuration cfg) { var connStr = cfg.Properties[Cfg.Environment.ConnectionString]; @@ -100,6 +105,7 @@ private static void SetupSqlServerOdbc(Cfg.Configuration cfg) } } } +#endif private static void SetupFirebird(Cfg.Configuration cfg) { @@ -115,6 +121,7 @@ private static void SetupFirebird(Cfg.Configuration cfg) FbConnection.CreateDatabase(connStr, forcedWrites:false); } +#if !NETCOREAPP2_0 private static void SetupSqlServerCe(Cfg.Configuration cfg) { var connStr = cfg.Properties[Cfg.Environment.ConnectionString]; @@ -136,6 +143,7 @@ private static void SetupSqlServerCe(Cfg.Configuration cfg) en.CreateDatabase(); } } +#endif private static void SetupNpgsql(Cfg.Configuration cfg) { @@ -181,6 +189,7 @@ RETURNS uuid } } +#if !NETCOREAPP2_0 private static void SetupSQLite(Cfg.Configuration cfg) { var connStr = cfg.Properties[Cfg.Environment.ConnectionString]; @@ -230,7 +239,6 @@ private static void SetupOracle(Cfg.Configuration cfg) // } //} } +#endif } } - - diff --git a/src/NHibernate.Tool.HbmXsd/NHibernate.Tool.HbmXsd.csproj b/src/NHibernate.Tool.HbmXsd/NHibernate.Tool.HbmXsd.csproj index 042dcd1fa1f..5a03544418f 100644 --- a/src/NHibernate.Tool.HbmXsd/NHibernate.Tool.HbmXsd.csproj +++ b/src/NHibernate.Tool.HbmXsd/NHibernate.Tool.HbmXsd.csproj @@ -3,7 +3,7 @@ Tool to Generate Hbm classes for use by NHibernate. - net461 + net461 HbmXsd NHibernate.Tool.HbmXsd Exe @@ -13,4 +13,9 @@ + + + + + diff --git a/src/NHibernate.sln b/src/NHibernate.sln index d50878b114d..dcecc4d4c96 100644 --- a/src/NHibernate.sln +++ b/src/NHibernate.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26730.12 +VisualStudioVersion = 15.0.27004.2010 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{593DCEA7-C933-46F3-939F-D8172399AB05}" ProjectSection(SolutionItems) = preProject @@ -21,6 +21,22 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.TestDatabaseSetu EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "NHibernate.Test.VisualBasic", "NHibernate.Test.VisualBasic\NHibernate.Test.VisualBasic.vbproj", "{7C2EF610-BCA0-4D1F-898A-DE9908E4970C}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Drivers", "Drivers", "{2A64334E-8456-4426-B50A-6172C6C3FDD5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SqlServer", "NHibernate.Driver.SqlServer\NHibernate.Driver.SqlServer.csproj", "{CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SQLite", "NHibernate.Driver.SQLite\NHibernate.Driver.SQLite.csproj", "{99FE5A5C-F732-40A3-BEE6-ED5ADC393862}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.PostgreSql", "NHibernate.Driver.PostgreSql\NHibernate.Driver.PostgreSql.csproj", "{C7C835DC-0A59-4227-9C3C-0AF0633CD68C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.Oracle.Managed", "NHibernate.Driver.Oracle.Managed\NHibernate.Driver.Oracle.Managed.csproj", "{22409381-1808-4F0A-9C42-9FAA6B3BCFA2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.Firebird", "NHibernate.Driver.Firebird\NHibernate.Driver.Firebird.csproj", "{DADD54C1-3679-4672-9774-9362428EB9E0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.SqlServer.Compact", "NHibernate.Driver.SqlServer.Compact\NHibernate.Driver.SqlServer.Compact.csproj", "{11B3C504-D501-4766-AC36-0CF1A813815B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NHibernate.Driver.MySql", "NHibernate.Driver.MySql\NHibernate.Driver.MySql.csproj", "{4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -47,10 +63,47 @@ Global {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 + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39}.Release|Any CPU.Build.0 = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Debug|Any CPU.Build.0 = Debug|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Any CPU.ActiveCfg = Release|Any CPU + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862}.Release|Any CPU.Build.0 = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C}.Release|Any CPU.Build.0 = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2}.Release|Any CPU.Build.0 = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DADD54C1-3679-4672-9774-9362428EB9E0}.Release|Any CPU.Build.0 = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11B3C504-D501-4766-AC36-0CF1A813815B}.Release|Any CPU.Build.0 = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CF9FEEC5-3403-4F3F-9E4F-F0BAFE95DE39} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {99FE5A5C-F732-40A3-BEE6-ED5ADC393862} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {C7C835DC-0A59-4227-9C3C-0AF0633CD68C} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {22409381-1808-4F0A-9C42-9FAA6B3BCFA2} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {DADD54C1-3679-4672-9774-9362428EB9E0} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {11B3C504-D501-4766-AC36-0CF1A813815B} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + {4F5F0C13-F302-4CEE-B60E-A55D7C30E3F8} = {2A64334E-8456-4426-B50A-6172C6C3FDD5} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {E2025263-49BD-45D7-B628-8BDD471B546C} EndGlobalSection diff --git a/src/NHibernate.sln.DotSettings b/src/NHibernate.sln.DotSettings index a38b0a203a1..ec2a3ce2054 100644 --- a/src/NHibernate.sln.DotSettings +++ b/src/NHibernate.sln.DotSettings @@ -1,5 +1,5 @@  - USE_SPACES + True True True @@ -7,7 +7,10 @@ True True True + NEVER + NEVER False + NEVER False True True @@ -20,9 +23,14 @@ <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> True + True + True + True True + True True True + True True True NUnit Assert.NotNull diff --git a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs index 716bf24fc85..af80a97ce01 100644 --- a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.Common; using System.Text; @@ -163,3 +164,4 @@ protected override void Dispose(bool isDisposing) } } } +#endif diff --git a/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs b/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs index 61304f1241e..3314e26d94d 100644 --- a/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs +++ b/src/NHibernate/AdoNet/SqlClientBatchingBatcherFactory.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using NHibernate.Engine; namespace NHibernate.AdoNet @@ -9,4 +10,5 @@ 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..6fd049206f9 100644 --- a/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs +++ b/src/NHibernate/AdoNet/SqlClientSqlCommandSet.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.SqlClient; using System.Diagnostics; @@ -135,3 +136,4 @@ public void Dispose() } } } +#endif diff --git a/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs b/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs index 6c84e3f517f..616caef2ca0 100644 --- a/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs +++ b/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +#if !NETSTANDARD2_0 using System; using System.Data.Common; using System.Text; @@ -94,3 +95,4 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke } } } +#endif diff --git a/src/NHibernate/Async/Dialect/Dialect.cs b/src/NHibernate/Async/Dialect/Dialect.cs index fd92f72de29..f51726c807e 100644 --- a/src/NHibernate/Async/Dialect/Dialect.cs +++ b/src/NHibernate/Async/Dialect/Dialect.cs @@ -18,6 +18,7 @@ using NHibernate.Dialect.Function; using NHibernate.Dialect.Lock; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Id; using NHibernate.Mapping; diff --git a/src/NHibernate/Async/Engine/ActionQueue.cs b/src/NHibernate/Async/Engine/ActionQueue.cs index 15a5951dbdd..207f403659f 100644 --- a/src/NHibernate/Async/Engine/ActionQueue.cs +++ b/src/NHibernate/Async/Engine/ActionQueue.cs @@ -12,6 +12,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/NHibernate/Async/Impl/CriteriaImpl.cs b/src/NHibernate/Async/Impl/CriteriaImpl.cs index a40bc06bbd5..e73e21d327b 100644 --- a/src/NHibernate/Async/Impl/CriteriaImpl.cs +++ b/src/NHibernate/Async/Impl/CriteriaImpl.cs @@ -11,6 +11,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; using System.Text; using System.Threading; using NHibernate.Criterion; diff --git a/src/NHibernate/Async/Type/ArrayType.cs b/src/NHibernate/Async/Type/ArrayType.cs index e3c4fcb9d2c..7114dcb58e8 100644 --- a/src/NHibernate/Async/Type/ArrayType.cs +++ b/src/NHibernate/Async/Type/ArrayType.cs @@ -12,6 +12,7 @@ using System.Collections; using System.Collections.Generic; using System.Data.Common; +using System.Runtime.Serialization; using NHibernate.Collection; using NHibernate.Engine; using NHibernate.Persister.Collection; @@ -70,4 +71,4 @@ public override async Task ReplaceElementsAsync(object original, object return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Type/EntityType.cs b/src/NHibernate/Async/Type/EntityType.cs index 6e0e345b1bc..0c3c2f639bd 100644 --- a/src/NHibernate/Async/Type/EntityType.cs +++ b/src/NHibernate/Async/Type/EntityType.cs @@ -18,6 +18,7 @@ using NHibernate.Proxy; using NHibernate.Util; using System.Collections.Generic; +using System.Runtime.Serialization; namespace NHibernate.Type { @@ -65,12 +66,12 @@ protected internal async Task GetReferenceValueAsync(object value, ISess else { IEntityPersister entityPersister = session.Factory.GetEntityPersister(GetAssociatedEntityName()); - object propertyValue = entityPersister.GetPropertyValue(value, uniqueKeyPropertyName); + object propertyValue = entityPersister.GetPropertyValue(value, _uniqueKeyPropertyName); // We now have the value of the property-ref we reference. However, // we need to dig a little deeper, as that property might also be // an entity type, in which case we need to resolve its identitifier - IType type = entityPersister.GetPropertyType(uniqueKeyPropertyName); + IType type = entityPersister.GetPropertyType(_uniqueKeyPropertyName); if (type.IsEntityType) { propertyValue = await (((EntityType) type).GetReferenceValueAsync(propertyValue, session, cancellationToken)).ConfigureAwait(false); @@ -98,9 +99,9 @@ public override async Task ReplaceAsync(object original, object target, { return target; } - if (session.GetContextEntityIdentifier(original) == null && (await (ForeignKeys.IsTransientFastAsync(associatedEntityName, original, session, cancellationToken)).ConfigureAwait(false)).GetValueOrDefault()) + if (session.GetContextEntityIdentifier(original) == null && (await (ForeignKeys.IsTransientFastAsync(_associatedEntityName, original, session, cancellationToken)).ConfigureAwait(false)).GetValueOrDefault()) { - object copy = session.Factory.GetEntityPersister(associatedEntityName).Instantiate(null); + object copy = session.Factory.GetEntityPersister(_associatedEntityName).Instantiate(null); //TODO: should this be Session.instantiate(Persister, ...)? copyCache.Add(original, copy); return copy; @@ -129,7 +130,7 @@ public override async Task ReplaceAsync(object original, object target, /// /// An instance of the object or if the identifer was null. /// - public override sealed async Task NullSafeGetAsync(DbDataReader rs, string[] names, ISessionImplementor session, object owner, CancellationToken cancellationToken) + public sealed override async Task NullSafeGetAsync(DbDataReader rs, string[] names, ISessionImplementor session, object owner, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await (ResolveIdentifierAsync(await (HydrateAsync(rs, names, session, owner, cancellationToken)).ConfigureAwait(false), session, owner, cancellationToken)).ConfigureAwait(false); @@ -144,10 +145,10 @@ protected async Task ResolveIdentifierAsync(object id, ISessionImplement { cancellationToken.ThrowIfCancellationRequested(); string entityName = GetAssociatedEntityName(); - bool isProxyUnwrapEnabled = unwrapProxy && session.Factory + bool isProxyUnwrapEnabled = _unwrapProxy && session.Factory .GetEntityPersister(entityName).IsInstrumented; - object proxyOrEntity = await (session.InternalLoadAsync(entityName, id, eager, IsNullable && !isProxyUnwrapEnabled, cancellationToken)).ConfigureAwait(false); + object proxyOrEntity = await (session.InternalLoadAsync(entityName, id, _eager, IsNullable && !isProxyUnwrapEnabled, cancellationToken)).ConfigureAwait(false); if (proxyOrEntity.IsProxy()) { @@ -178,21 +179,19 @@ public override Task ResolveIdentifierAsync(object value, ISessionImplem { return Task.FromResult(null); } - else + + if (IsNull(owner, session)) { - if (IsNull(owner, session)) - { - return Task.FromResult(null); //EARLY EXIT! - } + return Task.FromResult(null); //EARLY EXIT! + } - if (IsReferenceToPrimaryKey) - { - return ResolveIdentifierAsync(value, session, cancellationToken); - } - else - { - return LoadByUniqueKeyAsync(GetAssociatedEntityName(), uniqueKeyPropertyName, value, session, cancellationToken); - } + if (IsReferenceToPrimaryKey) + { + return ResolveIdentifierAsync(value, session, cancellationToken); + } + else + { + return LoadByUniqueKeyAsync(GetAssociatedEntityName(), _uniqueKeyPropertyName, value, session, cancellationToken); } } catch (Exception ex) diff --git a/src/NHibernate/Async/Type/SerializableType.cs b/src/NHibernate/Async/Type/SerializableType.cs index 8acf9f5fc56..5ccbeb367e6 100644 --- a/src/NHibernate/Async/Type/SerializableType.cs +++ b/src/NHibernate/Async/Type/SerializableType.cs @@ -16,6 +16,7 @@ using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Engine; using NHibernate.SqlTypes; +using NHibernate.Util; namespace NHibernate.Type { @@ -56,4 +57,4 @@ public override Task DisassembleAsync(object value, ISessionImplementor } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs b/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs index 7bdff38d8da..81dd215f1ec 100644 --- a/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs +++ b/src/NHibernate/Bytecode/Lightweight/ReflectionOptimizer.cs @@ -101,9 +101,13 @@ protected virtual void ThrowExceptionForNoDefaultCtor(System.Type type) protected DynamicMethod CreateDynamicMethod(System.Type returnType, System.Type[] argumentTypes) { System.Type owner = mappedType.IsInterface ? typeof (object) : mappedType; +#if !NETSTANDARD2_0 #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); } diff --git a/src/NHibernate/Cfg/Configuration.cs b/src/NHibernate/Cfg/Configuration.cs index 01cf85eebc0..c9b71bcf45d 100644 --- a/src/NHibernate/Cfg/Configuration.cs +++ b/src/NHibernate/Cfg/Configuration.cs @@ -1430,6 +1430,11 @@ private void AddProperties(ISessionFactoryConfiguration factoryConfiguration) public Configuration Configure() { var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as IHibernateConfiguration; + return Configure(hc); + } + + public Configuration Configure(IHibernateConfiguration hc) + { if (hc != null && hc.SessionFactory != null) { return DoConfigure(hc.SessionFactory); diff --git a/src/NHibernate/Cfg/Environment.cs b/src/NHibernate/Cfg/Environment.cs index 97fd19b075b..4637fe325fe 100644 --- a/src/NHibernate/Cfg/Environment.cs +++ b/src/NHibernate/Cfg/Environment.cs @@ -278,7 +278,7 @@ public static string Version private static IBytecodeProvider BytecodeProviderInstance; private static bool EnableReflectionOptimizer; - private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Environment)); + private static readonly INHibernateLogger log; /// /// Issue warnings to user when any obsolete property names are used. @@ -289,6 +289,8 @@ public static void VerifyProperties(IDictionary props) { } static Environment() { + log = NHibernateLogger.For(typeof(Environment)); + // Computing the version string is a bit expensive, so do it only if logging is enabled. if (log.IsInfoEnabled()) { @@ -296,27 +298,27 @@ static Environment() } GlobalProperties = new Dictionary(); - GlobalProperties[PropertyUseReflectionOptimizer] = bool.TrueString; - LoadGlobalPropertiesFromAppConfig(); - VerifyProperties(GlobalProperties); - - BytecodeProviderInstance = BuildBytecodeProvider(GlobalProperties); - EnableReflectionOptimizer = PropertiesHelper.GetBoolean(PropertyUseReflectionOptimizer, GlobalProperties); + InitializeGlobalProperties(LoadGlobalPropertiesFromAppConfig()); + } - if (EnableReflectionOptimizer) + private static IHibernateConfiguration LoadGlobalPropertiesFromAppConfig() + { + var assemblyLocation = Assembly.GetEntryAssembly()?.Location; + if (assemblyLocation == null) return null; + + var configuration = ConfigurationManager.OpenExeConfiguration(assemblyLocation); + if (configuration == null) { - log.Info("Using reflection optimizer"); + log.Info(string.Format("No configuration found at entry assembly location {0}", assemblyLocation)); + return null; } - } - private static void LoadGlobalPropertiesFromAppConfig() - { - object config = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName); + object config = configuration.GetSection(CfgXmlHelper.CfgSectionName); if (config == null) { log.Info("{0} section not found in application configuration file", CfgXmlHelper.CfgSectionName); - return; + return null; } var nhConfig = config as IHibernateConfiguration; @@ -325,18 +327,39 @@ private static void LoadGlobalPropertiesFromAppConfig() log.Info( "{0} section handler, in application configuration file, is not IHibernateConfiguration, section ignored", CfgXmlHelper.CfgSectionName); - return; + return null; } - GlobalProperties[PropertyBytecodeProvider] = nhConfig.ByteCodeProviderType; - GlobalProperties[PropertyUseReflectionOptimizer] = nhConfig.UseReflectionOptimizer.ToString(); - if (nhConfig.SessionFactory != null) + return nhConfig; + } + + public static void InitializeGlobalProperties(IHibernateConfiguration nhConfig) + { + GlobalProperties.Clear(); + GlobalProperties[PropertyUseReflectionOptimizer] = bool.TrueString; + + if (nhConfig != null) { - foreach (var kvp in nhConfig.SessionFactory.Properties) + GlobalProperties[PropertyBytecodeProvider] = nhConfig.ByteCodeProviderType; + GlobalProperties[PropertyUseReflectionOptimizer] = nhConfig.UseReflectionOptimizer.ToString(); + if (nhConfig.SessionFactory != null) { - GlobalProperties[kvp.Key] = kvp.Value; + foreach (var kvp in nhConfig.SessionFactory.Properties) + { + GlobalProperties[kvp.Key] = kvp.Value; + } } } + + VerifyProperties(GlobalProperties); + + BytecodeProviderInstance = BuildBytecodeProvider(GlobalProperties); + EnableReflectionOptimizer = PropertiesHelper.GetBoolean(PropertyUseReflectionOptimizer, GlobalProperties); + + if (EnableReflectionOptimizer) + { + log.Info("Using reflection optimizer"); + } } internal static void ResetSessionFactoryProperties() diff --git a/src/NHibernate/Connection/ConnectionProvider.cs b/src/NHibernate/Connection/ConnectionProvider.cs index 6a1882515b6..3c93a13dfee 100644 --- a/src/NHibernate/Connection/ConnectionProvider.cs +++ b/src/NHibernate/Connection/ConnectionProvider.cs @@ -112,9 +112,51 @@ protected virtual void ConfigureDriver(IDictionary settings) { throw new HibernateException("Could not create the driver from " + driverClass + ".", e); } + +#if !NETSTANDARD2_0 +#pragma warning disable 618 + switch (driver) + { + case NpgsqlDriver _: + LogObsoleteDriver(nameof(NpgsqlDriver), "PostgreSql", "PostgreSqlDriver"); + break; + case MySqlDataDriver _: + LogObsoleteDriver(nameof(MySqlDataDriver), "MySql", "MySqlDriver"); + break; + case FirebirdClientDriver _: + LogObsoleteDriver(nameof(FirebirdClientDriver), "Firebird", "FirebirdDriver"); + break; + case OracleManagedDataClientDriver _: + LogObsoleteDriver(nameof(OracleManagedDataClientDriver), "Oracle.Managed", "OracleManagedDriver"); + break; + case SQLite20Driver _: + LogObsoleteDriver(nameof(SQLite20Driver), "SQLite", "SQLiteDriver"); + break; + case Sql2008ClientDriver _: + LogObsoleteDriver(nameof(Sql2008ClientDriver), "SqlServer", "SqlServer2008Driver"); + break; + case SqlClientDriver _: + LogObsoleteDriver(nameof(SqlClientDriver), "SqlServer", "SqlServer2000Driver"); + break; + case SqlServerCeDriver _: + LogObsoleteDriver(nameof(SqlServerCeDriver), "SqlServer.Compact", "SqlServerCompactDriver"); + break; + } +#pragma warning restore 618 +#endif } } + private static void LogObsoleteDriver(string obsoleteDriverName, string nugetName, string newDriverName) + { + log.Warn( + "Using \"{0}\" from main NHibernate package is obsolete." + + " Install the NHibernate.Driver.{1} NuGet package and change " + Environment.ConnectionDriver + " setting to \"NHibernate.Driver.{2}, NHibernate.Driver.{1}\".", + obsoleteDriverName, + nugetName, + newDriverName); + } + /// /// Gets the for the /// to connect to the database. diff --git a/src/NHibernate/Context/CallSessionContext.cs b/src/NHibernate/Context/CallSessionContext.cs index 9b6d2b3ce83..f9fc868f863 100644 --- a/src/NHibernate/Context/CallSessionContext.cs +++ b/src/NHibernate/Context/CallSessionContext.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Collections; using System.Runtime.Remoting.Messaging; @@ -36,4 +37,5 @@ 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..68c28aaf963 100644 --- a/src/NHibernate/Context/ReflectiveHttpContext.cs +++ b/src/NHibernate/Context/ReflectiveHttpContext.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Collections; using System.Linq.Expressions; @@ -54,4 +55,5 @@ private static void CreateHttpContextItemsGetter() HttpContextItemsGetter = (Func) Expression.Lambda(itemsProperty, contextParam).Compile(); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Context/WebSessionContext.cs b/src/NHibernate/Context/WebSessionContext.cs index 3f30059be79..b44767d6bd2 100644 --- a/src/NHibernate/Context/WebSessionContext.cs +++ b/src/NHibernate/Context/WebSessionContext.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Collections; using NHibernate.Engine; @@ -25,4 +26,5 @@ protected override void SetMap(IDictionary value) ReflectiveHttpContext.HttpContextCurrentItems[SessionFactoryMapKey] = value; } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Dialect/DB2400Dialect.cs b/src/NHibernate/Dialect/DB2400Dialect.cs index aa306a0d05a..775864621b1 100644 --- a/src/NHibernate/Dialect/DB2400Dialect.cs +++ b/src/NHibernate/Dialect/DB2400Dialect.cs @@ -15,7 +15,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.DB2400Driver /// /// /// @@ -61,4 +61,4 @@ public override bool SupportsVariableLimit get { return false; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/DB2Dialect.cs b/src/NHibernate/Dialect/DB2Dialect.cs index 3bcd3f01da2..03aa5f59475 100644 --- a/src/NHibernate/Dialect/DB2Dialect.cs +++ b/src/NHibernate/Dialect/DB2Dialect.cs @@ -18,7 +18,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.DB2Driver /// /// /// diff --git a/src/NHibernate/Dialect/Dialect.cs b/src/NHibernate/Dialect/Dialect.cs index 53a31c43e15..0d8e72896e9 100644 --- a/src/NHibernate/Dialect/Dialect.cs +++ b/src/NHibernate/Dialect/Dialect.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; @@ -8,6 +9,7 @@ using NHibernate.Dialect.Function; using NHibernate.Dialect.Lock; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.Exceptions; using NHibernate.Id; using NHibernate.Mapping; @@ -47,6 +49,7 @@ public abstract partial class Dialect private readonly IDictionary _sqlFunctions; private static readonly IDictionary StandardAggregateFunctions = CollectionHelper.CreateCaseInsensitiveHashtable(); + private static readonly ConcurrentDictionary ExternalDriverExistsCache = new ConcurrentDictionary(); private static readonly IViolatedConstraintNameExtracter Extracter; @@ -2550,5 +2553,12 @@ public virtual ISQLExceptionConverter BuildSQLExceptionConverter() // may override to return whatever is most appropriate for that vendor. return new SQLStateConverter(ViolatedConstraintNameExtracter); } + + internal static string GetDriverName(string preferredName) where TFallback : IDriver + { + return ExternalDriverExistsCache.GetOrAdd(preferredName, s => ReflectHelper.ClassForFullNameOrNull(s) == null) + ? typeof(TFallback).FullName + : preferredName; + } } } diff --git a/src/NHibernate/Dialect/FirebirdDialect.cs b/src/NHibernate/Dialect/FirebirdDialect.cs index 5fa709e15c9..429913a4f97 100644 --- a/src/NHibernate/Dialect/FirebirdDialect.cs +++ b/src/NHibernate/Dialect/FirebirdDialect.cs @@ -4,9 +4,11 @@ using System.Data.Common; using NHibernate.Dialect.Function; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.Type; +using NHibernate.Util; using Environment = NHibernate.Cfg.Environment; namespace NHibernate.Dialect @@ -23,7 +25,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.FirebirdDriver, NHibernate.Driver.Firebird /// /// /// @@ -34,7 +36,13 @@ public FirebirdDialect() RegisterKeywords(); RegisterColumnTypes(); RegisterFunctions(); - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.FirebirdClientDriver"; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.FirebirdDriver, NHibernate.Driver.Firebird"); } public override string AddColumnString diff --git a/src/NHibernate/Dialect/InformixDialect.cs b/src/NHibernate/Dialect/InformixDialect.cs index 4bedf931856..05c8608f92d 100644 --- a/src/NHibernate/Dialect/InformixDialect.cs +++ b/src/NHibernate/Dialect/InformixDialect.cs @@ -27,7 +27,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.OdbcDriver /// /// /// diff --git a/src/NHibernate/Dialect/InformixDialect0940.cs b/src/NHibernate/Dialect/InformixDialect0940.cs index 59ef5b7a6e6..7c22a4ac9b5 100644 --- a/src/NHibernate/Dialect/InformixDialect0940.cs +++ b/src/NHibernate/Dialect/InformixDialect0940.cs @@ -26,7 +26,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.OdbcDriver /// /// /// diff --git a/src/NHibernate/Dialect/InformixDialect1000.cs b/src/NHibernate/Dialect/InformixDialect1000.cs index db4c9781591..1b7d7cf503e 100644 --- a/src/NHibernate/Dialect/InformixDialect1000.cs +++ b/src/NHibernate/Dialect/InformixDialect1000.cs @@ -25,7 +25,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.OdbcDriver /// /// /// diff --git a/src/NHibernate/Dialect/IngresDialect.cs b/src/NHibernate/Dialect/IngresDialect.cs index 9741642ccde..108e1e759dc 100644 --- a/src/NHibernate/Dialect/IngresDialect.cs +++ b/src/NHibernate/Dialect/IngresDialect.cs @@ -15,7 +15,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.IngresDriver /// /// /// diff --git a/src/NHibernate/Dialect/MsSql2000Dialect.cs b/src/NHibernate/Dialect/MsSql2000Dialect.cs index 7681e988d39..dd3e12e9865 100644 --- a/src/NHibernate/Dialect/MsSql2000Dialect.cs +++ b/src/NHibernate/Dialect/MsSql2000Dialect.cs @@ -28,7 +28,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer /// /// /// adonet.batch_size @@ -42,6 +42,16 @@ namespace NHibernate.Dialect /// public class MsSql2000Dialect : Dialect { + public const int MaxSizeForAnsiClob = 2147483647; // int.MaxValue + public const int MaxSizeForClob = 1073741823; // int.MaxValue / 2 + public const int MaxSizeForBlob = 2147483647; // int.MaxValue + + public const int MaxSizeForLengthLimitedAnsiString = 8000; + public const int MaxSizeForLengthLimitedString = 4000; + public const int MaxSizeForLengthLimitedBinary = 8000; + public const byte MaxDateTime2 = 8; + public const byte MaxDateTimeOffset = 10; + public MsSql2000Dialect() { RegisterCharacterTypeMappings(); @@ -59,7 +69,14 @@ public MsSql2000Dialect() protected virtual void RegisterDefaultProperties() { - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver"; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.SqlServer2000Driver, NHibernate.Driver.SqlServer"); + DefaultProperties[Environment.BatchSize] = "20"; DefaultProperties[Environment.QuerySubstitutions] = "true 1, false 0, yes 'Y', no 'N'"; } @@ -357,8 +374,8 @@ protected virtual void RegisterGuidTypeMapping() protected virtual void RegisterLargeObjectTypeMappings() { RegisterColumnType(DbType.Binary, "VARBINARY(8000)"); - RegisterColumnType(DbType.Binary, SqlClientDriver.MaxSizeForLengthLimitedBinary, "VARBINARY($l)"); - RegisterColumnType(DbType.Binary, SqlClientDriver.MaxSizeForBlob, "IMAGE"); + RegisterColumnType(DbType.Binary, MaxSizeForLengthLimitedBinary, "VARBINARY($l)"); + RegisterColumnType(DbType.Binary, MaxSizeForBlob, "IMAGE"); } protected virtual void RegisterDateTimeTypeMappings() @@ -388,13 +405,13 @@ protected virtual void RegisterCharacterTypeMappings() RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)"); RegisterColumnType(DbType.AnsiStringFixedLength, 8000, "CHAR($l)"); RegisterColumnType(DbType.AnsiString, "VARCHAR(255)"); - RegisterColumnType(DbType.AnsiString, SqlClientDriver.MaxSizeForLengthLimitedAnsiString, "VARCHAR($l)"); - RegisterColumnType(DbType.AnsiString, SqlClientDriver.MaxSizeForAnsiClob, "TEXT"); + RegisterColumnType(DbType.AnsiString, MaxSizeForLengthLimitedAnsiString, "VARCHAR($l)"); + RegisterColumnType(DbType.AnsiString, MaxSizeForAnsiClob, "TEXT"); RegisterColumnType(DbType.StringFixedLength, "NCHAR(255)"); - RegisterColumnType(DbType.StringFixedLength, SqlClientDriver.MaxSizeForLengthLimitedString, "NCHAR($l)"); + RegisterColumnType(DbType.StringFixedLength, MaxSizeForLengthLimitedString, "NCHAR($l)"); RegisterColumnType(DbType.String, "NVARCHAR(255)"); - RegisterColumnType(DbType.String, SqlClientDriver.MaxSizeForLengthLimitedString, "NVARCHAR($l)"); - RegisterColumnType(DbType.String, SqlClientDriver.MaxSizeForClob, "NTEXT"); + RegisterColumnType(DbType.String, MaxSizeForLengthLimitedString, "NVARCHAR($l)"); + RegisterColumnType(DbType.String, MaxSizeForClob, "NTEXT"); } public override string AddColumnString @@ -446,7 +463,7 @@ public override string GetDropTableString(string tableName) "if exists (select * from dbo.sysobjects where id = object_id(N'{0}') and OBJECTPROPERTY(id, N'IsUserTable') = 1)" + " drop table {0}"; - return String.Format(dropTable, tableName); + return string.Format(dropTable, tableName); } public override string ForUpdateString diff --git a/src/NHibernate/Dialect/MsSql2005Dialect.cs b/src/NHibernate/Dialect/MsSql2005Dialect.cs index 7383e1214ef..3190df79414 100644 --- a/src/NHibernate/Dialect/MsSql2005Dialect.cs +++ b/src/NHibernate/Dialect/MsSql2005Dialect.cs @@ -1,5 +1,4 @@ using System.Data; -using NHibernate.Driver; using NHibernate.Mapping; using NHibernate.SqlCommand; using NHibernate.Util; @@ -8,6 +7,9 @@ namespace NHibernate.Dialect { public class MsSql2005Dialect : MsSql2000Dialect { + ///http://stackoverflow.com/a/7264795/259946 + public const int MaxSizeForXml = 2147483647; // int.MaxValue + public MsSql2005Dialect() { RegisterColumnType(DbType.Xml, "XML"); @@ -16,16 +18,16 @@ public MsSql2005Dialect() protected override void RegisterCharacterTypeMappings() { base.RegisterCharacterTypeMappings(); - RegisterColumnType(DbType.String, SqlClientDriver.MaxSizeForClob, "NVARCHAR(MAX)"); - RegisterColumnType(DbType.AnsiString, SqlClientDriver.MaxSizeForAnsiClob, "VARCHAR(MAX)"); + RegisterColumnType(DbType.String, MaxSizeForClob, "NVARCHAR(MAX)"); + RegisterColumnType(DbType.AnsiString, MaxSizeForAnsiClob, "VARCHAR(MAX)"); } protected override void RegisterLargeObjectTypeMappings() { base.RegisterLargeObjectTypeMappings(); RegisterColumnType(DbType.Binary, "VARBINARY(MAX)"); - RegisterColumnType(DbType.Binary, SqlClientDriver.MaxSizeForLengthLimitedBinary, "VARBINARY($l)"); - RegisterColumnType(DbType.Binary, SqlClientDriver.MaxSizeForBlob, "VARBINARY(MAX)"); + RegisterColumnType(DbType.Binary, MaxSizeForLengthLimitedBinary, "VARBINARY($l)"); + RegisterColumnType(DbType.Binary, MaxSizeForBlob, "VARBINARY(MAX)"); } protected override void RegisterKeywords() diff --git a/src/NHibernate/Dialect/MsSql2008Dialect.cs b/src/NHibernate/Dialect/MsSql2008Dialect.cs index d19bfc7b19c..b97c3b0ed8c 100644 --- a/src/NHibernate/Dialect/MsSql2008Dialect.cs +++ b/src/NHibernate/Dialect/MsSql2008Dialect.cs @@ -69,7 +69,13 @@ protected override void RegisterKeywords() protected override void RegisterDefaultProperties() { base.RegisterDefaultProperties(); - DefaultProperties[Environment.ConnectionDriver] = typeof(Sql2008ClientDriver).AssemblyQualifiedName; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.SqlServer2008Driver, NHibernate.Driver.SqlServer"); } public override string CurrentTimestampSQLFunctionName => diff --git a/src/NHibernate/Dialect/MsSqlCeDialect.cs b/src/NHibernate/Dialect/MsSqlCeDialect.cs index 4b4f4bb9e1b..1b130f217bb 100644 --- a/src/NHibernate/Dialect/MsSqlCeDialect.cs +++ b/src/NHibernate/Dialect/MsSqlCeDialect.cs @@ -4,6 +4,7 @@ using System.Text; using NHibernate.Dialect.Function; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.Id; using NHibernate.SqlCommand; using NHibernate.Util; @@ -202,7 +203,14 @@ protected virtual void RegisterFunctions() protected virtual void RegisterDefaultProperties() { - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.SqlServerCeDriver"; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.SqlServerCompactDriver, NHibernate.Driver.SqlServer.Compact"); + DefaultProperties[Environment.PrepareSql] = "false"; } diff --git a/src/NHibernate/Dialect/MySQLDialect.cs b/src/NHibernate/Dialect/MySQLDialect.cs index f38759e7964..76a82c07a35 100644 --- a/src/NHibernate/Dialect/MySQLDialect.cs +++ b/src/NHibernate/Dialect/MySQLDialect.cs @@ -4,6 +4,7 @@ using System.Text; using NHibernate.Dialect.Function; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.SqlCommand; using NHibernate.SqlTypes; using NHibernate.Util; @@ -23,7 +24,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.MySqlDriver, NHibernate.Driver.MySql /// /// /// @@ -112,7 +113,13 @@ public MySQLDialect() //functions: RegisterFunctions(); - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.MySqlDataDriver"; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.MySqlDriver, NHibernate.Driver.MySql"); } #region private static readonly string[] DialectKeywords = { ... } diff --git a/src/NHibernate/Dialect/OracleLiteDialect.cs b/src/NHibernate/Dialect/OracleLiteDialect.cs index 9b6259f36dc..0e35da13fa9 100644 --- a/src/NHibernate/Dialect/OracleLiteDialect.cs +++ b/src/NHibernate/Dialect/OracleLiteDialect.cs @@ -17,7 +17,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.OracleLiteDataClientDriver /// /// /// diff --git a/src/NHibernate/Dialect/PostgreSQLDialect.cs b/src/NHibernate/Dialect/PostgreSQLDialect.cs index 3ddc692c767..9d855a03088 100644 --- a/src/NHibernate/Dialect/PostgreSQLDialect.cs +++ b/src/NHibernate/Dialect/PostgreSQLDialect.cs @@ -3,6 +3,7 @@ using NHibernate.Cfg; using NHibernate.Dialect.Function; using NHibernate.Dialect.Schema; +using NHibernate.Driver; using NHibernate.SqlCommand; using NHibernate.SqlTypes; @@ -20,7 +21,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.PostgreSqlDriver, NHibernate.Driver.PostgreSql /// /// /// @@ -28,7 +29,13 @@ public class PostgreSQLDialect : Dialect { public PostgreSQLDialect() { - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.NpgsqlDriver"; + DefaultProperties[Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.PostgreSqlDriver, NHibernate.Driver.PostgreSql"); RegisterDateTimeTypeMappings(); RegisterColumnType(DbType.AnsiStringFixedLength, "char(255)"); diff --git a/src/NHibernate/Dialect/SQLiteDialect.cs b/src/NHibernate/Dialect/SQLiteDialect.cs index 87904958221..28a5cc02976 100644 --- a/src/NHibernate/Dialect/SQLiteDialect.cs +++ b/src/NHibernate/Dialect/SQLiteDialect.cs @@ -3,6 +3,7 @@ using System.Data.Common; using System.Text; using NHibernate.Dialect.Function; +using NHibernate.Driver; using NHibernate.SqlCommand; using NHibernate.Util; @@ -180,7 +181,14 @@ protected virtual void RegisterKeywords() protected virtual void RegisterDefaultProperties() { - DefaultProperties[Cfg.Environment.ConnectionDriver] = "NHibernate.Driver.SQLite20Driver"; + DefaultProperties[Cfg.Environment.ConnectionDriver] = +#if !NETSTANDARD2_0 +#pragma warning disable 618 + GetDriverName +#pragma warning restore 618 +#endif + ("NHibernate.Driver.SQLiteDriver, NHibernate.Driver.SQLite"); + DefaultProperties[Cfg.Environment.QuerySubstitutions] = "true 1, false 0, yes 'Y', no 'N'"; } diff --git a/src/NHibernate/Dialect/SybaseASA9Dialect.cs b/src/NHibernate/Dialect/SybaseASA9Dialect.cs index 699a5430433..4c2f5ec82d2 100644 --- a/src/NHibernate/Dialect/SybaseASA9Dialect.cs +++ b/src/NHibernate/Dialect/SybaseASA9Dialect.cs @@ -24,7 +24,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SybaseAsaClientDriver /// /// /// prepare_sql diff --git a/src/NHibernate/Dialect/SybaseASE15Dialect.cs b/src/NHibernate/Dialect/SybaseASE15Dialect.cs index a1b1be5e49d..731194a3d87 100644 --- a/src/NHibernate/Dialect/SybaseASE15Dialect.cs +++ b/src/NHibernate/Dialect/SybaseASE15Dialect.cs @@ -21,7 +21,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SybaseAseClientDriver /// /// /// diff --git a/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs b/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs index 5758cd5da31..1924568e08e 100644 --- a/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs +++ b/src/NHibernate/Dialect/SybaseSQLAnywhere10Dialect.cs @@ -38,7 +38,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SybaseSQLAnywhereDriver /// /// /// prepare_sql diff --git a/src/NHibernate/Dialect/SybaseSQLAnywhere11Dialect.cs b/src/NHibernate/Dialect/SybaseSQLAnywhere11Dialect.cs index d28f67cdffe..b05d89a29b2 100644 --- a/src/NHibernate/Dialect/SybaseSQLAnywhere11Dialect.cs +++ b/src/NHibernate/Dialect/SybaseSQLAnywhere11Dialect.cs @@ -32,7 +32,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SybaseSQLAnywhereDriver /// /// /// prepare_sql diff --git a/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs b/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs index e99a40a3b26..adf55c5c395 100644 --- a/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs +++ b/src/NHibernate/Dialect/SybaseSQLAnywhere12Dialect.cs @@ -43,7 +43,7 @@ namespace NHibernate.Dialect /// /// /// connection.driver_class - /// + /// NHibernate.Driver.SybaseSQLAnywhereDotNet4Driver /// /// /// prepare_sql @@ -127,4 +127,4 @@ public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) return new SybaseAnywhereDataBaseMetaData(connection); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/CsharpSqliteDriver.cs b/src/NHibernate/Driver/CsharpSqliteDriver.cs index c11e51006ab..3337c057d81 100644 --- a/src/NHibernate/Driver/CsharpSqliteDriver.cs +++ b/src/NHibernate/Driver/CsharpSqliteDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE namespace NHibernate.Driver { /// @@ -51,3 +52,4 @@ public override bool SupportsMultipleOpenReaders } } } +#endif diff --git a/src/NHibernate/Driver/DB2400Driver.cs b/src/NHibernate/Driver/DB2400Driver.cs index c2c128bc68d..a8710f583ac 100644 --- a/src/NHibernate/Driver/DB2400Driver.cs +++ b/src/NHibernate/Driver/DB2400Driver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; namespace NHibernate.Driver @@ -8,7 +9,7 @@ namespace NHibernate.Driver public class DB2400Driver : ReflectionBasedDriver { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// /// Thrown when the IBM.Data.DB2.iSeries assembly can not be loaded. @@ -40,4 +41,5 @@ public override bool SupportsMultipleOpenReaders get { return false; } } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/DB2Driver.cs b/src/NHibernate/Driver/DB2Driver.cs index 93c1b26bd1f..6d0b2e8ee01 100644 --- a/src/NHibernate/Driver/DB2Driver.cs +++ b/src/NHibernate/Driver/DB2Driver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; namespace NHibernate.Driver @@ -41,4 +42,5 @@ public override bool SupportsMultipleOpenReaders get { return false; } } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/DbProviderFactoryDriveConnectionCommandProvider.cs b/src/NHibernate/Driver/DbProviderFactoryDriveConnectionCommandProvider.cs index 3c3a36db553..ef2c1ab16a3 100644 --- a/src/NHibernate/Driver/DbProviderFactoryDriveConnectionCommandProvider.cs +++ b/src/NHibernate/Driver/DbProviderFactoryDriveConnectionCommandProvider.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.Common; @@ -26,4 +27,5 @@ public DbCommand CreateCommand() return dbProviderFactory.CreateCommand(); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/DotConnectMySqlDriver.cs b/src/NHibernate/Driver/DotConnectMySqlDriver.cs index 1aff3e20fb7..069534a6512 100644 --- a/src/NHibernate/Driver/DotConnectMySqlDriver.cs +++ b/src/NHibernate/Driver/DotConnectMySqlDriver.cs @@ -1,4 +1,5 @@ -namespace NHibernate.Driver +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +namespace NHibernate.Driver { /// /// Provides a database driver for dotConnect for MySQL by DevArt. @@ -53,3 +54,4 @@ public override string NamedPrefix } } } +#endif diff --git a/src/NHibernate/Driver/FirebirdClientDriver.cs b/src/NHibernate/Driver/FirebirdClientDriver.cs index 81eb9c241ee..a00b508dfbd 100644 --- a/src/NHibernate/Driver/FirebirdClientDriver.cs +++ b/src/NHibernate/Driver/FirebirdClientDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; using System.Collections.Generic; using System.Data; @@ -10,20 +11,31 @@ using NHibernate.SqlTypes; using NHibernate.Util; +#if DRIVER_PACKAGE +using FirebirdSql.Data.FirebirdClient; +#endif + namespace NHibernate.Driver { /// /// A NHibernate Driver for using the Firebird data provider located in /// FirebirdSql.Data.FirebirdClient assembly. /// +#if DRIVER_PACKAGE + public class FirebirdDriver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.Firebird NuGet package and FirebirdDriver." + + " There are also Loquacious configuration points: .Connection.ByFirebirdDriver() and .DataBaseIntegration(x => x.FirebirdDriver()).")] public class FirebirdClientDriver : ReflectionBasedDriver +#endif { private const string SELECT_CLAUSE_EXP = @"(?<=\bselect|\bwhere).*"; private const string CAST_PARAMS_EXP = @"(?]\s?|first\s?|skip\s?|between\s|between\s@\bp\w+\b\sand\s)@\bp\w+\b(?!\s?[=<>])"; - private readonly Regex _statementRegEx = new Regex(SELECT_CLAUSE_EXP, RegexOptions.IgnoreCase); - private readonly Regex _castCandidateRegEx = new Regex(CAST_PARAMS_EXP, RegexOptions.IgnoreCase); + private static readonly Regex _statementRegEx = new Regex(SELECT_CLAUSE_EXP, RegexOptions.IgnoreCase); + private static readonly Regex _castCandidateRegEx = new Regex(CAST_PARAMS_EXP, RegexOptions.IgnoreCase); private readonly FirebirdDialect _fbDialect = new FirebirdDialect(); +#if !DRIVER_PACKAGE /// /// Initializes a new instance of the class. /// @@ -37,29 +49,32 @@ public FirebirdClientDriver() "FirebirdSql.Data.FirebirdClient.FbConnection", "FirebirdSql.Data.FirebirdClient.FbCommand") { - } +#endif - public override void Configure(IDictionary settings) +#if DRIVER_PACKAGE + public override DbConnection CreateConnection() { - base.Configure(settings); - _fbDialect.Configure(settings); + return new FbConnection(); } - public override bool UseNamedPrefixInSql + public override DbCommand CreateCommand() { - get { return true; } + return new FbCommand(); } +#endif - public override bool UseNamedPrefixInParameter + public override void Configure(IDictionary settings) { - get { return true; } + base.Configure(settings); + _fbDialect.Configure(settings); } - public override string NamedPrefix - { - get { return "@"; } - } + public override bool UseNamedPrefixInSql => true; + + public override bool UseNamedPrefixInParameter => true; + + public override string NamedPrefix => "@"; protected override void InitializeParameter(DbParameter dbParam, string name, SqlType sqlType) { @@ -96,7 +111,7 @@ private string GetStatementsWithCastCandidates(string commandText) return _statementRegEx.Match(commandText).Value; } - private HashSet GetCastCandidates(string statement) + private static HashSet GetCastCandidates(string statement) { var candidates = _castCandidateRegEx @@ -128,8 +143,10 @@ private string GetFbTypeForParam(SqlType sqlType) return _fbDialect.GetCastTypeName(sqlType); } +#if !DRIVER_PACKAGE private static volatile MethodInfo _clearPool; private static volatile MethodInfo _clearAllPools; +#endif /// /// Clears the connection pool. @@ -138,6 +155,19 @@ private string GetFbTypeForParam(SqlType sqlType) /// null for clearing them all. public void ClearPool(string connectionString) { +#if DRIVER_PACKAGE + if (connectionString != null) + { + using (var clearConnection = CreateConnection()) + { + clearConnection.ConnectionString = connectionString; + FbConnection.ClearPool((FbConnection)clearConnection); + } + return; + } + + FbConnection.ClearAllPools(); +#else // In case of concurrent threads, may initialize many times. We do not care. // Members are volatile for avoiding it gets used while its constructor is not yet ended. if (_clearPool == null || _clearAllPools == null) @@ -161,10 +191,11 @@ public void ClearPool(string connectionString) } _clearAllPools.Invoke(null, Array.Empty()); +#endif } /// - /// This driver support of is not compliant and too heavily + /// This driver support of System.Transactions.Transaction is not compliant and too heavily /// restricts what can be done for NHibernate tests. See DNET-764, DNET-766 (and bonus, DNET-765). /// /// @@ -184,7 +215,7 @@ public void ClearPool(string connectionString) /// /// DNET-766 /// When auto-enlistment is disabled (Enlist=false in connection string), the driver ignores - /// calls to . They silently do + /// calls to DbConnection.EnlistTransaction(System.Transactions.Transaction). They silently do /// nothing, the Firebird connection does not get enlisted. http://tracker.firebirdsql.org/browse/DNET-766 /// /// @@ -199,3 +230,4 @@ public void ClearPool(string connectionString) public override bool SupportsEnlistmentWhenAutoEnlistmentIsDisabled => false; } } +#endif diff --git a/src/NHibernate/Driver/IfxDriver.cs b/src/NHibernate/Driver/IfxDriver.cs index 0d3c3bebbd2..4a16e6b6ade 100644 --- a/src/NHibernate/Driver/IfxDriver.cs +++ b/src/NHibernate/Driver/IfxDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE namespace NHibernate.Driver { /// @@ -35,4 +36,5 @@ public override string NamedPrefix get { return ":"; } } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/IngresDriver.cs b/src/NHibernate/Driver/IngresDriver.cs index a82932bd1ab..9a7e5f52faa 100644 --- a/src/NHibernate/Driver/IngresDriver.cs +++ b/src/NHibernate/Driver/IngresDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; namespace NHibernate.Driver @@ -26,4 +27,5 @@ public override string NamedPrefix get { return String.Empty; } } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/MySqlDataDriver.cs b/src/NHibernate/Driver/MySqlDataDriver.cs index 83e9702cfef..dd2cc3c2b99 100644 --- a/src/NHibernate/Driver/MySqlDataDriver.cs +++ b/src/NHibernate/Driver/MySqlDataDriver.cs @@ -1,4 +1,6 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; +using System.Data.Common; namespace NHibernate.Driver { @@ -16,8 +18,15 @@ namespace NHibernate.Driver /// for any updates and/or documentation regarding MySQL. /// /// +#if DRIVER_PACKAGE + public class MySqlDriver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.MySql NuGet package and MySqlDriver." + + " There are also Loquacious configuration points: .Connection.ByMySqlDriver() and .DataBaseIntegration(x => x.MySqlDriver()).")] public class MySqlDataDriver : ReflectionBasedDriver +#endif { +#if !DRIVER_PACKAGE /// /// Initializes a new instance of the class. /// @@ -31,40 +40,41 @@ public MySqlDataDriver() : base( "MySql.Data.MySqlClient.MySqlCommand") { } +#endif + +#if DRIVER_PACKAGE + public override DbConnection CreateConnection() + { + return new MySql.Data.MySqlClient.MySqlConnection(); + } + + public override DbCommand CreateCommand() + { + return new MySql.Data.MySqlClient.MySqlCommand(); + } +#endif /// /// MySql.Data uses named parameters in the sql. /// /// - MySql uses ? in the sql. - public override bool UseNamedPrefixInSql - { - get { return true; } - } + public override bool UseNamedPrefixInSql => true; /// - public override bool UseNamedPrefixInParameter - { - get { return true; } - } + public override bool UseNamedPrefixInParameter => true; /// /// MySql.Data use the ? to locate parameters in sql. /// /// ? is used to locate parameters in sql. - public override string NamedPrefix - { - get { return "?"; } - } + public override string NamedPrefix => "?"; /// /// The MySql.Data driver does NOT support more than 1 open DbDataReader /// with only 1 DbConnection. /// /// - it is not supported. - public override bool SupportsMultipleOpenReaders - { - get { return false; } - } + public override bool SupportsMultipleOpenReaders => false; /// /// MySql.Data does not support preparing of commands. @@ -74,20 +84,14 @@ public override bool SupportsMultipleOpenReaders /// With the Gamma MySql.Data provider it is throwing an exception with the /// message "Expected End of data packet" when a select command is prepared. /// - protected override bool SupportsPreparingCommands - { - get { return false; } - } + protected override bool SupportsPreparingCommands => false; public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplementor session) { return new BasicResultSetsCommand(session); } - public override bool SupportsMultipleQueries - { - get { return true; } - } + public override bool SupportsMultipleQueries => true; public override bool RequiresTimeSpanForTime => true; @@ -97,3 +101,4 @@ public override bool SupportsMultipleQueries public override DateTime MinDate => new DateTime(1000, 1, 1); } } +#endif diff --git a/src/NHibernate/Driver/NpgsqlDriver.cs b/src/NHibernate/Driver/NpgsqlDriver.cs index 1f0701c30ad..dd0ccf70272 100644 --- a/src/NHibernate/Driver/NpgsqlDriver.cs +++ b/src/NHibernate/Driver/NpgsqlDriver.cs @@ -1,3 +1,5 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +using System; using System.Data; using System.Data.Common; @@ -24,8 +26,23 @@ namespace NHibernate.Driver /// http://pgfoundry.org/projects/npgsql. ///

/// +#if DRIVER_PACKAGE + public class PostgreSqlDriver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.PostgreSql NuGet package and PostgreSqlDriver." + + " There are also Loquacious configuration points: .Connection.ByPostgreSqlDriver() and .DataBaseIntegration(x => x.PostgreSqlDriver()).")] public class NpgsqlDriver : ReflectionBasedDriver +#endif { +#if DRIVER_PACKAGE + /// + /// Initializes a new instance of the class. + /// + public PostgreSqlDriver() + { + DriverVersion = typeof(Npgsql.NpgsqlCommand).Assembly.GetName().Version; + } +#else /// /// Initializes a new instance of the class. /// @@ -39,32 +56,37 @@ public NpgsqlDriver() : base( "Npgsql.NpgsqlCommand") { } +#endif - public override bool UseNamedPrefixInSql - { - get { return true; } - } +#if DRIVER_PACKAGE + /// + /// The driver assembly version. + /// + protected Version DriverVersion { get; } - public override bool UseNamedPrefixInParameter + public override DbConnection CreateConnection() { - get { return true; } + return new Npgsql.NpgsqlConnection(); } - public override string NamedPrefix + public override DbCommand CreateCommand() { - get { return ":"; } + return new Npgsql.NpgsqlCommand(); } +#endif - public override bool SupportsMultipleOpenReaders - { - get { return false; } - } + public override bool UseNamedPrefixInSql => true; - protected override bool SupportsPreparingCommands - { - // NH-2267 Patrick Earl - get { return true; } - } + public override bool UseNamedPrefixInParameter => true; + + public override string NamedPrefix => ":"; + + public override bool SupportsMultipleOpenReaders => false; + + /// + /// NH-2267 Patrick Earl + /// + protected override bool SupportsPreparingCommands => true; public override bool SupportsNullEnlistment => false; @@ -73,10 +95,7 @@ public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplement return new BasicResultSetsCommand(session); } - public override bool SupportsMultipleQueries - { - get { return true; } - } + public override bool SupportsMultipleQueries => true; protected override void InitializeParameter(DbParameter dbParam, string name, SqlTypes.SqlType sqlType) { @@ -94,3 +113,4 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq public override bool HasDelayedDistributedTransactionCompletion => true; } } +#endif diff --git a/src/NHibernate/Driver/OdbcDriver.cs b/src/NHibernate/Driver/OdbcDriver.cs index 73ec475166d..e3213306a48 100644 --- a/src/NHibernate/Driver/OdbcDriver.cs +++ b/src/NHibernate/Driver/OdbcDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Collections.Generic; using System.Data; @@ -111,3 +112,4 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq public override DateTime MinDate => new DateTime(1753, 1, 1); } } +#endif diff --git a/src/NHibernate/Driver/OleDbDriver.cs b/src/NHibernate/Driver/OleDbDriver.cs index cb0d00c63c8..cab0d606102 100644 --- a/src/NHibernate/Driver/OleDbDriver.cs +++ b/src/NHibernate/Driver/OleDbDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.Common; using System.Data.OleDb; @@ -49,4 +50,5 @@ public override bool SupportsMultipleOpenReaders get { return false; } } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/OracleClientDriver.cs b/src/NHibernate/Driver/OracleClientDriver.cs index df302b3c1d8..13244efd436 100644 --- a/src/NHibernate/Driver/OracleClientDriver.cs +++ b/src/NHibernate/Driver/OracleClientDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System.Data; using System.Data.Common; using NHibernate.Engine.Query; @@ -60,4 +61,5 @@ protected override void OnBeforePrepare(DbCommand command) " Consider using OracleDataClientDriver instead."); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/OracleDataClientDriver.cs b/src/NHibernate/Driver/OracleDataClientDriver.cs index 891379b18c9..05b7d4282ad 100644 --- a/src/NHibernate/Driver/OracleDataClientDriver.cs +++ b/src/NHibernate/Driver/OracleDataClientDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE namespace NHibernate.Driver { /// @@ -16,4 +17,5 @@ public OracleDataClientDriver() { } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/OracleDataClientDriverBase.cs b/src/NHibernate/Driver/OracleDataClientDriverBase.cs index 93b1d135125..b0885c48830 100644 --- a/src/NHibernate/Driver/OracleDataClientDriverBase.cs +++ b/src/NHibernate/Driver/OracleDataClientDriverBase.cs @@ -1,8 +1,8 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; using System.Collections.Generic; using System.Data; using System.Data.Common; -using System.Reflection; using NHibernate.AdoNet; using NHibernate.Engine.Query; using NHibernate.SqlTypes; @@ -169,3 +169,4 @@ protected override void OnBeforePrepare(DbCommand command) System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass => typeof(OracleDataClientBatchingBatcherFactory); } } +#endif diff --git a/src/NHibernate/Driver/OracleLiteDataClientDriver.cs b/src/NHibernate/Driver/OracleLiteDataClientDriver.cs index 98497360c28..dad9e8dd79c 100644 --- a/src/NHibernate/Driver/OracleLiteDataClientDriver.cs +++ b/src/NHibernate/Driver/OracleLiteDataClientDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System.Data; using System.Data.Common; using NHibernate.AdoNet; @@ -63,4 +64,5 @@ System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass #endregion } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/OracleManagedDataClientDriver.cs b/src/NHibernate/Driver/OracleManagedDataClientDriver.cs index 247a84dfaff..e19c18e1c19 100644 --- a/src/NHibernate/Driver/OracleManagedDataClientDriver.cs +++ b/src/NHibernate/Driver/OracleManagedDataClientDriver.cs @@ -1,8 +1,13 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +using System; + namespace NHibernate.Driver { /// /// A NHibernate Driver for using the Oracle.ManagedDataAccess DataProvider /// + [Obsolete("Use NHibernate.Driver.Oracle.Managed NuGet package and OracleManagedDriver." + + " There are also Loquacious configuration points: .Connection.ByOracleManagedDriver() and .DataBaseIntegration(x => x.OracleManagedDriver()).")] public class OracleManagedDataClientDriver : OracleDataClientDriverBase { /// @@ -19,3 +24,4 @@ public OracleManagedDataClientDriver() public override bool HasDelayedDistributedTransactionCompletion => true; } } +#endif diff --git a/src/NHibernate/Driver/ReflectionBasedDriver.cs b/src/NHibernate/Driver/ReflectionBasedDriver.cs index e606ee551e0..7cfbefa2496 100644 --- a/src/NHibernate/Driver/ReflectionBasedDriver.cs +++ b/src/NHibernate/Driver/ReflectionBasedDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.Common; using NHibernate.Util; @@ -71,4 +72,5 @@ public override DbCommand CreateCommand() return connectionCommandProvider.CreateCommand(); } } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/ReflectionDriveConnectionCommandProvider.cs b/src/NHibernate/Driver/ReflectionDriveConnectionCommandProvider.cs index 1e77e779e23..08fe5f42a79 100644 --- a/src/NHibernate/Driver/ReflectionDriveConnectionCommandProvider.cs +++ b/src/NHibernate/Driver/ReflectionDriveConnectionCommandProvider.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 using System; using System.Data.Common; using Environment = NHibernate.Cfg.Environment; @@ -37,4 +38,5 @@ public DbCommand CreateCommand() #endregion } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/SQLite20Driver.cs b/src/NHibernate/Driver/SQLite20Driver.cs index 4d840878490..b738a303d2b 100644 --- a/src/NHibernate/Driver/SQLite20Driver.cs +++ b/src/NHibernate/Driver/SQLite20Driver.cs @@ -1,3 +1,5 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +using System; using System.Data; using System.Data.Common; @@ -19,62 +21,68 @@ namespace NHibernate.Driver /// Please check https://www.sqlite.org/ for more information regarding SQLite. /// /// +#if DRIVER_PACKAGE + public class SQLiteDriver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.SQlLite NuGet package and SQLiteDriver." + + " There are also Loquacious configuration points: .Connection.BySQLiteDriver() and .DataBaseIntegration(x => x.SQLiteDriver()).")] public class SQLite20Driver : ReflectionBasedDriver +#endif { +#if DRIVER_PACKAGE + public SQLiteDriver() + {} +#else /// /// Initializes a new instance of . /// /// /// Thrown when the SQLite.NET assembly can not be loaded. /// - public SQLite20Driver() : base( - "System.Data.SQLite", - "System.Data.SQLite", - "System.Data.SQLite.SQLiteConnection", - "System.Data.SQLite.SQLiteCommand") + public SQLite20Driver() + : base( + "System.Data.SQLite", + "System.Data.SQLite", + "System.Data.SQLite.SQLiteConnection", + "System.Data.SQLite.SQLiteCommand") { } +#endif - public override DbConnection CreateConnection() - { - var connection = base.CreateConnection(); - connection.StateChange += Connection_StateChange; - return connection; - } - - private static void Connection_StateChange(object sender, StateChangeEventArgs e) - { - if ((e.OriginalState == ConnectionState.Broken || e.OriginalState == ConnectionState.Closed || e.OriginalState == ConnectionState.Connecting) && - e.CurrentState == ConnectionState.Open) - { - var connection = (DbConnection)sender; - using (var command = connection.CreateCommand()) - { - // Activated foreign keys if supported by SQLite. Unknown pragmas are ignored. - command.CommandText = "PRAGMA foreign_keys = ON"; - command.ExecuteNonQuery(); - } - } - } - - public override bool UseNamedPrefixInSql +#if DRIVER_PACKAGE + public override DbConnection CreateConnection() { - get { return true; } + var connection = new System.Data.SQLite.SQLiteConnection(); + connection.StateChange += Connection_StateChange; + return connection; } - public override bool UseNamedPrefixInParameter + public override DbCommand CreateCommand() { - get { return true; } + return new System.Data.SQLite.SQLiteCommand(); } - - public override string NamedPrefix +#else + public override DbConnection CreateConnection() { - get { return "@"; } + var connection = base.CreateConnection(); + connection.StateChange += Connection_StateChange; + return connection; } +#endif - public override bool SupportsMultipleOpenReaders + private static void Connection_StateChange(object sender, StateChangeEventArgs e) { - get { return false; } + if ((e.OriginalState == ConnectionState.Broken || e.OriginalState == ConnectionState.Closed || e.OriginalState == ConnectionState.Connecting) && + e.CurrentState == ConnectionState.Open) + { + var connection = (DbConnection)sender; + using (var command = connection.CreateCommand()) + { + // Activated foreign keys if supported by SQLite. Unknown pragmas are ignored. + command.CommandText = "PRAGMA foreign_keys = ON"; + command.ExecuteNonQuery(); + } + } } public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplementor session) @@ -82,13 +90,19 @@ public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplement return new BasicResultSetsCommand(session); } - public override bool SupportsMultipleQueries - { - get { return true; } - } - + public override bool UseNamedPrefixInSql => true; + + public override bool UseNamedPrefixInParameter => true; + + public override string NamedPrefix => "@"; + + public override bool SupportsMultipleOpenReaders => false; + + public override bool SupportsMultipleQueries => true; + public override bool SupportsNullEnlistment => false; public override bool HasDelayedDistributedTransactionCompletion => true; } } +#endif diff --git a/src/NHibernate/Driver/Sql2008ClientDriver.cs b/src/NHibernate/Driver/Sql2008ClientDriver.cs index d6ba53d8627..9c8c124629c 100644 --- a/src/NHibernate/Driver/Sql2008ClientDriver.cs +++ b/src/NHibernate/Driver/Sql2008ClientDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; using System.Data; using System.Data.Common; @@ -5,7 +6,13 @@ namespace NHibernate.Driver { +#if DRIVER_PACKAGE + public class SqlServer2008Driver : SqlServer2000Driver +#else + [Obsolete("Use NHibernate.Driver.SqlServer NuGet package and SqlServer2008Driver." + + " There are also Loquacious configuration points: .Connection.BySqlServer2008Driver() and .DataBaseIntegration(x => x.SqlServer2008Driver()).")] public class Sql2008ClientDriver : SqlClientDriver +#endif { const byte MaxTime = 5; @@ -30,3 +37,4 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq public override DateTime MinDate => DateTime.MinValue; } } +#endif diff --git a/src/NHibernate/Driver/SqlClientDriver.cs b/src/NHibernate/Driver/SqlClientDriver.cs index a4101d6ba9d..5d21a80085f 100644 --- a/src/NHibernate/Driver/SqlClientDriver.cs +++ b/src/NHibernate/Driver/SqlClientDriver.cs @@ -1,9 +1,11 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using NHibernate.AdoNet; +using NHibernate.Dialect; using NHibernate.Engine; using NHibernate.SqlTypes; @@ -12,15 +14,40 @@ namespace NHibernate.Driver /// /// A NHibernate Driver for using the SqlClient DataProvider /// - public class SqlClientDriver : DriverBase, IEmbeddedBatcherFactoryProvider +#if DRIVER_PACKAGE + public class SqlServer2000Driver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.SqlServer NuGet package and SqlServer2000Driver." + + " There are also Loquacious configuration points: .Connection.BySqlServer2000Driver() and .DataBaseIntegration(x => x.SqlServer2000Driver()).")] + public class SqlClientDriver : DriverBase +#endif +#if !NETSTANDARD2_0 + , IEmbeddedBatcherFactoryProvider +#endif { + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForAnsiClob")] public const int MaxSizeForAnsiClob = 2147483647; // int.MaxValue + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForClob")] public const int MaxSizeForClob = 1073741823; // int.MaxValue / 2 + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForBlob")] public const int MaxSizeForBlob = 2147483647; // int.MaxValue - //http://stackoverflow.com/a/7264795/259946 + + ///http://stackoverflow.com/a/7264795/259946 + // Since v5.1 + [Obsolete("Use MsSql2005Dialect.MaxSizeForXml")] public const int MaxSizeForXml = 2147483647; // int.MaxValue + + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForLengthLimitedAnsiString")] public const int MaxSizeForLengthLimitedAnsiString = 8000; + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForLengthLimitedString")] public const int MaxSizeForLengthLimitedString = 4000; + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxSizeForLengthLimitedBinary")] public const int MaxSizeForLengthLimitedBinary = 8000; // Since v5.1 [Obsolete("This member has no more usages and will be removed in a future version")] @@ -28,7 +55,11 @@ public class SqlClientDriver : DriverBase, IEmbeddedBatcherFactoryProvider // Since v5.1 [Obsolete("This member has no more usages and will be removed in a future version")] public const byte MaxScale = 5; + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxDateTime2")] public const byte MaxDateTime2 = 8; + // Since v5.1 + [Obsolete("Use MsSql2000Dialect.MaxDateTimeOffset")] public const byte MaxDateTimeOffset = 10; private Dialect.Dialect _dialect; @@ -42,7 +73,7 @@ public override void Configure(IDictionary settings) /// /// Creates an uninitialized object for - /// the SqlClientDriver. + /// the SQL-Server driver. /// /// An unitialized object. public override DbConnection CreateConnection() @@ -52,7 +83,7 @@ public override DbConnection CreateConnection() /// /// Creates an uninitialized object for - /// the SqlClientDriver. + /// the SQL-Server driver. /// /// An unitialized object. public override DbCommand CreateCommand() @@ -117,10 +148,10 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq { case DbType.AnsiString: case DbType.AnsiStringFixedLength: - dbParam.Size = IsAnsiText(dbParam, sqlType) ? MaxSizeForAnsiClob : MaxSizeForLengthLimitedAnsiString; + dbParam.Size = IsAnsiText(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForAnsiClob : MsSql2000Dialect.MaxSizeForLengthLimitedAnsiString; break; case DbType.Binary: - dbParam.Size = IsBlob(dbParam, sqlType) ? MaxSizeForBlob : MaxSizeForLengthLimitedBinary; + dbParam.Size = IsBlob(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForBlob : MsSql2000Dialect.MaxSizeForLengthLimitedBinary; break; case DbType.Decimal: if (_dialect == null) @@ -130,16 +161,16 @@ protected override void InitializeParameter(DbParameter dbParam, string name, Sq break; case DbType.String: case DbType.StringFixedLength: - dbParam.Size = IsText(dbParam, sqlType) ? MaxSizeForClob : MaxSizeForLengthLimitedString; + dbParam.Size = IsText(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForClob : MsSql2000Dialect.MaxSizeForLengthLimitedString; break; case DbType.DateTime2: - dbParam.Size = MaxDateTime2; + dbParam.Size = MsSql2000Dialect.MaxDateTime2; break; case DbType.DateTimeOffset: - dbParam.Size = MaxDateTimeOffset; + dbParam.Size = MsSql2000Dialect.MaxDateTimeOffset; break; case DbType.Xml: - dbParam.Size = MaxSizeForXml; + dbParam.Size = MsSql2005Dialect.MaxSizeForXml; break; } @@ -181,10 +212,10 @@ protected static void SetDefaultParameterSize(DbParameter dbParam, SqlType sqlTy { case DbType.AnsiString: case DbType.AnsiStringFixedLength: - dbParam.Size = IsAnsiText(dbParam, sqlType) ? MaxSizeForAnsiClob : MaxSizeForLengthLimitedAnsiString; + dbParam.Size = IsAnsiText(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForAnsiClob : MsSql2000Dialect.MaxSizeForLengthLimitedAnsiString; break; case DbType.Binary: - dbParam.Size = IsBlob(dbParam, sqlType) ? MaxSizeForBlob : MaxSizeForLengthLimitedBinary; + dbParam.Size = IsBlob(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForBlob : MsSql2000Dialect.MaxSizeForLengthLimitedBinary; break; case DbType.Decimal: dbParam.Precision = MaxPrecision; @@ -192,16 +223,16 @@ protected static void SetDefaultParameterSize(DbParameter dbParam, SqlType sqlTy break; case DbType.String: case DbType.StringFixedLength: - dbParam.Size = IsText(dbParam, sqlType) ? MaxSizeForClob : MaxSizeForLengthLimitedString; + dbParam.Size = IsText(dbParam, sqlType) ? MsSql2000Dialect.MaxSizeForClob : MsSql2000Dialect.MaxSizeForLengthLimitedString; break; case DbType.DateTime2: - dbParam.Size = MaxDateTime2; + dbParam.Size = MsSql2000Dialect.MaxDateTime2; break; case DbType.DateTimeOffset: - dbParam.Size = MaxDateTimeOffset; + dbParam.Size = MsSql2000Dialect.MaxDateTimeOffset; break; case DbType.Xml: - dbParam.Size = MaxSizeForXml; + dbParam.Size = MsSql2005Dialect.MaxSizeForXml; break; } } @@ -214,7 +245,7 @@ protected static void SetDefaultParameterSize(DbParameter dbParam, SqlType sqlTy /// True, if the parameter should be interpreted as a Clob, otherwise False protected static bool IsAnsiText(DbParameter dbParam, SqlType sqlType) { - return ((DbType.AnsiString == dbParam.DbType || DbType.AnsiStringFixedLength == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MaxSizeForLengthLimitedAnsiString)); + return ((DbType.AnsiString == dbParam.DbType || DbType.AnsiStringFixedLength == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MsSql2000Dialect.MaxSizeForLengthLimitedAnsiString)); } /// @@ -225,7 +256,7 @@ protected static bool IsAnsiText(DbParameter dbParam, SqlType sqlType) /// True, if the parameter should be interpreted as a Clob, otherwise False protected static bool IsText(DbParameter dbParam, SqlType sqlType) { - return (sqlType is StringClobSqlType) || ((DbType.String == dbParam.DbType || DbType.StringFixedLength == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MaxSizeForLengthLimitedString)); + return (sqlType is StringClobSqlType) || ((DbType.String == dbParam.DbType || DbType.StringFixedLength == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MsSql2000Dialect.MaxSizeForLengthLimitedString)); } /// @@ -236,9 +267,10 @@ protected static bool IsText(DbParameter dbParam, SqlType sqlType) /// True, if the parameter should be interpreted as a Blob, otherwise False protected static bool IsBlob(DbParameter dbParam, SqlType sqlType) { - return (sqlType is BinaryBlobSqlType) || ((DbType.Binary == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MaxSizeForLengthLimitedBinary)); + return (sqlType is BinaryBlobSqlType) || ((DbType.Binary == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MsSql2000Dialect.MaxSizeForLengthLimitedBinary)); } +#if !NETSTANDARD2_0 #region IEmbeddedBatcherFactoryProvider Members System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass @@ -247,6 +279,7 @@ System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass } #endregion +#endif public override IResultSetsCommand GetResultSetsCommand(ISessionImplementor session) { @@ -268,3 +301,4 @@ public override bool SupportsMultipleQueries public override DateTime MinDate => new DateTime(1753, 1, 1); } } +#endif diff --git a/src/NHibernate/Driver/SqlServerCeDriver.cs b/src/NHibernate/Driver/SqlServerCeDriver.cs index 4610cb47269..8604b99d243 100644 --- a/src/NHibernate/Driver/SqlServerCeDriver.cs +++ b/src/NHibernate/Driver/SqlServerCeDriver.cs @@ -1,3 +1,4 @@ +#if !NETSTANDARD2_0 || DRIVER_PACKAGE using System; using System.Collections.Generic; using System.Data; @@ -10,8 +11,15 @@ namespace NHibernate.Driver /// /// A NHibernate driver for Microsoft SQL Server CE data provider /// +#if DRIVER_PACKAGE + public class SqlServerCompactDriver : DriverBase +#else + [Obsolete("Use NHibernate.Driver.SqlServer.Compact NuGet package and SqlServerCompactDriver." + + " There are also Loquacious configuration points: .Connection.BySqlServerCompactDriver() and .DataBaseIntegration(x => x.SqlServerCompactDriver()).")] public class SqlServerCeDriver : ReflectionBasedDriver +#endif { +#if !DRIVER_PACKAGE /// /// Initializes a new instance of the class. /// @@ -22,7 +30,19 @@ public SqlServerCeDriver() "System.Data.SqlServerCe.SqlCeCommand") { } +#endif +#if DRIVER_PACKAGE + public override DbConnection CreateConnection() + { + return new System.Data.SqlServerCe.SqlCeConnection(); + } + + public override DbCommand CreateCommand() + { + return new System.Data.SqlServerCe.SqlCeCommand(); + } +#else private PropertyInfo dbParamSqlDbTypeProperty; public override void Configure(IDictionary settings) @@ -35,6 +55,7 @@ public override void Configure(IDictionary settings) dbParamSqlDbTypeProperty = dbParam.GetType().GetProperty("SqlDbType"); } } +#endif /// /// MsSql requires the use of a Named Prefix in the SQL statement. @@ -42,10 +63,7 @@ public override void Configure(IDictionary settings) /// /// because MsSql uses "@". /// - public override bool UseNamedPrefixInSql - { - get { return true; } - } + public override bool UseNamedPrefixInSql => true; /// /// MsSql requires the use of a Named Prefix in the Parameter. @@ -53,10 +71,7 @@ public override bool UseNamedPrefixInSql /// /// because MsSql uses "@". /// - public override bool UseNamedPrefixInParameter - { - get { return true; } - } + public override bool UseNamedPrefixInParameter => true; /// /// The Named Prefix for parameters. @@ -64,10 +79,7 @@ public override bool UseNamedPrefixInParameter /// /// Sql Server uses "@". /// - public override string NamedPrefix - { - get { return "@"; } - } + public override string NamedPrefix => "@"; /// /// The SqlClient driver does NOT support more than 1 open DbDataReader @@ -79,10 +91,7 @@ public override string NamedPrefix /// attempted to be Opened. When Yukon comes out a new Driver will be /// created for Yukon because it is supposed to support it. /// - public override bool SupportsMultipleOpenReaders - { - get { return false; } - } + public override bool SupportsMultipleOpenReaders => false; protected override void SetCommandTimeout(DbCommand cmd) { @@ -119,6 +128,17 @@ private static SqlType AdjustSqlType(SqlType sqlType) private void AdjustDbParamTypeForLargeObjects(DbParameter dbParam, SqlType sqlType) { +#if DRIVER_PACKAGE + var sqlCeParam = (System.Data.SqlServerCe.SqlCeParameter) dbParam; + if (sqlType is BinaryBlobSqlType) + { + sqlCeParam.SqlDbType = SqlDbType.Image; + } + else if (sqlType is StringClobSqlType) + { + sqlCeParam.SqlDbType = SqlDbType.NText; + } +#else if (sqlType is BinaryBlobSqlType) { dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.Image, null); @@ -127,13 +147,14 @@ private void AdjustDbParamTypeForLargeObjects(DbParameter dbParam, SqlType sqlTy { dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.NText, null); } +#endif } public override bool SupportsNullEnlistment => false; /// /// . Enlistment is completely disabled when auto-enlistment is disabled. - /// does nothing in + /// DbConnection.EnlistTransaction(System.Transactions.Transaction) does nothing in /// this case. /// public override bool SupportsEnlistmentWhenAutoEnlistmentIsDisabled => false; @@ -142,3 +163,4 @@ private void AdjustDbParamTypeForLargeObjects(DbParameter dbParam, SqlType sqlTy public override DateTime MinDate => new DateTime(1753, 1, 1); } } +#endif diff --git a/src/NHibernate/Driver/SybaseAsaClientDriver.cs b/src/NHibernate/Driver/SybaseAsaClientDriver.cs index 99aaf26e3ec..b86fe6c50c1 100644 --- a/src/NHibernate/Driver/SybaseAsaClientDriver.cs +++ b/src/NHibernate/Driver/SybaseAsaClientDriver.cs @@ -1,4 +1,5 @@ -using System; +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +using System; namespace NHibernate.Driver { @@ -35,4 +36,5 @@ public override string NamedPrefix public override bool RequiresTimeSpanForTime => true; } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/SybaseAseClientDriver.cs b/src/NHibernate/Driver/SybaseAseClientDriver.cs index eb73208ec1f..894da8c3764 100644 --- a/src/NHibernate/Driver/SybaseAseClientDriver.cs +++ b/src/NHibernate/Driver/SybaseAseClientDriver.cs @@ -1,4 +1,5 @@ -using System; +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +using System; namespace NHibernate.Driver { @@ -34,3 +35,4 @@ public override bool UseNamedPrefixInSql } } } +#endif diff --git a/src/NHibernate/Driver/SybaseSQLAnywhereDotNet4Driver.cs b/src/NHibernate/Driver/SybaseSQLAnywhereDotNet4Driver.cs index a7aae90d27d..4121e2e5bd3 100644 --- a/src/NHibernate/Driver/SybaseSQLAnywhereDotNet4Driver.cs +++ b/src/NHibernate/Driver/SybaseSQLAnywhereDotNet4Driver.cs @@ -1,4 +1,5 @@ -namespace NHibernate.Driver +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +namespace NHibernate.Driver { /// /// SQL Dialect for SQL Anywhere 12 - for the NHibernate 3.2.0 distribution @@ -58,4 +59,5 @@ public override string NamedPrefix public override bool RequiresTimeSpanForTime => true; } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Driver/SybaseSQLAnywhereDriver.cs b/src/NHibernate/Driver/SybaseSQLAnywhereDriver.cs index 94fd2ee5111..a662f94184f 100644 --- a/src/NHibernate/Driver/SybaseSQLAnywhereDriver.cs +++ b/src/NHibernate/Driver/SybaseSQLAnywhereDriver.cs @@ -1,4 +1,5 @@ -namespace NHibernate.Driver +#if !NETSTANDARD2_0 || DRIVER_PACKAGE +namespace NHibernate.Driver { /// /// The SybaseSQLAnywhereDriver Driver provides a database driver for Sybase SQL Anywhere 10 and above @@ -33,4 +34,5 @@ public override string NamedPrefix public override bool RequiresTimeSpanForTime => true; } -} \ No newline at end of file +} +#endif diff --git a/src/NHibernate/Engine/ActionQueue.cs b/src/NHibernate/Engine/ActionQueue.cs index d4d8344000a..e3a339b3dc5 100644 --- a/src/NHibernate/Engine/ActionQueue.cs +++ b/src/NHibernate/Engine/ActionQueue.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -195,8 +196,23 @@ private void InnerExecute(IExecutable executable) private void RegisterCleanupActions(IExecutable executable) { - beforeTransactionProcesses.Register(executable.BeforeTransactionCompletionProcess); - afterTransactionProcesses.Register(executable.AfterTransactionCompletionProcess); + BeforeTransactionCompletionProcessDelegate beforeTransactionDelegate = executable.BeforeTransactionCompletionProcess; + AfterTransactionCompletionProcessDelegate afterTransactionDelegate = executable.AfterTransactionCompletionProcess; + +#if NETSTANDARD2_0 + if (beforeTransactionDelegate != null) + { + log.Warn(".NET Core cannot serialize BeforeTransactionCompletionProcess."); + } + + if (afterTransactionDelegate != null) + { + log.Warn(".NET Core cannot serialize AfterTransactionCompletionProcess."); + } +#endif + + beforeTransactionProcesses.Register(beforeTransactionDelegate); + afterTransactionProcesses.Register(afterTransactionDelegate); } /// @@ -452,13 +468,27 @@ public override string ToString() } [Serializable] - private class BeforeTransactionCompletionProcessQueue + private sealed class BeforeTransactionCompletionProcessQueue : ISerializable { - private List processes = new List(); + // TODO: Not serializable in .NET Core + private readonly List _processes = new List(); + + public bool HasActions => _processes.Count > 0; + + public BeforeTransactionCompletionProcessQueue() + { + } - public bool HasActions + private BeforeTransactionCompletionProcessQueue(SerializationInfo info, StreamingContext context) { - get { return processes.Count > 0; } + } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { +#if NETSTANDARD2_0 + if (HasActions) + throw new NotImplementedException("Serializing delegates is not supported on this platform."); +#endif } public void Register(BeforeTransactionCompletionProcessDelegate process) @@ -467,17 +497,17 @@ public void Register(BeforeTransactionCompletionProcessDelegate process) { return; } - processes.Add(process); + _processes.Add(process); } public void BeforeTransactionCompletion() { - int size = processes.Count; + int size = _processes.Count; for (int i = 0; i < size; i++) { try { - BeforeTransactionCompletionProcessDelegate process = processes[i]; + BeforeTransactionCompletionProcessDelegate process = _processes[i]; process(); } catch (HibernateException) @@ -489,18 +519,32 @@ public void BeforeTransactionCompletion() throw new AssertionFailure("Unable to perform BeforeTransactionCompletion callback", e); } } - processes.Clear(); + _processes.Clear(); } } [Serializable] - private class AfterTransactionCompletionProcessQueue + private sealed class AfterTransactionCompletionProcessQueue : ISerializable { - private List processes = new List(InitQueueListSize * 3); + // TODO: Not serializable in .NET Core + private readonly List _processes = new List(InitQueueListSize * 3); + + public bool HasActions => _processes.Count > 0; + + public AfterTransactionCompletionProcessQueue() + { + } + + private AfterTransactionCompletionProcessQueue(SerializationInfo info, StreamingContext context) + { + } - public bool HasActions + public void GetObjectData(SerializationInfo info, StreamingContext context) { - get { return processes.Count > 0; } +#if NETSTANDARD2_0 + if (HasActions) + throw new NotImplementedException("Serializing delegates is not supported on this platform."); +#endif } public void Register(AfterTransactionCompletionProcessDelegate process) @@ -509,18 +553,18 @@ public void Register(AfterTransactionCompletionProcessDelegate process) { return; } - processes.Add(process); + _processes.Add(process); } public void AfterTransactionCompletion(bool success) { - int size = processes.Count; + int size = _processes.Count; for (int i = 0; i < size; i++) { try { - AfterTransactionCompletionProcessDelegate process = processes[i]; + AfterTransactionCompletionProcessDelegate process = _processes[i]; process(success); } catch (CacheException e) @@ -533,7 +577,7 @@ public void AfterTransactionCompletion(bool success) throw new AssertionFailure("Unable to perform AfterTransactionCompletion callback", e); } } - processes.Clear(); + _processes.Clear(); } } diff --git a/src/NHibernate/Engine/Query/QueryPlanCache.cs b/src/NHibernate/Engine/Query/QueryPlanCache.cs index 9b817c5eb87..2d501724bb8 100644 --- a/src/NHibernate/Engine/Query/QueryPlanCache.cs +++ b/src/NHibernate/Engine/Query/QueryPlanCache.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.Serialization; using NHibernate.Engine.Query.Sql; using NHibernate.Hql; using NHibernate.Linq; @@ -184,19 +185,16 @@ private class HQLQueryPlanKey : IEquatable private readonly bool shallow; private readonly HashSet filterNames; private readonly int hashCode; - private readonly System.Type queryTypeDiscriminator; - - public HQLQueryPlanKey(string query, bool shallow, IDictionary enabledFilters) - : this(typeof(object), query, shallow, enabledFilters) - { - } + [NonSerialized] + private System.Type queryTypeDiscriminator; + private SerializableSystemType _serializableQueryTypeDiscriminator; public HQLQueryPlanKey(IQueryExpression queryExpression, bool shallow, IDictionary enabledFilters) : this(queryExpression.GetType(), queryExpression.Key, shallow, enabledFilters) { } - protected HQLQueryPlanKey(System.Type queryTypeDiscriminator, string query, bool shallow, IDictionary enabledFilters) + private HQLQueryPlanKey(System.Type queryTypeDiscriminator, string query, bool shallow, IDictionary enabledFilters) { this.queryTypeDiscriminator = queryTypeDiscriminator; this.query = query; @@ -221,6 +219,18 @@ protected HQLQueryPlanKey(System.Type queryTypeDiscriminator, string query, bool } } + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableQueryTypeDiscriminator = SerializableSystemType.Wrap(queryTypeDiscriminator); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + queryTypeDiscriminator = _serializableQueryTypeDiscriminator?.GetSystemType(); + } + public override bool Equals(object obj) { return this == obj || Equals(obj as HQLQueryPlanKey); diff --git a/src/NHibernate/Impl/CriteriaImpl.cs b/src/NHibernate/Impl/CriteriaImpl.cs index 5e3bbb60d88..333c89ab553 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.Runtime.Serialization; using System.Text; using System.Threading; using NHibernate.Criterion; @@ -17,7 +18,9 @@ namespace NHibernate.Impl [Serializable] public partial class CriteriaImpl : ICriteria { - private readonly System.Type persistentClass; + [NonSerialized] + private System.Type persistentClass; + private SerializableSystemType _serializablePersistentClass; private readonly List criteria = new List(); private readonly List orderEntries = new List(10); private readonly Dictionary fetchModes = new Dictionary(); @@ -72,6 +75,18 @@ public CriteriaImpl(string entityOrClassName, string alias, ISessionImplementor subcriteriaByAlias[alias] = this; } + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializablePersistentClass = SerializableSystemType.Wrap(persistentClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + persistentClass = _serializablePersistentClass?.GetSystemType(); + } + public ISessionImplementor Session { get { return session; } diff --git a/src/NHibernate/Impl/SessionFactoryImpl.cs b/src/NHibernate/Impl/SessionFactoryImpl.cs index c66bf78baa4..a079e6bff16 100644 --- a/src/NHibernate/Impl/SessionFactoryImpl.cs +++ b/src/NHibernate/Impl/SessionFactoryImpl.cs @@ -1227,12 +1227,14 @@ private ICurrentSessionContext BuildCurrentSessionContext() return null; case "async_local": return new AsyncLocalSessionContext(this); +#if !NETSTANDARD2_0 case "call": return new CallSessionContext(this); - case "thread_static": - return new ThreadStaticSessionContext(this); case "web": return new WebSessionContext(this); +#endif + case "thread_static": + return new ThreadStaticSessionContext(this); case "wcf_operation": return new WcfOperationSessionContext(this); } diff --git a/src/NHibernate/InstantiationException.cs b/src/NHibernate/InstantiationException.cs index 08496bffdc2..5b2c9cccdf2 100644 --- a/src/NHibernate/InstantiationException.cs +++ b/src/NHibernate/InstantiationException.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +using NHibernate.Util; namespace NHibernate { @@ -11,15 +11,13 @@ namespace NHibernate [Serializable] public class InstantiationException : HibernateException { - private readonly System.Type type; + [NonSerialized] + private readonly System.Type _type; public InstantiationException(string message, System.Type type) : base(message) { - if (type == null) - throw new ArgumentNullException("type"); - - this.type = type; + _type = type ?? throw new ArgumentNullException(nameof(type)); } /// @@ -35,19 +33,13 @@ public InstantiationException(string message, System.Type type) public InstantiationException(string message, Exception innerException, System.Type type) : base(message, innerException) { - if (type == null) - throw new ArgumentNullException("type"); - - this.type = type; + _type = type ?? throw new ArgumentNullException(nameof(type)); } /// /// Gets the that NHibernate was trying to instantiate. /// - public System.Type PersistentType - { - get { return type; } - } + public System.Type PersistentType => _type; /// /// Gets a message that describes the current . @@ -56,10 +48,7 @@ public System.Type PersistentType /// The error message that explains the reason for this exception and the Type that /// was trying to be instantiated. /// - public override string Message - { - get { return base.Message + (type == null ? "" : type.FullName); } - } + public override string Message => base.Message + (_type == null ? "" : _type.FullName); #region ISerializable Members @@ -76,7 +65,7 @@ public override string Message /// protected InstantiationException(SerializationInfo info, StreamingContext context) : base(info, context) { - this.type = info.GetValue("type", typeof(System.Type)) as System.Type; + _type = info.GetValue("type"); } /// @@ -94,7 +83,7 @@ protected InstantiationException(SerializationInfo info, StreamingContext contex public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("type", type, typeof(System.Type)); + info.AddValue("type", ObjectReferenceSystemType.Wrap(_type, true)); } #endregion diff --git a/src/NHibernate/Intercept/AbstractFieldInterceptor.cs b/src/NHibernate/Intercept/AbstractFieldInterceptor.cs index 1a170d921d3..76374076801 100644 --- a/src/NHibernate/Intercept/AbstractFieldInterceptor.cs +++ b/src/NHibernate/Intercept/AbstractFieldInterceptor.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.Proxy; +using NHibernate.Util; namespace NHibernate.Intercept { @@ -16,7 +18,9 @@ public abstract class AbstractFieldInterceptor : IFieldInterceptor private readonly ISet unwrapProxyFieldNames; private readonly HashSet loadedUnwrapProxyFieldNames = new HashSet(); private readonly string entityName; - private readonly System.Type mappedClass; + [NonSerialized] + private System.Type mappedClass; + private SerializableSystemType _serializableMappedClass; [NonSerialized] private bool initializing; @@ -31,6 +35,18 @@ protected internal AbstractFieldInterceptor(ISessionImplementor session, ISet(s => s.Trim()), - ReflectHelper.GetMethodDefinition(s => s.Trim('a')), - ReflectHelper.GetMethodDefinition(s => s.TrimStart('a')), - ReflectHelper.GetMethodDefinition(s => s.TrimEnd('a')) - }; + SupportedMethods = typeof(string).GetMethods().Where(x => new[] { "Trim", "TrimStart", "TrimEnd" }.Contains(x.Name)).ToArray(); } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -262,8 +257,20 @@ public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, string trimChars = ""; if (method.GetParameters().Length > 0) - foreach (char c in (char[])((ConstantExpression)arguments[0]).Value) - trimChars += c; + { + object argumentValue = ((ConstantExpression)arguments[0]).Value; + if (argumentValue is char) + { + trimChars += (char)argumentValue; + } + else + { + foreach (char c in (char[])argumentValue) + { + trimChars += c; + } + } + } if (trimChars == "") diff --git a/src/NHibernate/Mapping/Array.cs b/src/NHibernate/Mapping/Array.cs index cb5650bf8bc..75aa80e3997 100644 --- a/src/NHibernate/Mapping/Array.cs +++ b/src/NHibernate/Mapping/Array.cs @@ -10,7 +10,9 @@ namespace NHibernate.Mapping [Serializable] public class Array : List { + [NonSerialized] private System.Type elementClass; + private string elementClassName; public Array(PersistentClass owner) : base(owner) @@ -21,23 +23,22 @@ public System.Type ElementClass { get { - if (elementClass == null) + if (elementClass != null) return elementClass; + + if (elementClassName == null) + { + IType elementType = Element.Type; + elementClass = IsPrimitiveArray ? ((PrimitiveType) elementType).PrimitiveClass : elementType.ReturnedClass; + } + else { - if (elementClassName == null) + try { - IType elementType = Element.Type; - elementClass = IsPrimitiveArray ? ((PrimitiveType) elementType).PrimitiveClass : elementType.ReturnedClass; + elementClass = ReflectHelper.ClassForName(elementClassName); } - else + catch (Exception cnfe) { - try - { - elementClass = ReflectHelper.ClassForName(elementClassName); - } - catch (Exception cnfe) - { - throw new MappingException(cnfe); - } + throw new MappingException(cnfe); } } return elementClass; @@ -68,4 +69,4 @@ public string ElementClassName } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/Collection.cs b/src/NHibernate/Mapping/Collection.cs index c1b6d1eda12..daff9efb510 100644 --- a/src/NHibernate/Mapping/Collection.cs +++ b/src/NHibernate/Mapping/Collection.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.Type; @@ -42,7 +44,9 @@ public abstract class Collection : IFetchable, IValue, IFilterable private bool orphanDelete; private int batchSize = -1; private FetchMode fetchMode; + [NonSerialized] private System.Type collectionPersisterClass; + private SerializableSystemType _serializableCollectionPersisterClass; private string referencedPropertyName; private string typeName; @@ -65,7 +69,9 @@ public abstract class Collection : IFetchable, IValue, IFilterable private ExecuteUpdateResultCheckStyle deleteAllCheckStyle; private bool isGeneric; + [NonSerialized] private System.Type[] genericArguments; + private SerializableSystemType[] _serializableGenericArguments; private readonly Dictionary filters = new Dictionary(); private readonly Dictionary manyToManyFilters = new Dictionary(); private bool subselectLoadable; @@ -81,6 +87,20 @@ protected Collection(PersistentClass owner) this.owner = owner; } + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableCollectionPersisterClass = SerializableSystemType.Wrap(collectionPersisterClass); + _serializableGenericArguments = genericArguments?.Select(SerializableSystemType.Wrap).ToArray(); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + collectionPersisterClass = _serializableCollectionPersisterClass?.GetSystemType(); + genericArguments = _serializableGenericArguments?.Select(sst => sst?.GetSystemType()).ToArray(); + } + public int ColumnSpan { get { return 0; } diff --git a/src/NHibernate/Mapping/Component.cs b/src/NHibernate/Mapping/Component.cs index 3a4793d6458..2b6441b3772 100644 --- a/src/NHibernate/Mapping/Component.cs +++ b/src/NHibernate/Mapping/Component.cs @@ -14,7 +14,10 @@ namespace NHibernate.Mapping public class Component : SimpleValue, IMetaAttributable { private readonly List properties = new List(); + + [NonSerialized] private System.Type componentClass; + private bool embedded; private Property parentProperty; private PersistentClass owner; @@ -133,26 +136,26 @@ public System.Type ComponentClass get { // NH Different implementation (we use reflection only when needed) - if (componentClass == null) + if (componentClass != null) return componentClass; + if (componentClassName == null) return null; + + try { - try - { - componentClass = ReflectHelper.ClassForName(componentClassName); - } - catch (Exception cnfe) - { - if (!IsDynamic) // TODO remove this if leave the Exception - throw new MappingException("component class not found: " + componentClassName, cnfe); - return null; - } + componentClass = ReflectHelper.ClassForName(componentClassName); + } + catch (Exception cnfe) + { + if (!IsDynamic) // TODO remove this if leave the Exception + throw new MappingException("component class not found: " + componentClassName, cnfe); + return null; } return componentClass; } set // TODO NH: Remove the setter { componentClass = value; - if (componentClass != null) - componentClassName = componentClass.AssemblyQualifiedName; + if (value != null) + componentClassName = value.AssemblyQualifiedName; } } diff --git a/src/NHibernate/Mapping/PersistentClass.cs b/src/NHibernate/Mapping/PersistentClass.cs index b63a60a3e09..8ae13b2f8dc 100644 --- a/src/NHibernate/Mapping/PersistentClass.cs +++ b/src/NHibernate/Mapping/PersistentClass.cs @@ -63,7 +63,10 @@ public abstract class PersistentClass : IFilterable, IMetaAttributable, ISqlCust private Versioning.OptimisticLock optimisticLockMode; + [NonSerialized] private System.Type mappedClass; + + [NonSerialized] private System.Type proxyInterface; public string ClassName @@ -98,18 +101,17 @@ public virtual System.Type MappedClass { get { - if (mappedClass == null) + if (mappedClass != null) return mappedClass; + + if (className == null) + return null; + try { - if (className == null) - return null; - try - { - mappedClass = ReflectHelper.ClassForName(className); - } - catch (Exception cnfe) - { - throw new MappingException("entity class not found: " + className, cnfe); - } + mappedClass = ReflectHelper.ClassForName(className); + } + catch (Exception cnfe) + { + throw new MappingException("entity class not found: " + className, cnfe); } return mappedClass; } @@ -126,18 +128,17 @@ public virtual System.Type ProxyInterface { get { - if (proxyInterface == null) + if (proxyInterface != null) return proxyInterface; + + if (proxyInterfaceName == null) + return null; + try { - if (proxyInterfaceName == null) - return null; - try - { - proxyInterface = ReflectHelper.ClassForName(proxyInterfaceName); - } - catch (Exception cnfe) - { - throw new MappingException("proxy class not found: " + proxyInterfaceName, cnfe); - } + proxyInterface = ReflectHelper.ClassForName(proxyInterfaceName); + } + catch (Exception cnfe) + { + throw new MappingException("proxy class not found: " + proxyInterfaceName, cnfe); } return proxyInterface; } diff --git a/src/NHibernate/Mapping/RootClass.cs b/src/NHibernate/Mapping/RootClass.cs index 59210b16467..a2c66a34a24 100644 --- a/src/NHibernate/Mapping/RootClass.cs +++ b/src/NHibernate/Mapping/RootClass.cs @@ -1,7 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; - +using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.Util; @@ -40,13 +40,27 @@ public class RootClass : PersistentClass, ITableOwner private bool mutable; private bool embeddedIdentifier = false; private bool explicitPolymorphism; + [NonSerialized] private System.Type entityPersisterClass; + private SerializableSystemType _serializableEntityPersisterClass; private bool forceDiscriminator; private string where; private Table table; private bool discriminatorInsertable = true; private int nextSubclassId = 0; + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableEntityPersisterClass = SerializableSystemType.Wrap(entityPersisterClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + entityPersisterClass = _serializableEntityPersisterClass?.GetSystemType(); + } + public override int SubclassId { get { return 0; } diff --git a/src/NHibernate/NHibernate.csproj b/src/NHibernate/NHibernate.csproj index 73ac2c9775e..dc80551f44f 100644 --- a/src/NHibernate/NHibernate.csproj +++ b/src/NHibernate/NHibernate.csproj @@ -3,8 +3,9 @@ An object persistence library for relational databases. - net461 - $(NoWarn);3001;3002;3003;3005;1591 + netstandard2.0;net461 + true + $(NoWarn);0419;3001;3002;3003;3005;1591 True true ..\NHibernate.snk @@ -41,11 +42,18 @@ - + + + + + + + + diff --git a/src/NHibernate/Properties/BasicPropertyAccessor.cs b/src/NHibernate/Properties/BasicPropertyAccessor.cs index 18399171f31..e3f91ba0088 100644 --- a/src/NHibernate/Properties/BasicPropertyAccessor.cs +++ b/src/NHibernate/Properties/BasicPropertyAccessor.cs @@ -2,7 +2,9 @@ using System.Collections; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.Serialization; using NHibernate.Engine; +using NHibernate.Util; namespace NHibernate.Properties { @@ -60,10 +62,7 @@ public ISetter GetSetter(System.Type type, string propertyName) return result; } - public bool CanAccessThroughReflectionOptimizer - { - get { return true; } - } + public bool CanAccessThroughReflectionOptimizer => true; #endregion @@ -161,9 +160,13 @@ internal static BasicSetter GetSetterOrNull(System.Type type, string propertyNam [Serializable] public sealed class BasicGetter : IGetter, IOptimizableGetter { - private readonly System.Type clazz; - private readonly PropertyInfo property; - private readonly string propertyName; + [NonSerialized] + private System.Type _clazz; + private SerializableSystemType _serializableClazz; + [NonSerialized] + private PropertyInfo _property; + private SerializablePropertyInfo _serializableProperty; + private readonly string _propertyName; /// /// Initializes a new instance of . @@ -173,16 +176,27 @@ public sealed class BasicGetter : IGetter, IOptimizableGetter /// The name of the Property. public BasicGetter(System.Type clazz, PropertyInfo property, string propertyName) { - this.clazz = clazz; - this.property = property; - this.propertyName = propertyName; + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); + _property = property ?? throw new ArgumentNullException(nameof(property)); + _propertyName = propertyName; + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableClazz = SerializableSystemType.Wrap(_clazz); + _serializableProperty = SerializablePropertyInfo.Wrap(_property); } - public PropertyInfo Property + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return property; } + _clazz = _serializableClazz?.GetSystemType(); + _property = _serializableProperty?.Value; } + public PropertyInfo Property => _property; + #region IGetter Members /// @@ -196,11 +210,11 @@ public object Get(object target) { try { - return property.GetValue(target, Array.Empty()); + return _property.GetValue(target, Array.Empty()); } catch (Exception e) { - throw new PropertyAccessException(e, "Exception occurred", false, clazz, propertyName); + throw new PropertyAccessException(e, "Exception occurred", false, _clazz, _propertyName); } } @@ -208,19 +222,13 @@ public object Get(object target) /// Gets the that the Property returns. /// /// The that the Property returns. - public System.Type ReturnType - { - get { return property.PropertyType; } - } + public System.Type ReturnType => _property.PropertyType; /// /// Gets the name of the Property. /// /// The name of the Property. - public string PropertyName - { - get { return property.Name; } - } + public string PropertyName => _property.Name; /// /// Gets the for the Property. @@ -228,10 +236,7 @@ public string PropertyName /// /// The for the Property. /// - public MethodInfo Method - { - get { return property.GetGetMethod(true); } - } + public MethodInfo Method => _property.GetGetMethod(true); public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplementor session) { @@ -245,7 +250,7 @@ public void Emit(ILGenerator il) MethodInfo method = Method; if (method == null) { - throw new PropertyNotFoundException(clazz, property.Name, "getter"); + throw new PropertyNotFoundException(_clazz, _property.Name, "getter"); } il.EmitCall(OpCodes.Callvirt, method, null); } @@ -257,9 +262,13 @@ public void Emit(ILGenerator il) [Serializable] public sealed class BasicSetter : ISetter, IOptimizableSetter { - private readonly System.Type clazz; - private readonly PropertyInfo property; - private readonly string propertyName; + [NonSerialized] + private System.Type _clazz; + private SerializableSystemType _serializableClazz; + [NonSerialized] + private PropertyInfo _property; + private SerializablePropertyInfo _serializableProperty; + private readonly string _propertyName; /// /// Initializes a new instance of . @@ -269,16 +278,27 @@ public sealed class BasicSetter : ISetter, IOptimizableSetter /// The name of the mapped Property. public BasicSetter(System.Type clazz, PropertyInfo property, string propertyName) { - this.clazz = clazz; - this.property = property; - this.propertyName = propertyName; + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); + _property = property ?? throw new ArgumentNullException(nameof(property)); + _propertyName = propertyName; + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableClazz = SerializableSystemType.Wrap(_clazz); + _serializableProperty = SerializablePropertyInfo.Wrap(_property); } - public PropertyInfo Property + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return property; } + _clazz = _serializableClazz?.GetSystemType(); + _property = _serializableProperty?.Value; } + public PropertyInfo Property => _property; + #region ISetter Members /// @@ -293,30 +313,31 @@ public void Set(object target, object value) { try { - property.SetValue(target, value, Array.Empty()); + _property.SetValue(target, value, Array.Empty()); } catch (ArgumentException ae) { // if I'm reading the msdn docs correctly this is the only reason the ArgumentException // would be thrown, but it doesn't hurt to make sure. - if (property.PropertyType.IsInstanceOfType(value) == false) + if (_property.PropertyType.IsInstanceOfType(value) == false) { // add some details to the error message - there have been a few forum posts an they are // all related to an ISet and IDictionary mixups. - string msg = - String.Format("The type {0} can not be assigned to a property of type {1}", value.GetType(), - property.PropertyType); - throw new PropertyAccessException(ae, msg, true, clazz, propertyName); + var msg = string.Format( + "The type {0} can not be assigned to a property of type {1}", value.GetType(), + _property.PropertyType); + throw new PropertyAccessException(ae, msg, true, _clazz, _propertyName); } else { - throw new PropertyAccessException(ae, "ArgumentException while setting the property value by reflection", true, - clazz, propertyName); + throw new PropertyAccessException( + ae, "ArgumentException while setting the property value by reflection", true, + _clazz, _propertyName); } } catch (Exception e) { - throw new PropertyAccessException(e, "could not set a property value by reflection", true, clazz, propertyName); + throw new PropertyAccessException(e, "could not set a property value by reflection", true, _clazz, _propertyName); } } @@ -324,24 +345,15 @@ public void Set(object target, object value) /// Gets the name of the mapped Property. /// /// The name of the mapped Property or . - public string PropertyName - { - get { return property.Name; } - } + public string PropertyName => _property.Name; /// /// Gets the for the mapped Property. /// /// The for the mapped Property. - public MethodInfo Method - { - get { return property.GetSetMethod(true); } - } + public MethodInfo Method => _property.GetSetMethod(true); - public System.Type Type - { - get { return property.PropertyType; } - } + public System.Type Type => _property.PropertyType; #endregion @@ -350,7 +362,7 @@ public void Emit(ILGenerator il) MethodInfo method = Method; if (method == null) { - throw new PropertyNotFoundException(clazz, property.Name, "setter"); + throw new PropertyNotFoundException(_clazz, _property.Name, "setter"); } il.EmitCall(OpCodes.Callvirt, method, null); } diff --git a/src/NHibernate/Properties/EmbeddedPropertyAccessor.cs b/src/NHibernate/Properties/EmbeddedPropertyAccessor.cs index 8e22d653bf4..a8a32dc7418 100644 --- a/src/NHibernate/Properties/EmbeddedPropertyAccessor.cs +++ b/src/NHibernate/Properties/EmbeddedPropertyAccessor.cs @@ -1,7 +1,9 @@ using System; using System.Collections; using System.Reflection; +using System.Runtime.Serialization; using NHibernate.Engine; +using NHibernate.Util; namespace NHibernate.Properties { @@ -20,45 +22,47 @@ public ISetter GetSetter(System.Type theClass, string propertyName) return new EmbeddedSetter(theClass); } - public bool CanAccessThroughReflectionOptimizer - { - get { return false; } - } + public bool CanAccessThroughReflectionOptimizer => false; #endregion [Serializable] public sealed class EmbeddedGetter : IGetter { - private readonly System.Type clazz; + [NonSerialized] + private System.Type _clazz; + private SerializableSystemType _serializableClazz; internal EmbeddedGetter(System.Type clazz) { - this.clazz = clazz; + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); } - #region IGetter Members - - public object Get(object target) + [OnSerializing] + private void OnSerializing(StreamingContext context) { - return target; + _serializableClazz = SerializableSystemType.Wrap(_clazz); } - public System.Type ReturnType + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return clazz; } + _clazz = _serializableClazz?.GetSystemType(); } - public string PropertyName - { - get { return null; } - } + #region IGetter Members - public MethodInfo Method + public object Get(object target) { - get { return null; } + return target; } + public System.Type ReturnType => _clazz; + + public string PropertyName => null; + + public MethodInfo Method => null; + public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplementor session) { return Get(owner); @@ -68,41 +72,49 @@ public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplement public override string ToString() { - return string.Format("EmbeddedGetter({0})", clazz.FullName); + return string.Format("EmbeddedGetter({0})", _clazz.FullName); } } [Serializable] public sealed class EmbeddedSetter : ISetter { - private readonly System.Type clazz; + [NonSerialized] + private System.Type _clazz; + private SerializableSystemType _serializableClazz; internal EmbeddedSetter(System.Type clazz) { - this.clazz = clazz; + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); } - #region ISetter Members - - public void Set(object target, object value) + [OnSerializing] + private void OnSerializing(StreamingContext context) { + _serializableClazz = SerializableSystemType.Wrap(_clazz); } - public string PropertyName + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return null; } + _clazz = _serializableClazz?.GetSystemType(); } - public MethodInfo Method + #region ISetter Members + + public void Set(object target, object value) { - get { return null; } } + public string PropertyName => null; + + public MethodInfo Method => null; + #endregion public override string ToString() { - return string.Format("EmbeddedSetter({0})", clazz.FullName); + return string.Format("EmbeddedSetter({0})", _clazz.FullName); } } diff --git a/src/NHibernate/Properties/FieldAccessor.cs b/src/NHibernate/Properties/FieldAccessor.cs index 5a4b4df3854..48b1b3dd7ec 100644 --- a/src/NHibernate/Properties/FieldAccessor.cs +++ b/src/NHibernate/Properties/FieldAccessor.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.Serialization; using NHibernate.Engine; using NHibernate.Util; @@ -18,7 +19,7 @@ namespace NHibernate.Properties [Serializable] public class FieldAccessor : IPropertyAccessor { - private readonly IFieldNamingStrategy namingStrategy; + private readonly IFieldNamingStrategy _namingStrategy; /// /// Initializes a new instance of . @@ -33,7 +34,7 @@ public FieldAccessor() /// The to use. public FieldAccessor(IFieldNamingStrategy namingStrategy) { - this.namingStrategy = namingStrategy; + _namingStrategy = namingStrategy; } /// @@ -41,10 +42,7 @@ public FieldAccessor(IFieldNamingStrategy namingStrategy) /// mapped Property in the hbm.xml file to the name of the field in the class. /// /// The or . - public IFieldNamingStrategy NamingStrategy - { - get { return namingStrategy; } - } + public IFieldNamingStrategy NamingStrategy => _namingStrategy; #region IPropertyAccessor Members @@ -92,10 +90,7 @@ public ISetter GetSetter(System.Type theClass, string propertyName) return new FieldSetter(GetField(theClass, fieldName), theClass, fieldName); } - public bool CanAccessThroughReflectionOptimizer - { - get { return true; } - } + public bool CanAccessThroughReflectionOptimizer => true; #endregion @@ -144,13 +139,13 @@ internal static FieldInfo GetField(System.Type type, string fieldName) /// The name of the Field. private string GetFieldName(string propertyName) { - if (namingStrategy == null) + if (_namingStrategy == null) { return propertyName; } else { - return namingStrategy.GetFieldName(propertyName); + return _namingStrategy.GetFieldName(propertyName); } } @@ -160,9 +155,11 @@ private string GetFieldName(string propertyName) [Serializable] public sealed class FieldGetter : IGetter, IOptimizableGetter { - private readonly FieldInfo field; - private readonly System.Type clazz; - private readonly string name; + private FieldInfo _field; + private SerializableFieldInfo _serializableField; + private System.Type _clazz; + private SerializableSystemType _serializableClazz; + private readonly string _name; /// /// Initializes a new instance of . @@ -172,9 +169,23 @@ public sealed class FieldGetter : IGetter, IOptimizableGetter /// The name of the Field. public FieldGetter(FieldInfo field, System.Type clazz, string name) { - this.field = field; - this.clazz = clazz; - this.name = name; + _field = field ?? throw new ArgumentNullException(nameof(field)); + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); + _name = name; + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableClazz = SerializableSystemType.Wrap(_clazz); + _serializableField = SerializableFieldInfo.Wrap(_field); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _clazz = _serializableClazz?.GetSystemType(); + _field = _serializableField?.Value; } #region IGetter Members @@ -190,11 +201,11 @@ public object Get(object target) { try { - return field.GetValue(target); + return _field.GetValue(target); } catch (Exception e) { - throw new PropertyAccessException(e, "could not get a field value by reflection", false, clazz, name); + throw new PropertyAccessException(e, "could not get a field value by reflection", false, _clazz, _name); } } @@ -202,28 +213,19 @@ public object Get(object target) /// Gets the that the Field returns. /// /// The that the Field returns. - public System.Type ReturnType - { - get { return field.FieldType; } - } + public System.Type ReturnType => _field.FieldType; /// /// Gets the name of the Property. /// /// since this is a Field - not a Property. - public string PropertyName - { - get { return null; } - } + public string PropertyName => null; /// /// Gets the for the Property. /// /// since this is a Field - not a Property. - public MethodInfo Method - { - get { return null; } - } + public MethodInfo Method => null; public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplementor session) { @@ -234,7 +236,7 @@ public object GetForInsert(object owner, IDictionary mergeMap, ISessionImplement public void Emit(ILGenerator il) { - il.Emit(OpCodes.Ldfld, field); + il.Emit(OpCodes.Ldfld, _field); } } @@ -244,9 +246,11 @@ public void Emit(ILGenerator il) [Serializable] public sealed class FieldSetter : ISetter, IOptimizableSetter { - private readonly FieldInfo field; - private readonly System.Type clazz; - private readonly string name; + private FieldInfo _field; + private SerializableFieldInfo _serializableField; + private System.Type _clazz; + private SerializableSystemType _serializableClazz; + private readonly string _name; /// /// Initializes a new instance of . @@ -256,9 +260,23 @@ public sealed class FieldSetter : ISetter, IOptimizableSetter /// The name of the Field. public FieldSetter(FieldInfo field, System.Type clazz, string name) { - this.field = field; - this.clazz = clazz; - this.name = name; + _field = field ?? throw new ArgumentNullException(nameof(field)); + _clazz = clazz ?? throw new ArgumentNullException(nameof(clazz)); + _name = name; + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableClazz = SerializableSystemType.Wrap(_clazz); + _serializableField = SerializableFieldInfo.Wrap(_field); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _clazz = _serializableClazz?.GetSystemType(); + _field = _serializableField?.Value; } #region ISetter Members @@ -275,30 +293,30 @@ public void Set(object target, object value) { try { - field.SetValue(target, value); + _field.SetValue(target, value); } catch (ArgumentException ae) { // if I'm reading the msdn docs correctly this is the only reason the ArgumentException // would be thrown, but it doesn't hurt to make sure. - if (field.FieldType.IsInstanceOfType(value) == false) + if (_field.FieldType.IsInstanceOfType(value) == false) { // add some details to the error message - there have been a few forum posts an they are // all related to an ISet and IDictionary mixups. - string msg = - String.Format("The type {0} can not be assigned to a field of type {1}", value.GetType().ToString(), - field.FieldType.ToString()); - throw new PropertyAccessException(ae, msg, true, clazz, name); + var msg = string.Format( + "The type {0} can not be assigned to a field of type {1}", value.GetType(), + _field.FieldType); + throw new PropertyAccessException(ae, msg, true, _clazz, _name); } else { - throw new PropertyAccessException(ae, "ArgumentException while setting the field value by reflection", true, clazz, - name); + throw new PropertyAccessException( + ae, "ArgumentException while setting the field value by reflection", true, _clazz, _name); } } catch (Exception e) { - throw new PropertyAccessException(e, "could not set a field value by reflection", true, clazz, name); + throw new PropertyAccessException(e, "could not set a field value by reflection", true, _clazz, _name); } } @@ -306,30 +324,21 @@ public void Set(object target, object value) /// Gets the name of the Property. /// /// since this is a Field - not a Property. - public string PropertyName - { - get { return null; } - } + public string PropertyName => null; /// /// Gets the for the Property. /// /// since this is a Field - not a Property. - public MethodInfo Method - { - get { return null; } - } + public MethodInfo Method => null; - public System.Type Type - { - get { return field.FieldType; } - } + public System.Type Type => _field.FieldType; #endregion public void Emit(ILGenerator il) { - il.Emit(OpCodes.Stfld, field); + il.Emit(OpCodes.Stfld, _field); } } } diff --git a/src/NHibernate/PropertyAccessException.cs b/src/NHibernate/PropertyAccessException.cs index 47666cd249a..f33020fbc30 100644 --- a/src/NHibernate/PropertyAccessException.cs +++ b/src/NHibernate/PropertyAccessException.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.Serialization; using System.Security; -using System.Security.Permissions; +using NHibernate.Util; namespace NHibernate { @@ -11,9 +11,10 @@ namespace NHibernate [Serializable] public class PropertyAccessException : HibernateException, ISerializable { - private readonly System.Type persistentType; - private readonly string propertyName; - private readonly bool wasSetter; + [NonSerialized] + private readonly System.Type _persistentType; + private readonly string _propertyName; + private readonly bool _wasSetter; /// /// Initializes a new instance of the class. @@ -31,25 +32,22 @@ public PropertyAccessException(Exception innerException, string message, bool wa string propertyName) : base(message, innerException) { - this.persistentType = persistentType; - this.wasSetter = wasSetter; - this.propertyName = propertyName; + _persistentType = persistentType; + _wasSetter = wasSetter; + _propertyName = propertyName; } public PropertyAccessException(Exception innerException, string message, bool wasSetter, System.Type persistentType) : base(message, innerException) { - this.persistentType = persistentType; - this.wasSetter = wasSetter; + _persistentType = persistentType; + _wasSetter = wasSetter; } /// /// Gets the that NHibernate was trying find the Property or Field in. /// - public System.Type PersistentType - { - get { return persistentType; } - } + public System.Type PersistentType => _persistentType; /// /// Gets a message that describes the current . @@ -62,9 +60,9 @@ public override string Message { get { - return base.Message + (wasSetter ? " setter of " : " getter of ") + - (persistentType == null ? "UnknownType" : persistentType.FullName) + - (string.IsNullOrEmpty(propertyName) ? string.Empty: "." + propertyName); + return base.Message + (_wasSetter ? " setter of " : " getter of ") + + (_persistentType == null ? "UnknownType" : _persistentType.FullName) + + (string.IsNullOrEmpty(_propertyName) ? string.Empty: "." + _propertyName); } } @@ -83,9 +81,9 @@ public override string Message /// protected PropertyAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { - persistentType = info.GetValue("persistentType", typeof(System.Type)) as System.Type; - propertyName = info.GetString("propertyName"); - wasSetter = info.GetBoolean("wasSetter"); + _propertyName = info.GetString("propertyName"); + _wasSetter = info.GetBoolean("wasSetter"); + _persistentType = info.GetValue("persistentType"); } /// @@ -103,11 +101,11 @@ protected PropertyAccessException(SerializationInfo info, StreamingContext conte public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("persistentType", persistentType, typeof(System.Type)); - info.AddValue("propertyName", propertyName); - info.AddValue("wasSetter", wasSetter); + info.AddValue("persistentType", ObjectReferenceSystemType.Wrap(_persistentType, true)); + info.AddValue("propertyName", _propertyName); + info.AddValue("wasSetter", _wasSetter); } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs index a88f78034e8..3a5b8ff660b 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyAssemblyBuilder.cs @@ -8,17 +8,22 @@ public class DefaultProxyAssemblyBuilder : IProxyAssemblyBuilder { public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name) { -#if DEBUG +#if DEBUG && !NETSTANDARD2_0 AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndSave; #else AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; #endif + +#if !NETSTANDARD2_0 return appDomain.DefineDynamicAssembly(name, access); +#else + return AssemblyBuilder.DefineDynamicAssembly(name, access); +#endif } public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName) { -#if DEBUG +#if DEBUG && !NETSTANDARD2_0 ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", moduleName), true); #else diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs index 4b6f99d2f30..f0a5ac44ff3 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyObjectReference.cs @@ -16,7 +16,10 @@ namespace NHibernate.Proxy.DynamicProxy [Serializable] public class ProxyObjectReference : IObjectReference, ISerializable { + [NonSerialized] private readonly System.Type _baseType; + + [NonSerialized] private readonly IProxy _proxy; protected ProxyObjectReference(SerializationInfo info, StreamingContext context) diff --git a/src/NHibernate/Proxy/LiteLazyInitializer.cs b/src/NHibernate/Proxy/LiteLazyInitializer.cs index 9684bbed5f7..0272523e3e4 100644 --- a/src/NHibernate/Proxy/LiteLazyInitializer.cs +++ b/src/NHibernate/Proxy/LiteLazyInitializer.cs @@ -1,17 +1,35 @@ using System; +using System.Runtime.Serialization; using NHibernate.Engine; +using NHibernate.Util; namespace NHibernate.Proxy { [Serializable] internal sealed class LiteLazyInitializer : AbstractLazyInitializer { + [NonSerialized] + private System.Type _persistentClass; + private SerializableSystemType _serializablePersistentClass; + internal LiteLazyInitializer(string entityName, object id, ISessionImplementor session, System.Type persistentClass) : base(entityName, id, session) { - PersistentClass = persistentClass; + _persistentClass = persistentClass; } - public override System.Type PersistentClass { get; } + public override System.Type PersistentClass => _persistentClass; + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializablePersistentClass = SerializableSystemType.Wrap(_persistentClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _persistentClass = _serializablePersistentClass?.GetSystemType(); + } } } diff --git a/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs b/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs index 065c3705729..3d4f6800923 100644 --- a/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs +++ b/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Security; using NHibernate.Type; +using NHibernate.Util; namespace NHibernate.Proxy { @@ -11,10 +13,19 @@ namespace NHibernate.Proxy public sealed class NHibernateProxyFactoryInfo : ISerializable { private readonly string _entityName; + + [NonSerialized] private readonly System.Type _persistentClass; + + [NonSerialized] private readonly System.Type[] _interfaces; + + [NonSerialized] private readonly MethodInfo _getIdentifierMethod; + + [NonSerialized] private readonly MethodInfo _setIdentifierMethod; + private readonly IAbstractComponentType _componentIdType; internal NHibernateProxyFactoryInfo(string entityName, System.Type persistentClass, System.Type[] interfaces, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, IAbstractComponentType componentIdType) @@ -37,10 +48,10 @@ public IProxyFactory CreateProxyFactory() private NHibernateProxyFactoryInfo(SerializationInfo info, StreamingContext context) { _entityName = (string) info.GetValue(nameof(_entityName), typeof(string)); - _persistentClass = (System.Type) info.GetValue(nameof(_persistentClass), typeof(System.Type)); - _interfaces = (System.Type[]) info.GetValue(nameof(_interfaces), typeof(System.Type[])); - _getIdentifierMethod = (MethodInfo) info.GetValue(nameof(_getIdentifierMethod), typeof(MethodInfo)); - _setIdentifierMethod = (MethodInfo) info.GetValue(nameof(_setIdentifierMethod), typeof(MethodInfo)); + _persistentClass = info.GetValue(nameof(_persistentClass))?.GetSystemType(); + _interfaces = info.GetValue(nameof(_interfaces))?.Select(x => x?.GetSystemType()).ToArray(); + _getIdentifierMethod = info.GetValue(nameof(_getIdentifierMethod))?.Value; + _setIdentifierMethod = info.GetValue(nameof(_setIdentifierMethod))?.Value; _componentIdType = (IAbstractComponentType) info.GetValue(nameof(_componentIdType), typeof(IAbstractComponentType)); } @@ -48,10 +59,10 @@ private NHibernateProxyFactoryInfo(SerializationInfo info, StreamingContext cont public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(_entityName), _entityName); - info.AddValue(nameof(_persistentClass), _persistentClass); - info.AddValue(nameof(_interfaces), _interfaces); - info.AddValue(nameof(_getIdentifierMethod), _getIdentifierMethod); - info.AddValue(nameof(_setIdentifierMethod), _setIdentifierMethod); + info.AddValue(nameof(_persistentClass), SerializableSystemType.Wrap(_persistentClass)); + info.AddValue(nameof(_interfaces), _interfaces?.Select(SerializableSystemType.Wrap).ToArray()); + info.AddValue(nameof(_getIdentifierMethod), SerializableMethodInfo.Wrap(_getIdentifierMethod)); + info.AddValue(nameof(_setIdentifierMethod), SerializableMethodInfo.Wrap(_setIdentifierMethod)); info.AddValue(nameof(_componentIdType), _componentIdType); } } diff --git a/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs b/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs index 8c7aed84af4..1fe3e81c786 100644 --- a/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs +++ b/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs @@ -14,22 +14,75 @@ public abstract class BasicLazyInitializer : AbstractLazyInitializer { private static readonly IEqualityComparer IdentityEqualityComparer = new IdentityEqualityComparer(); - internal System.Type persistentClass; + // Since 5.1 + [Obsolete("This field has no inherited usages in NHibernate and will be removed.")] + [NonSerialized] protected internal MethodInfo getIdentifierMethod; + // Since 5.1 + [Obsolete("This field has no inherited usages in NHibernate and will be removed.")] + [NonSerialized] protected internal MethodInfo setIdentifierMethod; + // Since 5.1 + [Obsolete("This field has no inherited usages in NHibernate and will be removed.")] + [NonSerialized] protected internal bool overridesEquals; + // Since 5.1 + [Obsolete("This field has no inherited usages in NHibernate and will be removed.")] + [NonSerialized] protected internal IAbstractComponentType componentIdType; + [NonSerialized] + private System.Type _persistentClass; + private SerializableSystemType _serializablePersistentClass; + [NonSerialized] + private MethodInfo _getIdentifierMethod; + private SerializableMethodInfo _serializableGetIdentifierMethod; + [NonSerialized] + private MethodInfo _setIdentifierMethod; + private SerializableMethodInfo _serializableSetIdentifierMethod; + private readonly bool _overridesEquals; + private readonly IAbstractComponentType _componentIdType; + protected internal BasicLazyInitializer(string entityName, System.Type persistentClass, object id, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, IAbstractComponentType componentIdType, ISessionImplementor session, bool overridesEquals) : base(entityName, id, session) { - this.persistentClass = persistentClass; + _persistentClass = persistentClass; + _getIdentifierMethod = getIdentifierMethod; + _setIdentifierMethod = setIdentifierMethod; + _componentIdType = componentIdType; + _overridesEquals = overridesEquals; + +#pragma warning disable 618 this.getIdentifierMethod = getIdentifierMethod; this.setIdentifierMethod = setIdentifierMethod; this.componentIdType = componentIdType; this.overridesEquals = overridesEquals; +#pragma warning restore 618 + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializablePersistentClass = SerializableSystemType.Wrap(_persistentClass); + _serializableGetIdentifierMethod = SerializableMethodInfo.Wrap(_getIdentifierMethod); + _serializableSetIdentifierMethod = SerializableMethodInfo.Wrap(_setIdentifierMethod); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _persistentClass = _serializablePersistentClass?.GetSystemType(); + _getIdentifierMethod = _serializableGetIdentifierMethod?.Value; + _setIdentifierMethod = _serializableSetIdentifierMethod?.Value; + +#pragma warning disable 618 + getIdentifierMethod = _getIdentifierMethod; + setIdentifierMethod = _setIdentifierMethod; + componentIdType = _componentIdType; + overridesEquals = _overridesEquals; +#pragma warning restore 618 } /// @@ -47,7 +100,7 @@ protected virtual void AddSerializationInfo(SerializationInfo info, StreamingCon public override System.Type PersistentClass { - get { return persistentClass; } + get { return _persistentClass; } } /// @@ -69,7 +122,7 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) if (paramCount == 0) { - if (!overridesEquals && methodName == "GetHashCode") + if (!_overridesEquals && methodName == "GetHashCode") { return IdentityEqualityComparer.GetHashCode(proxy); } @@ -88,11 +141,11 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) } else if (paramCount == 1) { - if (!overridesEquals && methodName == "Equals") + if (!_overridesEquals && methodName == "Equals") { return IdentityEqualityComparer.Equals(args[0], proxy); } - else if (setIdentifierMethod!=null&&method.Equals(setIdentifierMethod)) + else if (_setIdentifierMethod != null && method.Equals(_setIdentifierMethod)) { Initialize(); Identifier = args[0]; @@ -127,7 +180,7 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) } //if it is a property of an embedded component, invoke on the "identifier" - if (componentIdType != null && componentIdType.IsMethodOf(method)) + if (_componentIdType != null && _componentIdType.IsMethodOf(method)) { return method.Invoke(Identifier, args); } @@ -137,13 +190,14 @@ public virtual object Invoke(MethodInfo method, object[] args, object proxy) private bool IsEqualToIdentifierMethod(MethodInfo method) { - if (getIdentifierMethod != null) + if (_getIdentifierMethod != null) { // in the case of inherited identifier methods (from a base class or an iterface) the // passed in MethodBase object is not equal to the getIdentifierMethod instance that we // have... but if their names and return types are identical, then it is the correct // identifier method - return method.Name.Equals(getIdentifierMethod.Name) && method.ReturnType.Equals(getIdentifierMethod.ReturnType); + return method.Name.Equals(_getIdentifierMethod.Name) + && method.ReturnType.Equals(_getIdentifierMethod.ReturnType); } return false; diff --git a/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs b/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs index 1321b7faa68..0c86169ca29 100644 --- a/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs +++ b/src/NHibernate/SqlCommand/Parser/MsSqlSelectParser.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; +using System.Linq; namespace NHibernate.SqlCommand.Parser { - using System.Linq; - /// /// Represents SQL Server SELECT query parser, primarily intended to support generation of /// limit queries by SQL Server dialects. diff --git a/src/NHibernate/Transform/AliasToBeanConstructorResultTransformer.cs b/src/NHibernate/Transform/AliasToBeanConstructorResultTransformer.cs index 7be85aa8fba..b905eaf9077 100644 --- a/src/NHibernate/Transform/AliasToBeanConstructorResultTransformer.cs +++ b/src/NHibernate/Transform/AliasToBeanConstructorResultTransformer.cs @@ -1,34 +1,45 @@ using System; using System.Collections; using System.Reflection; +using System.Runtime.Serialization; +using NHibernate.Util; namespace NHibernate.Transform { [Serializable] public class AliasToBeanConstructorResultTransformer : IResultTransformer { - private readonly ConstructorInfo constructor; + [NonSerialized] + private ConstructorInfo _constructor; + private SerializableConstructorInfo _serializableConstructor; public AliasToBeanConstructorResultTransformer(ConstructorInfo constructor) { - if (constructor == null) - { - throw new ArgumentNullException("constructor"); - } - this.constructor = constructor; + _constructor = constructor ?? throw new ArgumentNullException(nameof(constructor)); + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableConstructor = SerializableConstructorInfo.Wrap(_constructor); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _constructor = _serializableConstructor?.Value; } public object TransformTuple(object[] tuple, string[] aliases) { try { - return constructor.Invoke(tuple); + return _constructor.Invoke(tuple); } catch (Exception e) { throw new QueryException( - "could not instantiate: " + - constructor.DeclaringType.FullName, + $"could not instantiate: {_constructor.DeclaringType.FullName}", e); } } @@ -48,7 +59,7 @@ public bool Equals(AliasToBeanConstructorResultTransformer other) { return true; } - return Equals(other.constructor, constructor); + return Equals(other._constructor, _constructor); } public override bool Equals(object obj) @@ -58,7 +69,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - return constructor.GetHashCode(); + return _constructor.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Transform/AliasToBeanResultTransformer.cs b/src/NHibernate/Transform/AliasToBeanResultTransformer.cs index 96a0677f256..414a066512f 100644 --- a/src/NHibernate/Transform/AliasToBeanResultTransformer.cs +++ b/src/NHibernate/Transform/AliasToBeanResultTransformer.cs @@ -1,8 +1,11 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Data.SqlTypes; using System.Linq; using System.Reflection; +using System.Runtime.Serialization; +using NHibernate.Util; namespace NHibernate.Transform { @@ -33,32 +36,56 @@ namespace NHibernate.Transform [Serializable] public class AliasToBeanResultTransformer : AliasedTupleSubsetResultTransformer, IEquatable { - private readonly System.Type _resultClass; - private readonly ConstructorInfo _beanConstructor; - private readonly Dictionary> _fieldsByNameCaseSensitive; - private readonly Dictionary> _fieldsByNameCaseInsensitive; - private readonly Dictionary> _propertiesByNameCaseSensitive; - private readonly Dictionary> _propertiesByNameCaseInsensitive; + [NonSerialized] + private System.Type _resultClass; + private SerializableSystemType _serializableResultClass; + [NonSerialized] + private ConstructorInfo _beanConstructor; + [NonSerialized] + private Dictionary> _fieldsByNameCaseSensitive; + [NonSerialized] + private Dictionary> _fieldsByNameCaseInsensitive; + [NonSerialized] + private Dictionary> _propertiesByNameCaseSensitive; + [NonSerialized] + private Dictionary> _propertiesByNameCaseInsensitive; public AliasToBeanResultTransformer(System.Type resultClass) { - _resultClass = resultClass ?? throw new ArgumentNullException("resultClass"); + _resultClass = resultClass ?? throw new ArgumentNullException(nameof(resultClass)); + InitializeTransformer(); + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableResultClass = SerializableSystemType.Wrap(_resultClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _resultClass = _serializableResultClass?.GetSystemType(); + InitializeTransformer(); + } + + private void InitializeTransformer() + { const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - _beanConstructor = resultClass.GetConstructor(bindingFlags, null, System.Type.EmptyTypes, null); + _beanConstructor = _resultClass.GetConstructor(bindingFlags, null, System.Type.EmptyTypes, null); // 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 (_beanConstructor == null && resultClass.IsClass) + if (_beanConstructor == null && _resultClass.IsClass) { - throw new ArgumentException( - "The target class of a AliasToBeanResultTransformer need a parameter-less constructor", - nameof(resultClass)); + throw new InvalidOperationException( + "The target class of a AliasToBeanResultTransformer need a parameter-less constructor"); } var fields = new List>(); var properties = new List>(); - FetchFieldsAndProperties(fields, properties); + FetchFieldsAndProperties(_resultClass, fields, properties); _fieldsByNameCaseSensitive = GetMapByName(fields, StringComparer.Ordinal); _fieldsByNameCaseInsensitive = GetMapByName(fields, StringComparer.OrdinalIgnoreCase); @@ -75,7 +102,7 @@ public override object TransformTuple(object[] tuple, String[] aliases) { if (aliases == null) { - throw new ArgumentNullException("aliases"); + throw new ArgumentNullException(nameof(aliases)); } object result; @@ -137,7 +164,7 @@ private void SetProperty(string alias, object value, object resultObj) throw new PropertyNotFoundException(resultObj.GetType(), alias, "setter"); } - private bool TrySet(string alias, object value, object resultObj, Dictionary> fieldsMap) + private static bool TrySet(string alias, object value, object resultObj, Dictionary> fieldsMap) { if (fieldsMap.TryGetValue(alias, out var field)) { @@ -148,7 +175,7 @@ private bool TrySet(string alias, object value, object resultObj, Dictionary> propertiesMap) + private static bool TrySet(string alias, object value, object resultObj, Dictionary> propertiesMap) { if (propertiesMap.TryGetValue(alias, out var property)) { @@ -159,7 +186,7 @@ private bool TrySet(string alias, object value, object resultObj, Dictionary(NamedMember member, string alias) where T : MemberInfo + private static void CheckMember(NamedMember member, string alias) where T : MemberInfo { if (member.Member != null) return; @@ -177,10 +204,9 @@ private void CheckMember(NamedMember member, string alias) where T : Membe $"{string.Join(", ", member.AmbiguousMembers.Select(m => m.Name))}"); } - private void FetchFieldsAndProperties(List> fields, List> properties) + private static void FetchFieldsAndProperties(System.Type currentType, List> fields, List> properties) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - var currentType = _resultClass; var rank = 1; // For grasping private members, we need to manually walk the hierarchy. while (currentType != null && currentType != typeof(object)) @@ -199,7 +225,7 @@ private void FetchFieldsAndProperties(List> fields, List } } - private int GetFieldVisibilityRank(FieldInfo field) + private static int GetFieldVisibilityRank(FieldInfo field) { if (field.IsPublic) return 1; @@ -212,7 +238,7 @@ private int GetFieldVisibilityRank(FieldInfo field) return 5; } - private int GetPropertyVisibilityRank(PropertyInfo property) + private static int GetPropertyVisibilityRank(PropertyInfo property) { var setter = property.SetMethod; if (setter.IsPublic) @@ -226,7 +252,7 @@ private int GetPropertyVisibilityRank(PropertyInfo property) return 5; } - private Dictionary> GetMapByName(IEnumerable> members, StringComparer comparer) where T : MemberInfo + private static Dictionary> GetMapByName(IEnumerable> members, StringComparer comparer) where T : MemberInfo { return members .GroupBy(m => m.Member.Name, @@ -249,7 +275,6 @@ private struct RankedMember where T : MemberInfo public int VisibilityRank; } - [Serializable] private struct NamedMember where T : MemberInfo { public NamedMember(string name, T[] members) diff --git a/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs b/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs index e94b6afc265..d1c7c88422c 100644 --- a/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs +++ b/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs @@ -2,6 +2,7 @@ using NHibernate.Bytecode; using NHibernate.Intercept; using NHibernate.Properties; +using NHibernate.Util; namespace NHibernate.Tuple.Component { @@ -11,25 +12,33 @@ namespace NHibernate.Tuple.Component /// A specific to the POCO entity mode. /// [Serializable] - public class PocoComponentTuplizer : AbstractComponentTuplizer + public class PocoComponentTuplizer : AbstractComponentTuplizer, IDeserializationCallback { - private readonly System.Type componentClass; - private readonly ISetter parentSetter; - private readonly IGetter parentGetter; [NonSerialized] - private IReflectionOptimizer optimizer; + private System.Type _componentClass; + private SerializableSystemType _serializableComponentClass; + private readonly ISetter _parentSetter; + private readonly IGetter _parentGetter; + [NonSerialized] + private IReflectionOptimizer _optimizer; + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableComponentClass = SerializableSystemType.Wrap(_componentClass); + } - [OnDeserialized] - internal void OnDeserialized(StreamingContext context) + void IDeserializationCallback.OnDeserialization(object sender) { + _componentClass = _serializableComponentClass?.GetSystemType(); SetReflectionOptimizer(); - if (optimizer != null) + if (_optimizer != null) { // Fix for NH-3119: // Also set the InstantiationOptimizer on the deserialized PocoInstantiator. - ((PocoInstantiator)instantiator).SetOptimizer(optimizer.InstantiationOptimizer); + ((PocoInstantiator)instantiator).SetOptimizer(_optimizer.InstantiationOptimizer); } ClearOptimizerWhenUsingCustomAccessors(); @@ -38,18 +47,18 @@ internal void OnDeserialized(StreamingContext context) public PocoComponentTuplizer(Mapping.Component component) : base(component) { - componentClass = component.ComponentClass; + _componentClass = component.ComponentClass; var parentProperty = component.ParentProperty; if (parentProperty == null) { - parentSetter = null; - parentGetter = null; + _parentSetter = null; + _parentGetter = null; } else { - parentSetter = parentProperty.GetSetter(componentClass); - parentGetter = parentProperty.GetGetter(componentClass); + _parentSetter = parentProperty.GetSetter(_componentClass); + _parentGetter = parentProperty.GetGetter(_componentClass); } SetReflectionOptimizer(); @@ -60,10 +69,7 @@ public PocoComponentTuplizer(Mapping.Component component) ClearOptimizerWhenUsingCustomAccessors(); } - public override System.Type MappedClass - { - get { return componentClass; } - } + public override System.Type MappedClass => _componentClass; public override object[] GetPropertyValues(object component) { @@ -73,9 +79,9 @@ public override object[] GetPropertyValues(object component) return new object[propertySpan]; } - if (optimizer != null && optimizer.AccessOptimizer != null) + if (_optimizer != null && _optimizer.AccessOptimizer != null) { - return optimizer.AccessOptimizer.GetPropertyValues(component); + return _optimizer.AccessOptimizer.GetPropertyValues(component); } else { @@ -85,9 +91,9 @@ public override object[] GetPropertyValues(object component) public override void SetPropertyValues(object component, object[] values) { - if (optimizer != null && optimizer.AccessOptimizer != null) + if (_optimizer != null && _optimizer.AccessOptimizer != null) { - optimizer.AccessOptimizer.SetPropertyValues(component, values); + _optimizer.AccessOptimizer.SetPropertyValues(component, values); } else { @@ -97,17 +103,17 @@ public override void SetPropertyValues(object component, object[] values) public override object GetParent(object component) { - return parentGetter.Get(component); + return _parentGetter.Get(component); } public override void SetParent(object component, object parent, Engine.ISessionFactoryImplementor factory) { - parentSetter.Set(component, parent); + _parentSetter.Set(component, parent); } public override bool HasParentProperty { - get { return parentGetter != null; } + get { return _parentGetter != null; } } protected internal override IInstantiator BuildInstantiator(Mapping.Component component) @@ -118,13 +124,13 @@ protected internal override IInstantiator BuildInstantiator(Mapping.Component co // return new ProxiedInstantiator(component); //} - if (optimizer == null) + if (_optimizer == null) { return new PocoInstantiator(component, null); } else { - return new PocoInstantiator(component, optimizer.InstantiationOptimizer); + return new PocoInstantiator(component, _optimizer.InstantiationOptimizer); } } @@ -142,7 +148,7 @@ protected void SetReflectionOptimizer() { if (Cfg.Environment.UseReflectionOptimizer) { - optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(componentClass, getters, setters); + _optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(_componentClass, getters, setters); } } @@ -150,7 +156,7 @@ protected void ClearOptimizerWhenUsingCustomAccessors() { if (hasCustomAccessors) { - optimizer = null; + _optimizer = null; } } } diff --git a/src/NHibernate/Tuple/PocoInstantiator.cs b/src/NHibernate/Tuple/PocoInstantiator.cs index 5085b194880..33330b15f02 100644 --- a/src/NHibernate/Tuple/PocoInstantiator.cs +++ b/src/NHibernate/Tuple/PocoInstantiator.cs @@ -15,21 +15,26 @@ public class PocoInstantiator : IInstantiator, IDeserializationCallback { private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PocoInstantiator)); - private readonly System.Type mappedClass; + [NonSerialized] + private System.Type _mappedClass; + private SerializableSystemType _serializableMappedClass; [NonSerialized] - private IInstantiationOptimizer optimizer; + private IInstantiationOptimizer _optimizer; - private readonly IProxyFactory proxyFactory; + [NonSerialized] + private readonly IProxyFactory _proxyFactory; - private readonly bool generateFieldInterceptionProxy; + private readonly bool _generateFieldInterceptionProxy; - private readonly bool embeddedIdentifier; + private readonly bool _embeddedIdentifier; [NonSerialized] - private ConstructorInfo constructor; + private ConstructorInfo _constructor; - private readonly System.Type proxyInterface; + [NonSerialized] + private System.Type _proxyInterface; + private SerializableSystemType _serializableProxyInterface; public PocoInstantiator() { @@ -37,40 +42,40 @@ public PocoInstantiator() public PocoInstantiator(Mapping.Component component, IInstantiationOptimizer optimizer) { - mappedClass = component.ComponentClass; - this.optimizer = optimizer; + _mappedClass = component.ComponentClass; + _optimizer = optimizer; - proxyInterface = null; - embeddedIdentifier = false; + _proxyInterface = null; + _embeddedIdentifier = false; try { - constructor = ReflectHelper.GetDefaultConstructor(mappedClass); + _constructor = ReflectHelper.GetDefaultConstructor(_mappedClass); } catch (PropertyNotFoundException) { - log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName); - constructor = null; + log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", _mappedClass.FullName); + _constructor = null; } } public PocoInstantiator(PersistentClass persistentClass, IInstantiationOptimizer optimizer, IProxyFactory proxyFactory, bool generateFieldInterceptionProxy) { - mappedClass = persistentClass.MappedClass; - proxyInterface = persistentClass.ProxyInterface; - embeddedIdentifier = persistentClass.HasEmbeddedIdentifier; - this.optimizer = optimizer; - this.proxyFactory = proxyFactory; - this.generateFieldInterceptionProxy = generateFieldInterceptionProxy; + _mappedClass = persistentClass.MappedClass; + _proxyInterface = persistentClass.ProxyInterface; + _embeddedIdentifier = persistentClass.HasEmbeddedIdentifier; + _optimizer = optimizer; + _proxyFactory = proxyFactory; + _generateFieldInterceptionProxy = generateFieldInterceptionProxy; try { - constructor = ReflectHelper.GetDefaultConstructor(mappedClass); + _constructor = ReflectHelper.GetDefaultConstructor(_mappedClass); } catch (PropertyNotFoundException) { - log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName); - constructor = null; + log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", _mappedClass.FullName); + _constructor = null; } } @@ -78,66 +83,80 @@ public PocoInstantiator(PersistentClass persistentClass, IInstantiationOptimizer public object Instantiate(object id) { - bool useEmbeddedIdentifierInstanceAsEntity = embeddedIdentifier && id != null && id.GetType().Equals(mappedClass); + bool useEmbeddedIdentifierInstanceAsEntity = _embeddedIdentifier && id != null && id.GetType().Equals(_mappedClass); return useEmbeddedIdentifierInstanceAsEntity ? id : Instantiate(); } public object Instantiate() { - if (ReflectHelper.IsAbstractClass(mappedClass)) + if (ReflectHelper.IsAbstractClass(_mappedClass)) { - throw new InstantiationException("Cannot instantiate abstract class or interface: ", mappedClass); + throw new InstantiationException("Cannot instantiate abstract class or interface: ", _mappedClass); } - if (generateFieldInterceptionProxy) + if (_generateFieldInterceptionProxy) { - return proxyFactory.GetFieldInterceptionProxy(GetInstance()); + return _proxyFactory.GetFieldInterceptionProxy(GetInstance()); } return GetInstance(); } private object GetInstance() { - if (optimizer != null) + if (_optimizer != null) { - return optimizer.CreateInstance(); + return _optimizer.CreateInstance(); } - if (mappedClass.IsValueType) + if (_mappedClass.IsValueType) { - return Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(mappedClass, true); + return Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(_mappedClass, true); } - if (constructor == null) + if (_constructor == null) { - throw new InstantiationException("No default constructor for entity: ", mappedClass); + throw new InstantiationException("No default constructor for entity: ", _mappedClass); } try { - return constructor.Invoke(null); + return _constructor.Invoke(null); } catch (Exception e) { - throw new InstantiationException("Could not instantiate entity: ", e, mappedClass); + throw new InstantiationException("Could not instantiate entity: ", e, _mappedClass); } } public bool IsInstance(object obj) { - return mappedClass.IsInstanceOfType(obj) || (proxyInterface != null && proxyInterface.IsInstanceOfType(obj)); //this one needed only for guessEntityMode() + return _mappedClass.IsInstanceOfType(obj) || (_proxyInterface != null && _proxyInterface.IsInstanceOfType(obj)); //this one needed only for guessEntityMode() } #endregion + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableMappedClass = SerializableSystemType.Wrap(_mappedClass); + _serializableProxyInterface = SerializableSystemType.Wrap(_proxyInterface); + } + #region IDeserializationCallback Members public void OnDeserialization(object sender) { - constructor = ReflectHelper.GetDefaultConstructor(mappedClass); + if (_generateFieldInterceptionProxy) + { + throw new InvalidOperationException("IProxyFactory implementors are currently not serializable."); + } + + _mappedClass = _serializableMappedClass?.GetSystemType(); + _proxyInterface = _serializableProxyInterface?.GetSystemType(); + _constructor = ReflectHelper.GetDefaultConstructor(_mappedClass); } #endregion public void SetOptimizer(IInstantiationOptimizer optimizer) { - this.optimizer = optimizer; + _optimizer = optimizer; } } } diff --git a/src/NHibernate/Type/AbstractEnumType.cs b/src/NHibernate/Type/AbstractEnumType.cs index 0b6ab128392..a5d5a485869 100644 --- a/src/NHibernate/Type/AbstractEnumType.cs +++ b/src/NHibernate/Type/AbstractEnumType.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.Runtime.Serialization; using System.Text; using NHibernate.SqlTypes; +using NHibernate.Util; namespace NHibernate.Type { @@ -17,29 +19,40 @@ protected AbstractEnumType(SqlType sqlType,System.Type enumType) { if (enumType.IsEnum) { - this.enumType = enumType; + _enumType = enumType; } else { throw new MappingException(enumType.Name + " did not inherit from System.Enum"); } - defaultValue = Enum.ToObject(enumType, 0); + _defaultValue = Enum.ToObject(enumType, 0); } - private readonly object defaultValue; - private readonly System.Type enumType; + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableEnumType = SerializableSystemType.Wrap(_enumType); + } - public override System.Type ReturnedClass + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return enumType; } + _enumType = _serializableEnumType?.GetSystemType(); } + private readonly object _defaultValue; + [NonSerialized] + private System.Type _enumType; + private SerializableSystemType _serializableEnumType; + + public override System.Type ReturnedClass => _enumType; + #region IIdentifierType Members public object StringToObject(string xml) { - return Enum.Parse(enumType, xml); + return Enum.Parse(_enumType, xml); } #endregion @@ -50,14 +63,8 @@ public override object FromStringValue(string xml) return StringToObject(xml); } - public override System.Type PrimitiveClass - { - get { return this.enumType; } - } + public override System.Type PrimitiveClass => _enumType; - public override object DefaultValue - { - get { return defaultValue; } - } + public override object DefaultValue => _defaultValue; } } diff --git a/src/NHibernate/Type/ArrayType.cs b/src/NHibernate/Type/ArrayType.cs index 1e9df6180fe..005065d74d9 100644 --- a/src/NHibernate/Type/ArrayType.cs +++ b/src/NHibernate/Type/ArrayType.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Data.Common; +using System.Runtime.Serialization; using NHibernate.Collection; using NHibernate.Engine; using NHibernate.Persister.Collection; @@ -16,8 +17,12 @@ namespace NHibernate.Type [Serializable] public partial class ArrayType : CollectionType { - private readonly System.Type elementClass; - private readonly System.Type arrayClass; + [NonSerialized] + private System.Type _elementClass; + private SerializableSystemType _serializableElementClass; + [NonSerialized] + private System.Type _arrayClass; + private SerializableSystemType _serializableArrayClass; /// /// Initializes a new instance of a class for @@ -34,17 +39,28 @@ public partial class ArrayType : CollectionType public ArrayType(string role, string propertyRef, System.Type elementClass) : base(role, propertyRef) { - this.elementClass = elementClass; - arrayClass = Array.CreateInstance(elementClass, 0).GetType(); + _elementClass = elementClass; + _arrayClass = Array.CreateInstance(elementClass, 0).GetType(); + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableElementClass = SerializableSystemType.Wrap(_elementClass); + _serializableArrayClass = SerializableSystemType.Wrap(_arrayClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _elementClass = _serializableElementClass?.GetSystemType(); + _arrayClass = _serializableArrayClass?.GetSystemType(); } /// /// The for the element. /// - public override System.Type ReturnedClass - { - get { return arrayClass; } - } + public override System.Type ReturnedClass => _arrayClass; public override IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister, object key) { @@ -82,17 +98,14 @@ public override IPersistentCollection Wrap(ISessionImplementor session, object a } /// - public override bool IsArrayType - { - get { return true; } - } + public override bool IsArrayType => true; // Not ported - ToString( object value, ISessionFactoryImplementor factory ) // - PesistentCollectionType implementation is able to handle arrays too in .NET public override object InstantiateResult(object original) { - return Array.CreateInstance(elementClass, ((Array) original).Length); + return Array.CreateInstance(_elementClass, ((Array) original).Length); } public override object Instantiate(int anticipatedSize) @@ -161,4 +174,4 @@ public override string ToLoggableString(object value, ISessionFactoryImplementor return CollectionPrinter.ToString(list); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/EntityType.cs b/src/NHibernate/Type/EntityType.cs index 5b1e94f1307..06cf3f7d2f4 100644 --- a/src/NHibernate/Type/EntityType.cs +++ b/src/NHibernate/Type/EntityType.cs @@ -8,6 +8,7 @@ using NHibernate.Proxy; using NHibernate.Util; using System.Collections.Generic; +using System.Runtime.Serialization; namespace NHibernate.Type { @@ -17,11 +18,17 @@ namespace NHibernate.Type [Serializable] public abstract partial class EntityType : AbstractType, IAssociationType { + // Since v5.1 + [Obsolete("This field has no more usages in NHibernate and will be removed. Use RHSUniqueKeyPropertyName instead.")] protected readonly string uniqueKeyPropertyName; - private readonly bool eager; - private readonly string associatedEntityName; - private readonly bool unwrapProxy; - private System.Type returnedClass; + + private readonly string _uniqueKeyPropertyName; + private readonly bool _eager; + private readonly string _associatedEntityName; + private readonly bool _unwrapProxy; + [NonSerialized] + private System.Type _returnedClass; + private SerializableSystemType _serializableReturnedClass; /// Constructs the requested entity type mapping. /// The name of the associated entity. @@ -37,22 +44,35 @@ public abstract partial class EntityType : AbstractType, IAssociationType /// protected internal EntityType(string entityName, string uniqueKeyPropertyName, bool eager, bool unwrapProxy) { - associatedEntityName = entityName; +#pragma warning disable 618 this.uniqueKeyPropertyName = uniqueKeyPropertyName; - this.eager = eager; - this.unwrapProxy = unwrapProxy; +#pragma warning restore 618 + + _associatedEntityName = entityName; + _uniqueKeyPropertyName = uniqueKeyPropertyName; + _eager = eager; + _unwrapProxy = unwrapProxy; } - /// Explicitly, an entity type is an entity type - /// True. - public override sealed bool IsEntityType + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableReturnedClass = SerializableSystemType.Wrap(_returnedClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) { - get { return true; } + _returnedClass = _serializableReturnedClass?.GetSystemType(); } + /// Explicitly, an entity type is an entity type + /// True. + public sealed override bool IsEntityType => true; + public override bool IsEqual(object x, object y, ISessionFactoryImplementor factory) { - IEntityPersister persister = factory.GetEntityPersister(associatedEntityName); + IEntityPersister persister = factory.GetEntityPersister(_associatedEntityName); if (!persister.CanExtractIdOutOfEntity) { return base.IsEqual(x, y); @@ -112,15 +132,15 @@ public override object NullSafeGet(DbDataReader rs, string name, ISessionImpleme /// entity persister (nor to the session factory, to look it up) which is really /// needed to "do the right thing" here... /// - override public System.Type ReturnedClass + public override System.Type ReturnedClass { get { - if (returnedClass == null) + if (_returnedClass == null) { - returnedClass = DetermineAssociatedEntityClass(); + _returnedClass = DetermineAssociatedEntityClass(); } - return returnedClass; + return _returnedClass; } } @@ -165,12 +185,12 @@ protected internal object GetReferenceValue(object value, ISessionImplementor se else { IEntityPersister entityPersister = session.Factory.GetEntityPersister(GetAssociatedEntityName()); - object propertyValue = entityPersister.GetPropertyValue(value, uniqueKeyPropertyName); + object propertyValue = entityPersister.GetPropertyValue(value, _uniqueKeyPropertyName); // We now have the value of the property-ref we reference. However, // we need to dig a little deeper, as that property might also be // an entity type, in which case we need to resolve its identitifier - IType type = entityPersister.GetPropertyType(uniqueKeyPropertyName); + IType type = entityPersister.GetPropertyType(_uniqueKeyPropertyName); if (type.IsEntityType) { propertyValue = ((EntityType) type).GetReferenceValue(propertyValue, session); @@ -187,8 +207,8 @@ public override string ToLoggableString(object value, ISessionFactoryImplementor return "null"; } - IEntityPersister persister = factory.GetEntityPersister(associatedEntityName); - StringBuilder result = new StringBuilder().Append(associatedEntityName); + IEntityPersister persister = factory.GetEntityPersister(_associatedEntityName); + StringBuilder result = new StringBuilder().Append(_associatedEntityName); if (persister.HasIdentifierProperty) { @@ -200,20 +220,14 @@ public override string ToLoggableString(object value, ISessionFactoryImplementor return result.ToString(); } - public override string Name - { - get { return associatedEntityName; } - } + public override string Name => _associatedEntityName; public override object DeepCopy(object value, ISessionFactoryImplementor factory) { return value; //special case ... this is the leaf of the containment graph, even though not immutable } - public override bool IsMutable - { - get { return false; } - } + public override bool IsMutable => false; public abstract bool IsOneToOne { get; } @@ -239,9 +253,9 @@ public override object Replace(object original, object target, ISessionImplement { return target; } - if (session.GetContextEntityIdentifier(original) == null && ForeignKeys.IsTransientFast(associatedEntityName, original, session).GetValueOrDefault()) + if (session.GetContextEntityIdentifier(original) == null && ForeignKeys.IsTransientFast(_associatedEntityName, original, session).GetValueOrDefault()) { - object copy = session.Factory.GetEntityPersister(associatedEntityName).Instantiate(null); + object copy = session.Factory.GetEntityPersister(_associatedEntityName).Instantiate(null); //TODO: should this be Session.instantiate(Persister, ...)? copyCache.Add(original, copy); return copy; @@ -259,10 +273,7 @@ public override object Replace(object original, object target, ISessionImplement } } - public override bool IsAssociationType - { - get { return true; } - } + public override bool IsAssociationType => true; /// /// Converts the id contained in the to an object. @@ -274,7 +285,7 @@ public override bool IsAssociationType /// /// An instance of the object or if the identifer was null. /// - public override sealed object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) + public sealed override object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) { return ResolveIdentifier(Hydrate(rs, names, session, owner), session, owner); } @@ -283,7 +294,7 @@ public override sealed object NullSafeGet(DbDataReader rs, string[] names, ISess public bool IsUniqueKeyReference { - get { return uniqueKeyPropertyName != null; } + get { return _uniqueKeyPropertyName != null; } } public abstract bool IsNullable { get; } @@ -293,7 +304,7 @@ public bool IsUniqueKeyReference /// The associated joinable public IJoinable GetAssociatedJoinable(ISessionFactoryImplementor factory) { - return (IJoinable) factory.GetEntityPersister(associatedEntityName); + return (IJoinable) factory.GetEntityPersister(_associatedEntityName); } /// @@ -311,7 +322,7 @@ public IType GetIdentifierOrUniqueKeyType(IMapping factory) } else { - IType type = factory.GetReferencedPropertyType(GetAssociatedEntityName(), uniqueKeyPropertyName); + IType type = factory.GetReferencedPropertyType(GetAssociatedEntityName(), _uniqueKeyPropertyName); if (type.IsEntityType) { type = ((EntityType) type).GetIdentifierOrUniqueKeyType(factory); @@ -333,7 +344,7 @@ public string GetIdentifierOrUniqueKeyPropertyName(IMapping factory) } else { - return uniqueKeyPropertyName; + return _uniqueKeyPropertyName; } } @@ -359,10 +370,10 @@ internal virtual IType GetIdentifierType(ISessionImplementor session) protected object ResolveIdentifier(object id, ISessionImplementor session) { string entityName = GetAssociatedEntityName(); - bool isProxyUnwrapEnabled = unwrapProxy && session.Factory + bool isProxyUnwrapEnabled = _unwrapProxy && session.Factory .GetEntityPersister(entityName).IsInstrumented; - object proxyOrEntity = session.InternalLoad(entityName, id, eager, IsNullable && !isProxyUnwrapEnabled); + object proxyOrEntity = session.InternalLoad(entityName, id, _eager, IsNullable && !isProxyUnwrapEnabled); if (proxyOrEntity.IsProxy()) { @@ -386,21 +397,19 @@ public override object ResolveIdentifier(object value, ISessionImplementor sessi { return null; } - else + + if (IsNull(owner, session)) { - if (IsNull(owner, session)) - { - return null; //EARLY EXIT! - } + return null; //EARLY EXIT! + } - if (IsReferenceToPrimaryKey) - { - return ResolveIdentifier(value, session); - } - else - { - return LoadByUniqueKey(GetAssociatedEntityName(), uniqueKeyPropertyName, value, session); - } + if (IsReferenceToPrimaryKey) + { + return ResolveIdentifier(value, session); + } + else + { + return LoadByUniqueKey(GetAssociatedEntityName(), _uniqueKeyPropertyName, value, session); } } @@ -416,7 +425,7 @@ public virtual string GetAssociatedEntityName(ISessionFactoryImplementor factory /// The associated entity name. public string GetAssociatedEntityName() { - return associatedEntityName; + return _associatedEntityName; } /// @@ -431,24 +440,15 @@ public string GetAssociatedEntityName() /// public abstract bool UseLHSPrimaryKey { get; } - public string LHSPropertyName - { - get { return null; } - } + public string LHSPropertyName => null; - public string RHSUniqueKeyPropertyName - { - get { return uniqueKeyPropertyName; } - } + public string RHSUniqueKeyPropertyName => _uniqueKeyPropertyName; - public virtual string PropertyName - { - get { return null; } - } + public virtual string PropertyName => null; public override int GetHashCode(object x, ISessionFactoryImplementor factory) { - IEntityPersister persister = factory.GetEntityPersister(associatedEntityName); + IEntityPersister persister = factory.GetEntityPersister(_associatedEntityName); if (!persister.CanExtractIdOutOfEntity) { return base.GetHashCode(x); @@ -470,10 +470,7 @@ public override int GetHashCode(object x, ISessionFactoryImplementor factory) public abstract bool IsAlwaysDirtyChecked { get; } - public bool IsReferenceToPrimaryKey - { - get { return string.IsNullOrEmpty(uniqueKeyPropertyName); } - } + public bool IsReferenceToPrimaryKey => string.IsNullOrEmpty(_uniqueKeyPropertyName); public string GetOnCondition(string alias, ISessionFactoryImplementor factory, IDictionary enabledFilters) { @@ -490,7 +487,7 @@ public string GetOnCondition(string alias, ISessionFactoryImplementor factory, I public override IType GetSemiResolvedType(ISessionFactoryImplementor factory) { - return factory.GetEntityPersister(associatedEntityName).IdentifierType; + return factory.GetEntityPersister(_associatedEntityName).IdentifierType; } /// diff --git a/src/NHibernate/Type/ManyToOneType.cs b/src/NHibernate/Type/ManyToOneType.cs index 5f130dc8c35..b0e69c275b9 100644 --- a/src/NHibernate/Type/ManyToOneType.cs +++ b/src/NHibernate/Type/ManyToOneType.cs @@ -97,7 +97,7 @@ public override object Hydrate(DbDataReader rs, string[] names, ISessionImplemen private void ScheduleBatchLoadIfNeeded(object id, ISessionImplementor session) { //cannot batch fetch by unique key (property-ref associations) - if (uniqueKeyPropertyName == null && id != null) + if (RHSUniqueKeyPropertyName == null && id != null) { IEntityPersister persister = session.Factory.GetEntityPersister(GetAssociatedEntityName()); EntityKey entityKey = session.GenerateEntityKey(id, persister); diff --git a/src/NHibernate/Type/SerializableType.cs b/src/NHibernate/Type/SerializableType.cs index 3be7ad710db..923a2538918 100644 --- a/src/NHibernate/Type/SerializableType.cs +++ b/src/NHibernate/Type/SerializableType.cs @@ -6,6 +6,7 @@ using System.Runtime.Serialization.Formatters.Binary; using NHibernate.Engine; using NHibernate.SqlTypes; +using NHibernate.Util; namespace NHibernate.Type { @@ -28,8 +29,10 @@ namespace NHibernate.Type [Serializable] public partial class SerializableType : MutableType { - private readonly System.Type serializableClass; - private readonly BinaryType binaryType; + [NonSerialized] + private System.Type _serializableClass; + private SerializableSystemType _serializableSerializableClass; + private readonly BinaryType _binaryType; internal SerializableType() : this(typeof(Object)) { @@ -37,19 +40,31 @@ internal SerializableType() : this(typeof(Object)) internal SerializableType(System.Type serializableClass) : base(new BinarySqlType()) { - this.serializableClass = serializableClass; - binaryType = (BinaryType) NHibernateUtil.Binary; + _serializableClass = serializableClass; + _binaryType = NHibernateUtil.Binary; } internal SerializableType(System.Type serializableClass, BinarySqlType sqlType) : base(sqlType) { - this.serializableClass = serializableClass; - binaryType = (BinaryType) TypeFactory.GetBinaryType(sqlType.Length); + _serializableClass = serializableClass; + _binaryType = (BinaryType) TypeFactory.GetBinaryType(sqlType.Length); + } + + [OnSerializing] + private void OnSerializing(StreamingContext context) + { + _serializableSerializableClass = SerializableSystemType.Wrap(_serializableClass); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + _serializableClass = _serializableSerializableClass?.GetSystemType(); } public override void Set(DbCommand st, object value, int index, ISessionImplementor session) { - binaryType.Set(st, ToBytes(value), index, session); + _binaryType.Set(st, ToBytes(value), index, session); } public override object Get(DbDataReader rs, string name, ISessionImplementor session) @@ -59,7 +74,7 @@ public override object Get(DbDataReader rs, string name, ISessionImplementor ses public override object Get(DbDataReader rs, int index, ISessionImplementor session) { - byte[] bytes = (byte[]) binaryType.Get(rs, index, session); + byte[] bytes = (byte[]) _binaryType.Get(rs, index, session); if (bytes == null) { return null; @@ -70,10 +85,7 @@ public override object Get(DbDataReader rs, int index, ISessionImplementor sessi } } - public override System.Type ReturnedClass - { - get { return serializableClass; } - } + public override System.Type ReturnedClass => _serializableClass; public override bool IsEqual(object x, object y) { @@ -83,22 +95,22 @@ public override bool IsEqual(object x, object y) if (x == null || y == null) return false; - return x.Equals(y) || binaryType.IsEqual(ToBytes(x), ToBytes(y)); + return x.Equals(y) || _binaryType.IsEqual(ToBytes(x), ToBytes(y)); } public override int GetHashCode(Object x) { - return binaryType.GetHashCode(ToBytes(x)); + return _binaryType.GetHashCode(ToBytes(x)); } public override string ToString(object value) { - return binaryType.ToString(ToBytes(value)); + return _binaryType.ToString(ToBytes(value)); } public override object FromStringValue(string xml) { - return FromBytes((byte[])binaryType.FromStringValue(xml)); + return FromBytes((byte[])_binaryType.FromStringValue(xml)); } /// @@ -106,7 +118,7 @@ public override string Name { get { - return serializableClass == typeof(ISerializable) ? "serializable" : serializableClass.FullName; + return _serializableClass == typeof(ISerializable) ? "serializable" : _serializableClass.FullName; } } @@ -163,4 +175,4 @@ public override object Disassemble(object value, ISessionImplementor session, ob return (value == null) ? null : ToBytes(value); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/UnresolvableObjectException.cs b/src/NHibernate/UnresolvableObjectException.cs index d766bf2881a..c66947193d5 100644 --- a/src/NHibernate/UnresolvableObjectException.cs +++ b/src/NHibernate/UnresolvableObjectException.cs @@ -3,6 +3,7 @@ using System.Security; using System.Security.Permissions; using NHibernate.Impl; +using NHibernate.Util; namespace NHibernate { @@ -13,9 +14,10 @@ namespace NHibernate [Serializable] public class UnresolvableObjectException : HibernateException { - private readonly object identifier; - private readonly System.Type clazz; - private readonly string entityName; + private readonly object _identifier; + [NonSerialized] + private readonly System.Type _clazz; + private readonly string _entityName; /// /// Initializes a new instance of the class. @@ -39,40 +41,24 @@ public UnresolvableObjectException(object identifier, string entityName) public UnresolvableObjectException(string message, object identifier, System.Type clazz) : base(message) { - this.identifier = identifier; - this.clazz = clazz; + _identifier = identifier; + _clazz = clazz; } public UnresolvableObjectException(string message, object identifier, string entityName) : base(message) { - this.identifier = identifier; - this.entityName = entityName; + _identifier = identifier; + _entityName = entityName; } - public object Identifier - { - get { return identifier; } - } + public object Identifier => _identifier; - public override string Message - { - get { return base.Message + MessageHelper.InfoString(EntityName, identifier); } - } + public override string Message => base.Message + MessageHelper.InfoString(EntityName, _identifier); - public System.Type PersistentClass - { - get { return clazz; } - } + public System.Type PersistentClass => _clazz; - public string EntityName - { - get - { - if (clazz != null) return clazz.FullName; - return entityName; - } - } + public string EntityName => _clazz != null ? _clazz.FullName : _entityName; public static void ThrowIfNull(object o, object id, System.Type clazz) { @@ -96,17 +82,17 @@ public static void ThrowIfNull(object o, object id, string entityName) public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("identifier", identifier); - info.AddValue("clazz", clazz); - info.AddValue("entityName", entityName); + info.AddValue("identifier", _identifier); + info.AddValue("clazz", ObjectReferenceSystemType.Wrap(_clazz, true)); + info.AddValue("entityName", _entityName); } protected UnresolvableObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { - identifier = info.GetValue("identifier", typeof(object)); - clazz = info.GetValue("clazz", typeof(System.Type)) as System.Type; - entityName = info.GetString("entityName"); + _identifier = info.GetValue("identifier", typeof(object)); + _entityName = info.GetString("entityName"); + _clazz = info.GetValue("clazz"); } #endregion diff --git a/src/NHibernate/Util/AssemblyQualifiedTypeName.cs b/src/NHibernate/Util/AssemblyQualifiedTypeName.cs index b82fc677523..23c28469fff 100644 --- a/src/NHibernate/Util/AssemblyQualifiedTypeName.cs +++ b/src/NHibernate/Util/AssemblyQualifiedTypeName.cs @@ -2,35 +2,26 @@ namespace NHibernate.Util { + [Serializable] public class AssemblyQualifiedTypeName { - private readonly string type; - private readonly string assembly; - private readonly int hashCode; + private readonly string _type; + private readonly string _assembly; + private readonly int _hashCode; public AssemblyQualifiedTypeName(string type, string assembly) { - if (type == null) - { - throw new ArgumentNullException("type"); - } - this.type = type; - this.assembly = assembly; + _type = type ?? throw new ArgumentNullException(nameof(type)); + _assembly = assembly; unchecked { - hashCode = (type.GetHashCode() * 397) ^ (assembly != null ? assembly.GetHashCode() : 0); + _hashCode = (type.GetHashCode() * 397) ^ (assembly?.GetHashCode() ?? 0); } } - public string Type - { - get { return type; } - } + public string Type => _type; - public string Assembly - { - get { return assembly; } - } + public string Assembly => _assembly; public override bool Equals(object obj) { @@ -40,12 +31,12 @@ public override bool Equals(object obj) public override string ToString() { - if (assembly == null) + if (_assembly == null) { - return type; + return _type; } - return string.Concat(type, ", ", assembly); + return string.Concat(_type, ", ", _assembly); } public bool Equals(AssemblyQualifiedTypeName obj) @@ -58,12 +49,12 @@ public bool Equals(AssemblyQualifiedTypeName obj) { return true; } - return Equals(obj.type, type) && Equals(obj.assembly, assembly); + return Equals(obj._type, _type) && Equals(obj._assembly, _assembly); } public override int GetHashCode() { - return hashCode; + return _hashCode; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Util/ReflectHelper.cs b/src/NHibernate/Util/ReflectHelper.cs index b7b159025e6..9c7ef64f4c6 100644 --- a/src/NHibernate/Util/ReflectHelper.cs +++ b/src/NHibernate/Util/ReflectHelper.cs @@ -392,7 +392,7 @@ public static System.Type TypeFromAssembly(string type, string assembly, bool th /// type cannot be found then the assembly is loaded using /// . /// - public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool throwOnError) + public static System.Type TypeFromAssembly(this AssemblyQualifiedTypeName name, bool throwOnError) { try { diff --git a/src/NHibernate/Util/SerializableConstructorInfo.cs b/src/NHibernate/Util/SerializableConstructorInfo.cs new file mode 100644 index 00000000000..abde74b5ad6 --- /dev/null +++ b/src/NHibernate/Util/SerializableConstructorInfo.cs @@ -0,0 +1,81 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Util +{ + [Serializable] + internal sealed class SerializableConstructorInfo : ISerializable, IEquatable + { + [NonSerialized] + private readonly ConstructorInfo _constructorInfo; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// New instance of or null. + public static SerializableConstructorInfo Wrap(ConstructorInfo constructorInfo) + { + return constructorInfo == null ? null : new SerializableConstructorInfo(constructorInfo); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + private SerializableConstructorInfo(ConstructorInfo constructorInfo) + { + _constructorInfo = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo)); + if (constructorInfo.DeclaringType == null) + { + throw new ArgumentException("ConstructorInfo must have non-null DeclaringType", nameof(constructorInfo)); + } + } + + private SerializableConstructorInfo(SerializationInfo info, StreamingContext context) + { + System.Type declaringType = info.GetValue("declaringType").GetSystemType(); + SerializableSystemType[] parameterSystemTypes = info.GetValue("parameterTypesHelper"); + + System.Type[] parameterTypes = parameterSystemTypes?.Select(x => x.GetSystemType()).ToArray() ?? new System.Type[0]; + _constructorInfo = declaringType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, parameterTypes, null); + + if (_constructorInfo == null) throw new MissingMethodException(declaringType.FullName, ".ctor"); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + SerializableSystemType[] parameterSystemTypes = + _constructorInfo.GetParameters() + .Select(x => SerializableSystemType.Wrap(x.ParameterType)) + .ToArray(); + + info.AddValue("declaringType", SerializableSystemType.Wrap(_constructorInfo.DeclaringType)); + info.AddValue("parameterTypesHelper", parameterSystemTypes); + } + + public ConstructorInfo Value => _constructorInfo; + + public bool Equals(SerializableConstructorInfo other) + { + return other != null && Equals(_constructorInfo, other._constructorInfo); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + return obj is SerializableConstructorInfo && Equals((SerializableConstructorInfo) obj); + } + + public override int GetHashCode() + { + return (_constructorInfo != null ? _constructorInfo.GetHashCode() : 0); + } + } +} diff --git a/src/NHibernate/Util/SerializableFieldInfo.cs b/src/NHibernate/Util/SerializableFieldInfo.cs new file mode 100644 index 00000000000..30c3d3b5317 --- /dev/null +++ b/src/NHibernate/Util/SerializableFieldInfo.cs @@ -0,0 +1,74 @@ +using System; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Util +{ + [Serializable] + internal sealed class SerializableFieldInfo : ISerializable, IEquatable + { + [NonSerialized] + private readonly FieldInfo _fieldInfo; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// New instance of or null. + public static SerializableFieldInfo Wrap(FieldInfo fieldInfo) + { + return fieldInfo == null ? null : new SerializableFieldInfo(fieldInfo); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + private SerializableFieldInfo(FieldInfo fieldInfo) + { + _fieldInfo = fieldInfo ?? throw new ArgumentNullException(nameof(fieldInfo)); + if (fieldInfo.IsStatic) throw new ArgumentException("Only for instance fields", nameof(fieldInfo)); + if (fieldInfo.DeclaringType == null) throw new ArgumentException("FieldInfo must have non-null DeclaringType", nameof(fieldInfo)); + } + + private SerializableFieldInfo(SerializationInfo info, StreamingContext context) + { + System.Type declaringType = info.GetValue("declaringType").GetSystemType(); + string fieldName = info.GetString("fieldName"); + + _fieldInfo = declaringType.GetField( + fieldName, + BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + if (_fieldInfo == null) throw new MissingFieldException(declaringType.FullName, fieldName); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("declaringType", SerializableSystemType.Wrap(_fieldInfo.DeclaringType)); + info.AddValue("fieldName", _fieldInfo.Name); + } + + public FieldInfo Value => _fieldInfo; + + public bool Equals(SerializableFieldInfo other) + { + return other != null && Equals(_fieldInfo, other._fieldInfo); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + return obj is SerializableFieldInfo && Equals((SerializableFieldInfo) obj); + } + + public override int GetHashCode() + { + return (_fieldInfo != null ? _fieldInfo.GetHashCode() : 0); + } + } +} diff --git a/src/NHibernate/Util/SerializableMethodInfo.cs b/src/NHibernate/Util/SerializableMethodInfo.cs new file mode 100644 index 00000000000..cdfc1767aba --- /dev/null +++ b/src/NHibernate/Util/SerializableMethodInfo.cs @@ -0,0 +1,71 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Util +{ + [Serializable] + internal sealed class SerializableMethodInfo : ISerializable, IEquatable + { + [NonSerialized] + private readonly MethodInfo _methodInfo; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// New instance of or null. + public static SerializableMethodInfo Wrap(MethodInfo methodInfo) + { + return methodInfo == null ? null : new SerializableMethodInfo(methodInfo); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + private SerializableMethodInfo(MethodInfo methodInfo) + { + _methodInfo = methodInfo ?? throw new ArgumentNullException(nameof(methodInfo)); + if (methodInfo.IsStatic) throw new ArgumentException("Only for instance fields", nameof(methodInfo)); + if (methodInfo.DeclaringType == null) throw new ArgumentException("MethodInfo must have non-null DeclaringType", nameof(methodInfo)); + } + + private SerializableMethodInfo(SerializationInfo info, StreamingContext context) + { + System.Type declaringType = info.GetValue("declaringType").GetSystemType(); + string methodName = info.GetString("methodName"); + SerializableSystemType[] parameterSystemTypes = info.GetValue("parameterTypesHelper"); + + System.Type[] parameterTypes = parameterSystemTypes?.Select(x => x.GetSystemType()).ToArray() ?? new System.Type[0]; + _methodInfo = declaringType.GetMethod( + methodName, + BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null); + + if (_methodInfo == null) throw new MissingMethodException(declaringType.FullName, methodName); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + SerializableSystemType[] parameterSystemTypes = + _methodInfo.GetParameters() + .Select(x => SerializableSystemType.Wrap(x.ParameterType)) + .ToArray(); + + info.AddValue("declaringType", SerializableSystemType.Wrap(_methodInfo.DeclaringType)); + info.AddValue("methodName", _methodInfo.Name); + info.AddValue("parameterTypesHelper", parameterSystemTypes); + } + + public MethodInfo Value => _methodInfo; + + public bool Equals(SerializableMethodInfo other) + { + return other != null && Equals(_methodInfo, other._methodInfo); + } + } +} diff --git a/src/NHibernate/Util/SerializablePropertyInfo.cs b/src/NHibernate/Util/SerializablePropertyInfo.cs new file mode 100644 index 00000000000..0e902d8b6cf --- /dev/null +++ b/src/NHibernate/Util/SerializablePropertyInfo.cs @@ -0,0 +1,74 @@ +using System; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Util +{ + [Serializable] + internal sealed class SerializablePropertyInfo : ISerializable, IEquatable + { + [NonSerialized] + private readonly PropertyInfo _propertyInfo; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// New instance of or null. + public static SerializablePropertyInfo Wrap(PropertyInfo propertyInfo) + { + return propertyInfo == null ? null : new SerializablePropertyInfo(propertyInfo); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + private SerializablePropertyInfo(PropertyInfo propertyInfo) + { + _propertyInfo = propertyInfo ?? throw new ArgumentNullException(nameof(propertyInfo)); + if (propertyInfo.DeclaringType == null) throw new ArgumentException("PropertyInfo must have non-null DeclaringType", nameof(propertyInfo)); + if (propertyInfo.GetIndexParameters().Length > 0) throw new ArgumentException("PropertyInfo not supported with IndexParameters", nameof(propertyInfo)); + } + + private SerializablePropertyInfo(SerializationInfo info, StreamingContext context) + { + System.Type declaringType = info.GetValue("declaringType").GetSystemType(); + string propertyName = info.GetString("propertyName"); + + _propertyInfo = declaringType.GetProperty( + propertyName, + BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + if (_propertyInfo == null) throw new MissingMethodException(declaringType.FullName, propertyName); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("declaringType", SerializableSystemType.Wrap(_propertyInfo.DeclaringType)); + info.AddValue("propertyName", _propertyInfo.Name); + } + + public PropertyInfo Value => _propertyInfo; + + public bool Equals(SerializablePropertyInfo other) + { + return other != null && Equals(_propertyInfo, other._propertyInfo); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + return obj is SerializablePropertyInfo && Equals((SerializablePropertyInfo) obj); + } + + public override int GetHashCode() + { + return (_propertyInfo != null ? _propertyInfo.GetHashCode() : 0); + } + } +} diff --git a/src/NHibernate/Util/SerializableSystemType.cs b/src/NHibernate/Util/SerializableSystemType.cs new file mode 100644 index 00000000000..2e1b6565db6 --- /dev/null +++ b/src/NHibernate/Util/SerializableSystemType.cs @@ -0,0 +1,145 @@ +using System; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Util +{ + [Serializable] + internal class SerializableSystemType : ISerializable, IEquatable + { + [NonSerialized] + private readonly System.Type _type; + + private AssemblyQualifiedTypeName _typeName; + + protected AssemblyQualifiedTypeName TypeName => _typeName; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// New instance of or null. + public static SerializableSystemType Wrap(System.Type type) + { + return type == null ? null : new SerializableSystemType(type); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + protected SerializableSystemType(System.Type type) + { + _type = type ?? throw new ArgumentNullException(nameof(type)); + } + + protected SerializableSystemType(SerializationInfo info, StreamingContext context) + { + _typeName = info.GetValue("_typeName"); + if (_typeName == null) + throw new InvalidOperationException("_typeName was null after deserialization"); + _type = _typeName.TypeFromAssembly(false); + } + + /// + /// Returns the wrapped type. Will throw if it was unable to load it after deserialization. + /// + /// The type that this class was initialized with or initialized after deserialization. + public System.Type GetSystemType() => _type ?? throw new TypeLoadException("Could not load type " + _typeName + "."); + + /// + /// Returns the wrapped type. Will return null if it was unable to load it after deserialization. + /// + /// The type that this class was initialized with, the type initialized after deserialization, or null if unable to load. + public System.Type TryGetSystemType() => _type; + + public string FullName => _type?.FullName ?? _typeName.Type; + + public string AssemblyQualifiedName => _type?.AssemblyQualifiedName ?? _typeName.ToString(); + + [SecurityCritical] + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (_typeName == null) + { + _typeName = new AssemblyQualifiedTypeName(_type.FullName, _type.Assembly.FullName); + } + + info.AddValue("_typeName", _typeName); + } + + public bool Equals(SerializableSystemType other) + { + return other != null && + (_type == null || other._type == null + ? Equals(_typeName, other._typeName) + : Equals(_type, other._type)); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + return obj is SerializableSystemType type && Equals(type); + } + + public override int GetHashCode() + { + unchecked + { + return (FullName.GetHashCode() * 397) ^ (AssemblyQualifiedName?.GetHashCode() ?? 0); + } + } + } + + [Serializable] + internal sealed class ObjectReferenceSystemType : SerializableSystemType, IObjectReference + { + private readonly bool _throwOnDeserializationError; + + /// + /// Creates a new instance of if + /// is not null, otherwise returns null. + /// + /// The being wrapped for serialization. + /// for failing if unable to load the type + /// in , to yield + /// instead. + /// New instance of or null. + public static ObjectReferenceSystemType Wrap(System.Type type, bool throwOnDeserializationError) + { + return type == null ? null : new ObjectReferenceSystemType(type, throwOnDeserializationError); + } + + /// + /// Creates a new + /// + /// The being wrapped for serialization. + /// for failing if unable to load the type + /// in , to yield + /// instead. + private ObjectReferenceSystemType(System.Type type, bool throwOnDeserializationError) : base(type) + { + _throwOnDeserializationError = throwOnDeserializationError; + } + + private ObjectReferenceSystemType(SerializationInfo info, StreamingContext context) : base(info, context) + { + _throwOnDeserializationError = info.GetBoolean("_throwOnDeserializationError"); + } + + [SecurityCritical] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("_throwOnDeserializationError", _throwOnDeserializationError); + } + + [SecurityCritical] + object IObjectReference.GetRealObject(StreamingContext context) + { + return TypeName.TypeFromAssembly(_throwOnDeserializationError); + } + } +} diff --git a/src/NHibernate/Util/SerializationInfoExtensions.cs b/src/NHibernate/Util/SerializationInfoExtensions.cs new file mode 100644 index 00000000000..b6d2d68d931 --- /dev/null +++ b/src/NHibernate/Util/SerializationInfoExtensions.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.Serialization; + +namespace NHibernate.Util +{ + internal static class SerializationInfoExtensions + { + public static T GetValue(this SerializationInfo info, string name) + { + if (info == null) throw new ArgumentNullException(nameof(info)); + return (T) info.GetValue(name, typeof(T)); + } + } +} diff --git a/teamcity.build b/teamcity.build index 9a5d35b3815..5190605d233 100644 --- a/teamcity.build +++ b/teamcity.build @@ -51,7 +51,7 @@ - + @@ -59,7 +59,7 @@ - + @@ -67,27 +67,27 @@ - + - + - + - + @@ -162,7 +162,7 @@ - + @@ -170,7 +170,7 @@ - +