From c849842f766290a276e8d08fb4f5582eaa535460 Mon Sep 17 00:00:00 2001 From: Antonio Milesi Bastos Date: Mon, 4 May 2015 16:51:24 -0300 Subject: [PATCH 1/4] add session resolver project --- source/.nuget/NuGet.Config | 9 -- source/.nuget/NuGet.targets | 136 ------------------ source/.nuget/packages.config | 4 - source/NHibernate.AspNet.Identity.sln | 20 ++- .../ISessionResolver.cs | 11 ++ .../NHibernate.SessionResolver.csproj | 122 ++++++++++++++++ .../Owin/SessionMiddleware.cs | 36 +++++ .../Properties/AssemblyInfo.cs | 23 +++ .../SessionFactoryBuilder.cs | 73 ++++++++++ .../SessionResolver.cs | 75 ++++++++++ .../packages.config | 8 ++ 11 files changed, 361 insertions(+), 156 deletions(-) delete mode 100644 source/.nuget/NuGet.Config delete mode 100644 source/.nuget/NuGet.targets delete mode 100644 source/.nuget/packages.config create mode 100644 source/NHibernate.SessionResolver/ISessionResolver.cs create mode 100644 source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj create mode 100644 source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs create mode 100644 source/NHibernate.SessionResolver/Properties/AssemblyInfo.cs create mode 100644 source/NHibernate.SessionResolver/SessionFactoryBuilder.cs create mode 100644 source/NHibernate.SessionResolver/SessionResolver.cs create mode 100644 source/NHibernate.SessionResolver/packages.config diff --git a/source/.nuget/NuGet.Config b/source/.nuget/NuGet.Config deleted file mode 100644 index 338ed8a..0000000 --- a/source/.nuget/NuGet.Config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/source/.nuget/NuGet.targets b/source/.nuget/NuGet.targets deleted file mode 100644 index 045aa84..0000000 --- a/source/.nuget/NuGet.targets +++ /dev/null @@ -1,136 +0,0 @@ - - - - $(MSBuildProjectDirectory)\..\ - - - false - - - false - - - true - - - true - - - - - - - - - - - $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) - $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) - - - - - $(SolutionDir).nuget - packages.config - - - - - $(NuGetToolsPath)\NuGet.exe - @(PackageSource) - - "$(NuGetExePath)" - mono --runtime=v4.0.30319 $(NuGetExePath) - - $(TargetDir.Trim('\\')) - - -RequireConsent - -NonInteractive - - "$(SolutionDir) " - "$(SolutionDir)" - - - $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) - $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols - - - - RestorePackages; - $(BuildDependsOn); - - - - - $(BuildDependsOn); - BuildPackage; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/source/.nuget/packages.config b/source/.nuget/packages.config deleted file mode 100644 index a7df95c..0000000 --- a/source/.nuget/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/source/NHibernate.AspNet.Identity.sln b/source/NHibernate.AspNet.Identity.sln index 0f6daa5..955cc09 100644 --- a/source/NHibernate.AspNet.Identity.sln +++ b/source/NHibernate.AspNet.Identity.sln @@ -1,16 +1,10 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 +VisualStudioVersion = 12.0.31101.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.AspNet.Identity", "NHibernate.AspNet.Identity\NHibernate.AspNet.Identity.csproj", "{C620FAAE-F1B6-479E-9959-C46C20ED0A8A}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{B4B93010-9348-456C-9F18-1305854364F9}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.targets = .nuget\NuGet.targets - EndProjectSection -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.AspNet.Identity.Tests", "NHibernate.AspNet.Identity.Tests\NHibernate.AspNet.Identity.Tests.csproj", "{4AB55157-6F8F-423C-9C6F-A3A92B2101CE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Sample", "Sample", "{3FBC8B33-CB9E-48E4-8D3C-D17CFC61E71B}" @@ -19,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.AspNet.Web", "NH EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.AspNet.Web.Specs", "NHibernate.AspNet.Web.Specs\NHibernate.AspNet.Web.Specs.csproj", "{12933FB3-BE28-4F4F-A43A-0BE836788065}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate.SessionResolver", "NHibernate.SessionResolver\NHibernate.SessionResolver.csproj", "{63CD19ED-5019-493E-A4BB-1D19FED25C17}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -69,6 +65,16 @@ Global {12933FB3-BE28-4F4F-A43A-0BE836788065}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {12933FB3-BE28-4F4F-A43A-0BE836788065}.Release|Mixed Platforms.Build.0 = Release|Any CPU {12933FB3-BE28-4F4F-A43A-0BE836788065}.Release|x86.ActiveCfg = Release|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Debug|Any CPU.Build.0 = Debug|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Debug|x86.ActiveCfg = Debug|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Release|Any CPU.ActiveCfg = Release|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Release|Any CPU.Build.0 = Release|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/source/NHibernate.SessionResolver/ISessionResolver.cs b/source/NHibernate.SessionResolver/ISessionResolver.cs new file mode 100644 index 0000000..e7d228b --- /dev/null +++ b/source/NHibernate.SessionResolver/ISessionResolver.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace NHibernate +{ + public interface ISessionResolver + { + IEnumerable GetAllFactories(); + ISessionFactory GetFactoryFor(); + ISession GetCurrentSessionFor(); + } +} diff --git a/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj b/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj new file mode 100644 index 0000000..e0b2c14 --- /dev/null +++ b/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj @@ -0,0 +1,122 @@ + + + + + Debug + AnyCPU + {63CD19ED-5019-493E-A4BB-1D19FED25C17} + Library + Properties + NHibernate + NHibernate.SessionResolver + v4.5.1 + 512 + 1 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + True + False + True + False + False + False + True + True + True + True + True + True + True + True + False + True + False + True + False + False + False + False + True + False + True + True + True + False + False + + + + + + + + True + False + False + True + Full + %28none%29 + 0 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll + + + ..\..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll + + + ..\..\packages\NHibernate.4.0.3.4000\lib\net40\NHibernate.dll + + + ..\..\packages\Owin.1.0\lib\net40\Owin.dll + + + + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs b/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs new file mode 100644 index 0000000..0256e3f --- /dev/null +++ b/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs @@ -0,0 +1,36 @@ +using System.Threading.Tasks; +using Microsoft.Owin; +using NHibernate.Context; + +namespace NHibernate.Owin +{ + public class SessionMiddleware : OwinMiddleware + { + private readonly ISessionResolver _resolver; + + public SessionMiddleware(OwinMiddleware next, ISessionResolver resolver) + : base(next) + { + _resolver = resolver; + } + + public async override Task Invoke(IOwinContext context) + { + await Next.Invoke(context); + + foreach (var factory in _resolver.GetAllFactories()) + { + if (CurrentSessionContext.HasBind(factory)) + { + ISession session = CurrentSessionContext.Unbind(factory); + + if (session.Transaction.IsActive) + session.Transaction.Rollback(); + + if (session != null) + session.Close(); + } + } + } + } +} diff --git a/source/NHibernate.SessionResolver/Properties/AssemblyInfo.cs b/source/NHibernate.SessionResolver/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..76f078f --- /dev/null +++ b/source/NHibernate.SessionResolver/Properties/AssemblyInfo.cs @@ -0,0 +1,23 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("NHibernate.SessionResolver")] +[assembly: AssemblyDescription("Provides a registration point for ISession resolves that implements ISessionResolver interface.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("@milesibastos")] +[assembly: AssemblyProduct("NHibernate.SessionResolver")] +[assembly: AssemblyCopyright("Copyright © @milesibastos 2015")] +[assembly: AssemblyTrademark("@milesibastos")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("513b0f96-d5ac-4e0d-a04a-d4eb5ee5d2d8")] \ No newline at end of file diff --git a/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs b/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs new file mode 100644 index 0000000..24ac806 --- /dev/null +++ b/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs @@ -0,0 +1,73 @@ +using System.Collections.Generic; +using System.Linq; +using NHibernate.Cfg; +using NHibernate.Context; +using NHibernate.Engine; +using NHibernate.Owin; +using Owin; + +namespace NHibernate +{ + public class SessionFactoryBuilder + { + private readonly ISet _configurations; + + public SessionFactoryBuilder() + { + _configurations = new HashSet(); + } + + public void RegisterToBuild(Configuration configuration) + { + _configurations.Add(configuration); + } + + public void Build(IAppBuilder app) + { + var resolver = new DefaultSessionResolver(); + foreach (var configuration in _configurations) { + var factory = configuration.BuildSessionFactory(); + resolver.RegisterFactoryToResolve(factory); + } + + app.Use(resolver); + SessionResolver.SetResolver(resolver); + } + + private class DefaultSessionResolver : ISessionResolver + { + private static readonly ISet _factories; + + static DefaultSessionResolver() + { + _factories = new HashSet(); + } + + internal void RegisterFactoryToResolve(ISessionFactory factory) + { + _factories.Add(factory); + } + + public IEnumerable GetAllFactories() + { + return _factories; + } + + public ISessionFactory GetFactoryFor() + { + var type = typeof(TEntity); + var factory = _factories.SingleOrDefault(x => ((ISessionFactoryImplementor)x).TryGetEntityPersister(type.FullName) != null); + return factory; + } + + public ISession GetCurrentSessionFor() + { + var factory = GetFactoryFor(); + if (!CurrentSessionContext.HasBind(factory)) + CurrentSessionContext.Bind(factory.OpenSession()); + + return factory.GetCurrentSession(); + } + } + } +} diff --git a/source/NHibernate.SessionResolver/SessionResolver.cs b/source/NHibernate.SessionResolver/SessionResolver.cs new file mode 100644 index 0000000..02bd119 --- /dev/null +++ b/source/NHibernate.SessionResolver/SessionResolver.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using NHibernate.Context; +using NHibernate.Engine; + +namespace NHibernate +{ + public class SessionResolver + { + private static SessionResolver _instance = new SessionResolver(); + private ISessionResolver _current; + + public static ISessionResolver Current { get { return _instance.InnerCurrent; } } + + private ISessionResolver InnerCurrent { get { return _current; } } + + public static void RegisterFactoryToResolve(params ISessionFactory[] factory) + { + var resolver = new DefaultSessionResolver(); + foreach (var item in factory) + resolver.RegisterFactoryToResolve(item); + + _instance.InnerSetResolver(resolver); + } + + public static void SetResolver(ISessionResolver resolver) + { + _instance.InnerSetResolver(resolver); + } + + private void InnerSetResolver(ISessionResolver resolver) + { + Contract.Requires(resolver != null); + _current = resolver; + } + + private class DefaultSessionResolver : ISessionResolver + { + private static readonly ISet _factories; + + static DefaultSessionResolver() + { + _factories = new HashSet(); + } + + internal void RegisterFactoryToResolve(ISessionFactory factory) + { + _factories.Add(factory); + } + + public IEnumerable GetAllFactories() + { + return _factories; + } + + public ISessionFactory GetFactoryFor() + { + var type = typeof(TEntity); + var factory = _factories.SingleOrDefault(x => ((ISessionFactoryImplementor)x).TryGetEntityPersister(type.FullName) != null); + return factory; + } + + public ISession GetCurrentSessionFor() + { + var factory = GetFactoryFor(); + if (!CurrentSessionContext.HasBind(factory)) + CurrentSessionContext.Bind(factory.OpenSession()); + + return factory.GetCurrentSession(); + } + } + } +} diff --git a/source/NHibernate.SessionResolver/packages.config b/source/NHibernate.SessionResolver/packages.config new file mode 100644 index 0000000..0e30ead --- /dev/null +++ b/source/NHibernate.SessionResolver/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file From 1cbc33e76002371436c4b2db636680f8936d9bae Mon Sep 17 00:00:00 2001 From: Antonio Milesi Bastos Date: Mon, 4 May 2015 19:02:53 -0300 Subject: [PATCH 2/4] configure web sample --- .../AssemblyStartup.cs | 47 +++++++++++++++- .../NHibernate.AspNet.Web.Specs/LoginSpecs.cs | 7 ++- .../NHibernate.AspNet.Web.Specs.csproj | 8 +-- source/NHibernate.AspNet.Web.Specs/app.config | 3 ++ .../packages.config | 1 - .../NHibernate.AspNet.Web/App_Data/schema.sql | 10 ++-- .../App_Start/DataConfig.cs | 53 ------------------- .../Controllers/AccountController.cs | 3 +- .../NHibernate.AspNet.Web.csproj | 9 ++-- source/NHibernate.AspNet.Web/Startup.cs | 37 ++++++++++--- source/NHibernate.AspNet.Web/Web.config | 2 + source/NHibernate.AspNet.Web/packages.config | 1 - .../Owin/SessionMiddleware.cs | 2 +- 13 files changed, 99 insertions(+), 84 deletions(-) delete mode 100644 source/NHibernate.AspNet.Web/App_Start/DataConfig.cs diff --git a/source/NHibernate.AspNet.Web.Specs/AssemblyStartup.cs b/source/NHibernate.AspNet.Web.Specs/AssemblyStartup.cs index 22b840d..11ce062 100644 --- a/source/NHibernate.AspNet.Web.Specs/AssemblyStartup.cs +++ b/source/NHibernate.AspNet.Web.Specs/AssemblyStartup.cs @@ -1,8 +1,13 @@ using System; using System.IO; +using NHibernate.AspNet.Identity.Helpers; +using NHibernate.AspNet.Web.Models; using NUnit.Framework; -using SharpArch.NHibernate; using SpecsFor.Mvc; +using NHibernate.Mapping.ByCode; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; +using NHibernate.Context; namespace NHibernate.AspNet.Web.Specs { @@ -51,12 +56,50 @@ private void ConfigureDataBase() AppDomain.CurrentDomain.SetData( "DataDirectory", Path.Combine(root, @"SpecsForMvc.TestSite\App_Data")); - DataConfig.Configure(new SimpleSessionStorage()); + var internalTypes = new[] { + typeof(ApplicationUser) + }; + + var mapping = MappingHelper.GetIdentityMappings(internalTypes); + System.Diagnostics.Debug.WriteLine(mapping.AsString()); + + var config = new Configuration().Configure(); + config.AddDeserializedMapping(mapping, null); + BuildSchema(config); + + var factory = config.BuildSessionFactory(); + SessionResolver.RegisterFactoryToResolve(factory); } + private static void BuildSchema(Configuration config) + { + var path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), @"schema.sql"); + + // this NHibernate tool takes a configuration (with mapping info in) + // and exports a database schema from it + new SchemaExport(config) + .SetOutputFile(path) + .Create(true, true /* DROP AND CREATE SCHEMA */); + } + + [TearDown] public void TearDownTestRun() { + foreach (var factory in SessionResolver.Current.GetAllFactories()) + { + if (CurrentSessionContext.HasBind(factory)) + { + ISession session = CurrentSessionContext.Unbind(factory); + + if (session.Transaction.IsActive) + session.Transaction.Rollback(); + + if (session != null && session.IsOpen) + session.Close(); + } + } + _host.Shutdown(); } } diff --git a/source/NHibernate.AspNet.Web.Specs/LoginSpecs.cs b/source/NHibernate.AspNet.Web.Specs/LoginSpecs.cs index 7df1cd6..5ba3b89 100644 --- a/source/NHibernate.AspNet.Web.Specs/LoginSpecs.cs +++ b/source/NHibernate.AspNet.Web.Specs/LoginSpecs.cs @@ -4,7 +4,6 @@ using NHibernate.AspNet.Web.Controllers; using NHibernate.AspNet.Web.Models; using NUnit.Framework; -using SharpArch.NHibernate; using Should; using SpecsFor; using SpecsFor.Mvc; @@ -49,14 +48,14 @@ public class when_logging_in_with_valid_credentials : SpecsFor { protected override void Given() { - var userManager = new UserManager(new UserStore(NHibernateSession.Current)); + var session = SessionResolver.Current.GetCurrentSessionFor(); + var userManager = new UserManager(new UserStore(session)); using (var transaction = new TransactionScope()) { var user = new ApplicationUser() { UserName = "RealUserName" }; - var result = userManager.CreateAsync(user, "RealPassword"); + userManager.CreateAsync(user, "RealPassword").Wait(); transaction.Complete(); - result.Exception.ShouldBeNull(); } SUT.NavigateTo(c => c.Login("/Home/About")); diff --git a/source/NHibernate.AspNet.Web.Specs/NHibernate.AspNet.Web.Specs.csproj b/source/NHibernate.AspNet.Web.Specs/NHibernate.AspNet.Web.Specs.csproj index 91d5c6c..6722e0a 100644 --- a/source/NHibernate.AspNet.Web.Specs/NHibernate.AspNet.Web.Specs.csproj +++ b/source/NHibernate.AspNet.Web.Specs/NHibernate.AspNet.Web.Specs.csproj @@ -77,10 +77,6 @@ False ..\..\packages\MilesiBastos.SharpArch.Domain.4.0.3000\lib\NET40\SharpArch.Domain.dll - - False - ..\..\packages\MilesiBastos.SharpArch.NHibernate.4.0.3000\lib\NET40\SharpArch.NHibernate.dll - ..\..\packages\Should.1.1.20\lib\Should.dll @@ -171,6 +167,10 @@ {64ab1955-b578-497e-ac28-2d0641be44a7} NHibernate.AspNet.Web + + {63cd19ed-5019-493e-a4bb-1d19fed25c17} + NHibernate.SessionResolver + diff --git a/source/NHibernate.AspNet.Web.Specs/app.config b/source/NHibernate.AspNet.Web.Specs/app.config index d611c59..0fcf1f6 100644 --- a/source/NHibernate.AspNet.Web.Specs/app.config +++ b/source/NHibernate.AspNet.Web.Specs/app.config @@ -4,12 +4,15 @@
+ + NHibernate.Connection.DriverConnectionProvider, NHibernate NHibernate.Dialect.SQLiteDialect NHibernate.Driver.SQLite20Driver DefaultConnection on_close true + thread_static diff --git a/source/NHibernate.AspNet.Web.Specs/packages.config b/source/NHibernate.AspNet.Web.Specs/packages.config index 2ec8e08..8fb5419 100644 --- a/source/NHibernate.AspNet.Web.Specs/packages.config +++ b/source/NHibernate.AspNet.Web.Specs/packages.config @@ -11,7 +11,6 @@ - diff --git a/source/NHibernate.AspNet.Web/App_Data/schema.sql b/source/NHibernate.AspNet.Web/App_Data/schema.sql index a11df83..14bb012 100644 --- a/source/NHibernate.AspNet.Web/App_Data/schema.sql +++ b/source/NHibernate.AspNet.Web/App_Data/schema.sql @@ -34,15 +34,15 @@ create table AspNetUserRoles ( UserId TEXT not null, RoleId TEXT not null, - constraint FKFAADC1EF92E2FD93 foreign key (RoleId) references AspNetRoles, - constraint FKFAADC1EF526E4265 foreign key (UserId) references AspNetUsers + constraint FK86803B282B87AB2A foreign key (RoleId) references AspNetRoles, + constraint FK86803B28EA778823 foreign key (UserId) references AspNetUsers ) create table AspNetUserLogins ( UserId TEXT not null, LoginProvider TEXT, ProviderKey TEXT, - constraint FK6B768E3C526E4265 foreign key (UserId) references AspNetUsers + constraint FKEF896DAEEA778823 foreign key (UserId) references AspNetUsers ) create table AspNetRoles ( @@ -56,11 +56,11 @@ ClaimType TEXT, ClaimValue TEXT, UserId TEXT, - constraint FKE3450235526E4265 foreign key (UserId) references AspNetUsers + constraint FKF4F7D992EA778823 foreign key (UserId) references AspNetUsers ) create table ApplicationUser ( applicationuser_key TEXT not null, primary key (applicationuser_key), - constraint FKBF196D2F8745E746 foreign key (applicationuser_key) references AspNetUsers + constraint FK4376B148E75DF37 foreign key (applicationuser_key) references AspNetUsers ) diff --git a/source/NHibernate.AspNet.Web/App_Start/DataConfig.cs b/source/NHibernate.AspNet.Web/App_Start/DataConfig.cs deleted file mode 100644 index 806e34d..0000000 --- a/source/NHibernate.AspNet.Web/App_Start/DataConfig.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using NHibernate.AspNet.Identity; -using NHibernate.AspNet.Identity.Helpers; -using NHibernate.AspNet.Web.Models; -using NHibernate.Cfg; -using NHibernate.Mapping.ByCode; -using NHibernate.Tool.hbm2ddl; -using SharpArch.Domain.DomainModel; -using SharpArch.NHibernate; -using System.Collections.Generic; - -namespace NHibernate.AspNet.Web -{ - public class DataConfig - { - public static void Configure(ISessionStorage storage) - { - var internalTypes = new[] { - typeof(ApplicationUser) - }; - - var mapping = MappingHelper.GetIdentityMappings(internalTypes); - System.Diagnostics.Debug.WriteLine(mapping.AsString()); - - var configuration = NHibernateSession.Init(storage, mapping); - BuildSchema(configuration); - } - - private static void DefineBaseClass(ConventionModelMapper mapper, System.Type[] baseEntityToIgnore) - { - if (baseEntityToIgnore == null) return; - mapper.IsEntity((type, declared) => - baseEntityToIgnore.Any(x => x.IsAssignableFrom(type)) && - !baseEntityToIgnore.Any(x => x == type) && - !type.IsInterface); - mapper.IsRootEntity((type, declared) => baseEntityToIgnore.Any(x => x == type.BaseType)); - } - - private static void BuildSchema(Configuration config) - { - var path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), @"schema.sql"); - - // this NHibernate tool takes a configuration (with mapping info in) - // and exports a database schema from it - new SchemaExport(config) - .SetOutputFile(path) - .Create(true, true /* DROP AND CREATE SCHEMA */); - } - - } -} \ No newline at end of file diff --git a/source/NHibernate.AspNet.Web/Controllers/AccountController.cs b/source/NHibernate.AspNet.Web/Controllers/AccountController.cs index a49dbb5..df85834 100644 --- a/source/NHibernate.AspNet.Web/Controllers/AccountController.cs +++ b/source/NHibernate.AspNet.Web/Controllers/AccountController.cs @@ -5,7 +5,6 @@ using Microsoft.Owin.Security; using NHibernate.AspNet.Identity; using NHibernate.AspNet.Web.Models; -using SharpArch.NHibernate; namespace NHibernate.AspNet.Web.Controllers { @@ -13,7 +12,7 @@ namespace NHibernate.AspNet.Web.Controllers public class AccountController : Controller { public AccountController() - : this(new UserManager(new UserStore(NHibernateSession.Current))) + : this(new UserManager(new UserStore(SessionResolver.Current.GetCurrentSessionFor()))) { } diff --git a/source/NHibernate.AspNet.Web/NHibernate.AspNet.Web.csproj b/source/NHibernate.AspNet.Web/NHibernate.AspNet.Web.csproj index c1b7af0..5168b62 100644 --- a/source/NHibernate.AspNet.Web/NHibernate.AspNet.Web.csproj +++ b/source/NHibernate.AspNet.Web/NHibernate.AspNet.Web.csproj @@ -112,10 +112,6 @@ False ..\..\packages\MilesiBastos.SharpArch.Domain.4.0.3000\lib\NET40\SharpArch.Domain.dll - - False - ..\..\packages\MilesiBastos.SharpArch.NHibernate.4.0.3000\lib\NET40\SharpArch.NHibernate.dll - @@ -186,7 +182,6 @@ - @@ -274,6 +269,10 @@ {c620faae-f1b6-479e-9959-c46c20ed0a8a} NHibernate.AspNet.Identity + + {63cd19ed-5019-493e-a4bb-1d19fed25c17} + NHibernate.SessionResolver + 10.0 diff --git a/source/NHibernate.AspNet.Web/Startup.cs b/source/NHibernate.AspNet.Web/Startup.cs index 1c2bb37..c24356e 100644 --- a/source/NHibernate.AspNet.Web/Startup.cs +++ b/source/NHibernate.AspNet.Web/Startup.cs @@ -1,6 +1,11 @@ -using Microsoft.Owin; +using System; +using System.IO; +using Microsoft.Owin; +using NHibernate.AspNet.Identity.Helpers; +using NHibernate.AspNet.Web.Models; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; using Owin; -using SharpArch.NHibernate.Web.Mvc; [assembly: OwinStartupAttribute(typeof(NHibernate.AspNet.Web.Startup))] namespace NHibernate.AspNet.Web @@ -10,13 +15,33 @@ public partial class Startup public void Configuration(IAppBuilder app) { ConfigureAuth(app); - ConfigureData(); + + var internalTypes = new[] { + typeof(ApplicationUser) + }; + + var mapping = MappingHelper.GetIdentityMappings(internalTypes); + + var config = new Configuration().Configure(); + config.AddDeserializedMapping(mapping, null); + BuildSchema(config); + + var builder = new SessionFactoryBuilder(); + builder.RegisterToBuild(config); + // Register a second config for multi data bases + // builder.RegisterToBuild(secondconfig); + builder.Build(app); } - private static void ConfigureData() + private static void BuildSchema(Configuration config) { - var storage = new WebSessionStorage(System.Web.HttpContext.Current.ApplicationInstance); - DataConfig.Configure(storage); + var path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), @"schema.sql"); + + // this NHibernate tool takes a configuration (with mapping info in) + // and exports a database schema from it + new SchemaExport(config) + .SetOutputFile(path) + .Create(true, true /* DROP AND CREATE SCHEMA */); } } } diff --git a/source/NHibernate.AspNet.Web/Web.config b/source/NHibernate.AspNet.Web/Web.config index f24cde9..4117471 100644 --- a/source/NHibernate.AspNet.Web/Web.config +++ b/source/NHibernate.AspNet.Web/Web.config @@ -5,11 +5,13 @@ + NHibernate.Connection.DriverConnectionProvider, NHibernate NHibernate.Dialect.SQLiteDialect NHibernate.Driver.SQLite20Driver DefaultConnection on_close true + web diff --git a/source/NHibernate.AspNet.Web/packages.config b/source/NHibernate.AspNet.Web/packages.config index beae681..a1dd6ff 100644 --- a/source/NHibernate.AspNet.Web/packages.config +++ b/source/NHibernate.AspNet.Web/packages.config @@ -25,7 +25,6 @@ - diff --git a/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs b/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs index 0256e3f..89353bf 100644 --- a/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs +++ b/source/NHibernate.SessionResolver/Owin/SessionMiddleware.cs @@ -27,7 +27,7 @@ public async override Task Invoke(IOwinContext context) if (session.Transaction.IsActive) session.Transaction.Rollback(); - if (session != null) + if (session != null && session.IsOpen) session.Close(); } } From 327fe5db609b9ecd2c6ee5cefe30554f0b258d1c Mon Sep 17 00:00:00 2001 From: Antonio Milesi Bastos Date: Tue, 5 May 2015 16:57:18 -0300 Subject: [PATCH 3/4] eliminating duplicate code --- .../SessionFactoryBuilder.cs | 45 +------------------ 1 file changed, 2 insertions(+), 43 deletions(-) diff --git a/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs b/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs index 24ac806..cffa26d 100644 --- a/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs +++ b/source/NHibernate.SessionResolver/SessionFactoryBuilder.cs @@ -1,8 +1,5 @@ using System.Collections.Generic; -using System.Linq; using NHibernate.Cfg; -using NHibernate.Context; -using NHibernate.Engine; using NHibernate.Owin; using Owin; @@ -24,50 +21,12 @@ public void RegisterToBuild(Configuration configuration) public void Build(IAppBuilder app) { - var resolver = new DefaultSessionResolver(); foreach (var configuration in _configurations) { var factory = configuration.BuildSessionFactory(); - resolver.RegisterFactoryToResolve(factory); + SessionResolver.RegisterFactoryToResolve(factory); } - app.Use(resolver); - SessionResolver.SetResolver(resolver); - } - - private class DefaultSessionResolver : ISessionResolver - { - private static readonly ISet _factories; - - static DefaultSessionResolver() - { - _factories = new HashSet(); - } - - internal void RegisterFactoryToResolve(ISessionFactory factory) - { - _factories.Add(factory); - } - - public IEnumerable GetAllFactories() - { - return _factories; - } - - public ISessionFactory GetFactoryFor() - { - var type = typeof(TEntity); - var factory = _factories.SingleOrDefault(x => ((ISessionFactoryImplementor)x).TryGetEntityPersister(type.FullName) != null); - return factory; - } - - public ISession GetCurrentSessionFor() - { - var factory = GetFactoryFor(); - if (!CurrentSessionContext.HasBind(factory)) - CurrentSessionContext.Bind(factory.OpenSession()); - - return factory.GetCurrentSession(); - } + app.Use(SessionResolver.Current); } } } From b790d1d904503b9a7e44812b98a6ea58ce1e0d48 Mon Sep 17 00:00:00 2001 From: Antonio Milesi Bastos Date: Tue, 5 May 2015 17:19:38 -0300 Subject: [PATCH 4/4] fix build to code contracts --- .../NHibernate.SessionResolver.csproj | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj b/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj index e0b2c14..d930034 100644 --- a/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj +++ b/source/NHibernate.SessionResolver/NHibernate.SessionResolver.csproj @@ -72,6 +72,49 @@ TRACE prompt 4 + True + False + True + False + False + False + True + True + True + True + True + True + True + True + False + True + False + True + False + False + False + False + True + False + True + True + True + False + False + + + + + + + + True + False + False + True + Full + %28none%29 + 0