SQL Azure Federation with S#arp Architecture - nhibernate

I’m using S#harp Architecture, has anyone found a way to access SQL Azure Federations with it?
I am aware that the following command must be executed outside of the transaction since SQL Azure does not allow “use Federation” statements within a transaction.
use Federation CustomerFederation (CustomerID=2) with reset, filtering=on
GO
<some sql statement...>
GO
There is another post on here that shows an example with creating a custom NHibernate Session class, but how can this be accomplished/extended using S#arp Architecture?
I'm also aware that there are other sharding options to SQL Azure Federation such as NHibernate.Shards or a multi-tenant S#arp Architecture extension but, please, keep to answering the question as opposed to providing other options.
I know I’m not the only person using S#arp Architecture and SQL Azure Federations and Google hasn't provided much so if anyone else out their has found a solution then, please, share.

Since no one has yet to respond to my post I am responding to it after several days of research. I was able to integrated with S#harp with 1 interface and 3 classes (I was hoping their would be an out of the box solution?).
The code provided below can be copied and pasted to any application and it should just work. The only exception is the FederationSessionHelper class. This is specific to each application as to were you are getting the info may change. I have an app setting section within my web.config that has the Federation name etc. Also, when the user authenticates, I parse the root url they are comming from then query the Federation Root to find out what tenant they are (I have a custom Tenant table I created). I then place the tenant ID in session under key "FederationKeyValue_Key" which will then be used in the FederationSession class to build the Use Federation statement.
/// <summary>
/// Interface used to retrieve app specific info about your federation.
/// </summary>
public interface IFederationSessionHelper
{
string ConnectionString { get; }
string FederationName { get; }
string DistributionName { get; }
string FederationKeyValue { get; }
}
/// <summary>
/// This is were you would get things specific for your application. I have 3 items in the web.config file and 1 stored in session. You could easily change this to get them all from the repository or wherever meets the needs of your application.
/// </summary>
public class FederationSessionHelper : IFederationSessionHelper
{
private const string ConnectionStringKey = "ConnectionString_Key";
private const string FederationNameKey = "FederationName_Key";
private const string DistributionNameKey = "DistributionName_Key";
private const string FederationKeyValueKey = "FederationKeyValue_Key";
public string ConnectionString { get { return ConfigurationManager.ConnectionStrings[ConnectionStringKey].ConnectionString; } }
public string FederationName { get { return ConfigurationManager.AppSettings[FederationNameKey]; } }
public string DistributionName { get { return ConfigurationManager.AppSettings[DistributionNameKey]; } }
//When user authenitcates, retrieve key value and store in session. This will allow to retrieve here.
public string FederationKeyValue { get { return Session[FederationKeyValueKey]; } }
}
/// <summary>
/// This is were the magic begins and where the integration with S#arp occurs. It manually creates a Sql Connections and adds it the S#arps storage. It then runs the Use Federation command and leaves the connection open. So now when you use an NhibernateSession.Current it will work with Sql Azure Federation.
/// </summary>
public class FederationSession : IDisposable
{
private SqlConnection _sqlConnection;
public void Init(string factoryKey,
string federationName,
string distributionName,
string federationKeyValue,
bool doesFilter,
string connectionString)
{
var sql = string.Format("USE FEDERATION {0}({1} = '{2}') WITH RESET, FILTERING = {3};", federationName, distributionName, federationKeyValue, (doesFilter) ? "ON" : "OFF");
_sqlConnection = new SqlConnection(connectionString);
_sqlConnection.Open();
var session = NHibernateSession.GetSessionFactoryFor(factoryKey).OpenSession(_sqlConnection);
NHibernateSession.Storage.SetSessionForKey(factoryKey, session);
var query = NHibernateSession.Current.CreateSQLQuery(sql);
query.UniqueResult();
}
public void Dispose()
{
if (_sqlConnection != null && _sqlConnection.State != ConnectionState.Closed)
_sqlConnection.Close();
}
}
/// <summary>
/// This was just icing on the cake. It inherits from S#arps TransactionAttribute and calls the FederationSession helper to open a connection. That way all you need to do in decorate your controller with the newly created [FederationTransaction] attribute and thats it.
/// </summary>
public class FederationTransactionAttribute : TransactionAttribute
{
private readonly string _factoryKey = string.Empty;
private bool _doesFilter = true;
/// <summary>
/// When used, assumes the <see cref = "factoryKey" /> to be NHibernateSession.DefaultFactoryKey
/// </summary>
public FederationTransactionAttribute()
{ }
/// <summary>
/// Overrides the default <see cref = "factoryKey" /> with a specific factory key
/// </summary>
public FederationTransactionAttribute(string factoryKey = "", bool doesFilter = true)
: base(factoryKey)
{
_factoryKey = factoryKey;
_doesFilter = doesFilter;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var federationSessionHelper = ServiceLocator.Current.GetInstance<IFederationSessionHelper>();
var factoryKey = GetEffectiveFactoryKey();
new FederationSession().Init(factoryKey,
federationSessionHelper.FederationName,
federationSessionHelper.DistributionName,
federationSessionHelper.FederationKeyValue,
_doesFilter,
federationSessionHelper.ConnectionString);
NHibernateSession.CurrentFor(factoryKey).BeginTransaction();
}
private string GetEffectiveFactoryKey()
{
return String.IsNullOrEmpty(_factoryKey) ? SessionFactoryKeyHelper.GetKey() : _factoryKey;
}
}
Now I am able to replace S#arp's [Transaction] attribute with the newly created [FederationTransaction] as follows:
[HttpGet]
[FederationTransaction]
public ActionResult Index()
{
var viewModel = NHibernateSession.Current.QueryOver<SomeDemoModel>().List()
return View(viewModel);
}
None of the code within the Controller needs to know that its using Sql Azure Federation. It should all just work.
Any thoughts? Anyone found a better solution? Please, share.

Related

Google reCAPTCHA Enterprise with ASP.NET CORE 3.1

After some hours spent searching the web for implementation of Google reCAPTCHA Enterprise with ASP.NET CORE 3.1, I must, unfortunately, admit that I was not able to find anything I could use in my project.
I've read the docs following the official site, but in the end, I'm still stucking for a clean implementation.
In ASP.NET Monsters there is an example, but targeting reCAPTCHA V3 and not reCAPTCHA enterprise.
There is also a nice post here Google ReCaptcha v3 server-side validation using ASP.NET Core 5.0, but again on reCAPTCHA V3.
Any help is appreciated.
So for me i needed to implement google recapthca with dotnet 5 using an angular front end. I am sure you can replace the angular front end with the native javascript instead, but this took me hours of investigating so hopefully it will help people.
First i had to enable reCAPTCHA Enterprise, to do this i went to https://cloud.google.com/recaptcha-enterprise/ and then clicked on the "go to console" button. This took me to my Google Cloud Platform. From here i needed to create a key, fill in the options and save. This key will be referred to as your SITE_KEY.
-- IF YOU ARE USING ANGULAR, READ THIS, ELSE SKIP THIS STEP AND IMPLEMENT IT YOURSELF
On the client i used ng-recaptcha, you can find it here
To implement this component, i added this import to my app.module.ts
import { RECAPTCHA_V3_SITE_KEY } from 'ng-recaptcha';
and this to the providers section
{
provide: RECAPTCHA_V3_SITE_KEY,
useValue: SITE_KEY_GOES_HERE
}
On my component, when the submit button is pressed, i used the ReCaptchaV3Service from the library above. My code looks like this
this.recaptchaV3Service.execute(YOUR_ACTION_NAME).subscribe((recaptchaResponse) => {
// now call your api on the server and make sure you pass the recaptchaResponse string to your method
});
The text YOUR_ACTION_NAME is the name of the action you are doing. In my case i passed 'forgotPassword' as this parameter.
-- END OF ANGULAR PART
Now on the server, first i included this into my project
<PackageReference Include="Google.Cloud.RecaptchaEnterprise.V1" Version="1.2.0" />
Once included in my service, i found it easier to create a service in my code, which is then injected. I also created a basic options class, which is injected into my service, it can be injected into other places if needed.
RecaptchaOptions.cs
public class RecaptchaOptions
{
public string Type { get; set; }
public string ProjectId { get; set; }
public string PrivateKeyId { get; set; }
public string PrivateKey { get; set; }
public string ClientEmail { get; set; }
public string ClientId { get; set; }
public string SiteKey { get { return YOUR_SITE_KEY; } }
/// <summary>
/// 0.1 is worst (probably a bot), 0.9 is best (probably human)
/// </summary>
public float ExceptedScore { get { return (float)0.7; } }
}
Some of these values are not used, but i have added them for the future, encase i do use them.
Then i have created my service, which looks like so (i have created an interface for injecting and testing)
IRecaptchaService.cs
public interface IRecaptchaService
{
Task<bool> VerifyAsync(string recaptchaResponse, string expectedAction);
}
RecaptchaService.cs
public class RecaptchaService : IRecaptchaService
{
#region IRecaptchaService
/// <summary>
/// Check our recaptcha
/// </summary>
/// <param name="recaptchaResponse">The response from the client</param>
/// <param name="expectedAction">The action that we are expecting</param>
/// <returns></returns>
public async Task<bool> VerifyAsync(string recaptchaResponse, string expectedAction)
{
// initialize request argument(s)
var createAssessmentRequest = new CreateAssessmentRequest
{
ParentAsProjectName = ProjectName.FromProject(_recaptchaOptions.ProjectId),
Assessment = new Assessment()
{
Event = new Event()
{
SiteKey = _recaptchaOptions.SiteKey,
Token = recaptchaResponse
}
},
};
// client
var cancellationToken = new CancellationToken();
var client = RecaptchaEnterpriseServiceClient.Create();
// Make the request
try
{
var response = await client.CreateAssessmentAsync(createAssessmentRequest, cancellationToken);
return response.TokenProperties.Valid && response.TokenProperties.Action.Equals(expectedAction) && response.RiskAnalysis?.Score >= _recaptchaOptions.ExceptedScore;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
#endregion
private RecaptchaOptions _recaptchaOptions;
public RecaptchaService(RecaptchaOptions recaptchaOptions)
{
_recaptchaOptions = recaptchaOptions;
}
}
Now my api endpoint, i inject this service and call it. Here is an example API method that calls the recaptchaService.
public async Task<IActionResult> ForgotPasswordAsync([FromBody] ForgotPasswordModel model)
{
// check our recaptchaResponse
var verified = await _recaptchaService.VerifyAsync(model.RecaptchaResponse, "forgotPassword");
if (!verified)
throw new ApplicationException("Recaptcha failed, please try again");
// successful, carry on
}
Hope this helps everyone, if there are any questions, please ask and i will edit this and update it with anything i have missed.

Override AuthorizeAttribute in ASP.Net Core and respond Json status

I'm moving from ASP.Net Framework to ASP.Net Core.
In ASP.Net Framework with Web API 2 project, I can customize AuthorizeAttribute like this :
public class ApiAuthorizeAttribute : AuthorizationFilterAttribute
{
#region Methods
/// <summary>
/// Override authorization event to do custom authorization.
/// </summary>
/// <param name="httpActionContext"></param>
public override void OnAuthorization(HttpActionContext httpActionContext)
{
// Retrieve email and password.
var accountEmail =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Email"))
.Select(x => x.Value.FirstOrDefault())
.FirstOrDefault();
// Retrieve account password.
var accountPassword =
httpActionContext.Request.Headers.Where(
x =>
!string.IsNullOrEmpty(x.Key) &&
x.Key.Equals("Password"))
.Select(x => x.Value.FirstOrDefault()).FirstOrDefault();
// Account view model construction.
var filterAccountViewModel = new FilterAccountViewModel();
filterAccountViewModel.Email = accountEmail;
filterAccountViewModel.Password = accountPassword;
filterAccountViewModel.EmailComparision = TextComparision.Equal;
filterAccountViewModel.PasswordComparision = TextComparision.Equal;
// Find the account.
var account = RepositoryAccount.FindAccount(filterAccountViewModel);
// Account is not found.
if (account == null)
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
return;
}
// Role is not defined which means the request is allowed.
if (_roles == null)
return;
// Role is not allowed
if (!_roles.Any(x => x == account.Role))
{
// Treat the account as unthorized.
httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
// Store the requester information in action argument.
httpActionContext.ActionArguments["Account"] = account;
}
#endregion
#region Properties
/// <summary>
/// Repository which provides function to access account database.
/// </summary>
public IRepositoryAccount RepositoryAccount { get; set; }
/// <summary>
/// Which role can be allowed to access server.
/// </summary>
private readonly byte[] _roles;
#endregion
#region Constructor
/// <summary>
/// Initialize instance with default settings.
/// </summary>
public ApiAuthorizeAttribute()
{
}
/// <summary>
/// Initialize instance with allowed role.
/// </summary>
/// <param name="roles"></param>
public ApiAuthorizeAttribute(byte[] roles)
{
_roles = roles;
}
#endregion
}
In my customized AuthorizeAttribute, I can check whether account is valid or not and return HttpStatusCode with message to client.
I'm trying to do the samething in ASP.Net Core, but no OnAuthorization for me to override.
How can I achieve the same thing as in ASP.Net Framework ?
Thank you,
You're approaching this incorrectly. It never was really encouraged to write custom attributes for this, or to extend existing. With ASP.NET Core roles are still apart of the system for backwards compatibility but they are now also discouraged.
There is a great 2 part series on some of the driving architecture changes and the way that this is and should be utilized found here. If you want to still rely on roles you can do so, but I would suggest using policies.
To wire a policy do the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy(nameof(Policy.Account),
policy => policy.Requirements.Add(new AccountRequirement()));
});
services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}
I created a Policy enum for convenience.
public enum Policy { Account };
Decorate entry points as such:
[
HttpPost,
Authorize(Policy = nameof(Policy.Account))
]
public async Task<IActionResult> PostSomething([FromRoute] blah)
{
}
The AccountRequirement is just a placeholder, it needs to implement the IAuthorizationRequirement interface.
public class AccountRequirement: IAuthorizationRequirement { }
Now we simply need to create a handler and wire this up for DI.
public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{
// Your logic here... or anything else you need to do.
if (context.User.IsInRole("fooBar"))
{
// Call 'Succeed' to mark current requirement as passed
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
Additional Resources
ASP.NET Core Security -- All the things
My comment looks bad as a comment so I post an answer but only useful if you use MVC:
// don't forget this
services.AddSingleton<IAuthorizationHandler, MyCustomAuthorizationHandler>();
services
.AddMvc(config => { var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser() .AddRequirements(new[] { new MyCustomRequirement() })
.Build(); config.Filters.Add(new AuthorizeFilter(policy)); })
I also noticed that async keyword is superfluous for "HandleRequirementAsync" signature, in question code. And I guess that returning Task.CompletedTask could be good.

How to properly implement the Strategy Pattern with two interfaces?

I have created a service data access layer where there are multiple databases where data needs to come from.
I was doing fine with one database where I defined the memberRepository that contained member details. However, now I have to get session-related details that are stored in another database.
OprationContracts:
IMemberServices contains GetLoggedInBuddies(int profileID);
ISessionServices contains GetProfileIDFromSessionID(string sessionID);
My service class:
public class MemberService : IMemberService, ISessionServices
{
#region Strategy pattern configuration
//
// Member repo
//
private MemberRepository memberRepository;
public MemberService()
: this(new MemberRepository())
{ }
public MemberService(MemberRepository memberRepository)
{
this.memberRepository = memberRepository;
}
//
// Session repo
//
private SessionRepository sessionRepository;
public MemberService() : this(new SessionRepository()){}
public MemberService(SessionRepository sessionRepository)
{
this.sessionRepository = sessionRepository;
}
#endregion
/// <summary>
/// Session-related details are maintained in the Secondary database
/// </summary>
/// <param name="sessionID"></param>
/// <returns></returns>
public int GetProfileIDFromSessionID(string sessionID)
{
int sessionProfileID = sessionRepository.GetProfileDetailsFromSessionID(sessionRepository);
return sessionProfileID;
}
/// <summary>
/// Try profileID = 1150526
/// </summary>
/// <param name="profileID"></param>
public void GetLoggedInBuddies(int profileID)
{
memberRepository.GetLoggedInBuddies(profileID);
//return memberRepository.GetLoggedInBuddies(profileID);
}
The issue is that in the // Session Repo section, as I already have a constructor defined. I get that.
So basically in each method I want to do something like
MemberService useSessionRepo = new MemberService(SessionRepository);
useSessionRepo.GetProfileDetailsFromSessionID(...);
MemberService useMemberRepo = new MemberService(MemberRepository);
useMemberRepo.GetLoggedInBuddies(...);
Just need a hand putting this together.
Thanks.
I'm not sure about your issue, but you can use a ctor without param, and with param for each repo.
public MemberService()
{
this.memberRepository = new MemberRepository();
this.sessionRepository = new SessionRepository();
}
I created a central repository that accepts the name of the connection string of the database I want to connect to.
public abstract class DatabaseRepository : BaseRepository
{
static IDbConnection connection;
/// <summary>
/// Handles db connectivity as Dapper assumes an existing connection for all functions
/// Since this app uses three databases, pass in the connection string for the required db.
/// </summary>
/// <returns></returns>
protected static IDbConnection OpenConnection(string connectionStringName)
{
try
{
connection = new SqlConnection(WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString);
//connection = SqlMapperUtil.GetOpenConnection(connectionStringName); // if we want to use the Dapper utility methods
connection.Open();
return connection;
}
catch (Exception ex)
{
ErrorLogging.Instance.Fatal(ex); // uses singleton for logging
return null;
}
}
.
.
.
Then in my service library, I make the connection to the appropriate db and perform whatever queries I need:
using (IDbConnection connection = OpenConnection("FirstDBConnectionString")) { ...

WCF Data Service Partial class property on the client causes SaveContext exceptions

I have a WCF Data Service running that is exposing an EDM. There are several properties I needed on the client side, that the database doesn't need to know about. After setting all that up I got to testing the SaveContext method and get this error on the server "Error processing request stream. The property name 'CanDelete' specified for type 'DataModels.Customer' is not valid."
Is there a way to tell WCF Data Services on the client side to ignore this property? Or should I move to RIA Serivces? I've read that setting the property to internal will do this, but I need the property for binding and I have the client UI code in a different project (de-coupling my SL applications from my data service).
on the client I have:
public partial class Customer
{
private bool canDelete;
/// <summary>
/// Gets or sets a value indicating whether this instance can be deleted.
/// </summary>
/// <value>
/// <c>true</c> if this instance can delete; otherwise, <c>false</c>.
private bool canDelete;
/// <summary>
/// Gets or sets a value indicating whether this instance can be deleted.
/// </summary>
/// <value>
/// <c>true</c> if this instance can delete; otherwise, <c>false</c>.
/// </value>
public bool CanDelete
{
get
{
return this.canDelete;
}
set
{
if (this.canDelete != value)
{
this.canDelete = value;
this.OnPropertyChanged("CanDelete");
}
}
}
}
I had the exact same problem and adapted some code below from
extending partial designer classes
It simply involves hooking the WritingEntity Event inside a partial class of the Context.
I added my own attribute (IgnorePropertyAttribute) so I could attach it to other properties.
Would of course be nice if the attribute wasnt inserted in the first place but this worked for me
public sealed class IgnorePropertyAttribute : Attribute
{
}
...
partial void OnContextCreated()
{
this.WritingEntity += MyDataContext_WritingEntity;
}
private void MyDataContext_WritingEntity(object sender, System.Data.Services.Client.ReadingWritingEntityEventArgs e)
{
//
foreach (XElement node in e.Data.Elements())
{
if (node != null && node.Name.LocalName == "content")
{
foreach (XElement el in node.Elements())
{
if (el.Name.LocalName == "properties")
{
foreach (XElement prop in el.Elements())
{
if(e.Entity.GetType().GetProperty(prop.Name.LocalName).GetCustomAttributes(typeof(IgnorePropertyAttribute), true).Length > 0)
{
prop.Remove();
}
}
}
}
}
}
}

NHibernate - good complete working Helper class for managing SessionFactory/Session [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
can anyone provide/refer a proper OO type helper class for managing a singleton of the SessionFactory and then also for managing Sessions?
Check out Billy McCafferty's work. His earlier version had some limitations, you'll need to correct the error handling around closing and flushing, and I'm not sure i have it right but I will post how I modified his stuff.
Billy is also working on a new framework that uses MVC & nHibernate called S#arp Architechure which I'm currently using, and so far so good.
Anyways here's my modified version of his code. I make no guanrtees on accuracy or completness and you are using this on your own risk. If you use this make sure you close the session out. If you have any questions drop me an email [joshua][dot][berke] at [gmail...you know the rest].
/// <summary>
/// Handles creation and management of sessions and transactions. It is a singleton because
/// building the initial session factory is very expensive. Inspiration for this class came
/// from Chapter 8 of Hibernate in Action by Bauer and King. Although it is a sealed singleton
/// you can use TypeMock (http://www.typemock.com) for more flexible testing.
/// </summary>
public sealed class NHibernateSessionManager
{
private const string DefaultConfigFile = "DefaultAppWeb.Config";
private static readonly object _syncRoot = new object();
#region Thread-safe, lazy Singleton
/// <summary>
/// This is a thread-safe, lazy singleton. See http://www.yoda.arachsys.com/csharp/singleton.html
/// for more details about its implementation.
/// </summary>
public static NHibernateSessionManager Instance
{
get
{
return Nested.NHibernateSessionManager;
}
}
/// <summary>
/// Private constructor to enforce singleton
/// </summary>
private NHibernateSessionManager() { }
/// <summary>
/// Assists with ensuring thread-safe, lazy singleton
/// </summary>
private class Nested
{
static Nested() { }
internal static readonly NHibernateSessionManager NHibernateSessionManager =
new NHibernateSessionManager();
}
#endregion
/// <summary>
/// This method attempts to find a session factory stored in <see cref="sessionFactories" />
/// via its name; if it can't be found it creates a new one and adds it the hashtable.
/// </summary>
/// <param name="sessionFactoryConfigPath">Path location of the factory config</param>
private ISessionFactory GetSessionFactoryFor(string sessionFactoryConfigPath)
{
Check.Require(!string.IsNullOrEmpty(sessionFactoryConfigPath),
"sessionFactoryConfigPath may not be null nor empty");
// Attempt to retrieve a stored SessionFactory from the hashtable.
ISessionFactory sessionFactory;// = (ISessionFactory)sessionFactories[sessionFactoryConfigPath];
// try and get a session factory if we don't find one create it
lock (_syncRoot)
{
if (!sessionFactories.TryGetValue(sessionFactoryConfigPath, out sessionFactory))
{
Configuration cfg = new Configuration();
if (sessionFactoryConfigPath != DefaultConfigFile)
{
Check.Require(File.Exists(sessionFactoryConfigPath),
"The config file at '" + sessionFactoryConfigPath + "' could not be found");
cfg.Configure(sessionFactoryConfigPath);
}
else
{
cfg.Configure();
}
// Now that we have our Configuration object, create a new SessionFactory
sessionFactory = cfg.BuildSessionFactory();
Check.Ensure(sessionFactory != null, "sessionFactory is null and was not built");
sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);
}
}
return sessionFactory;
}
/// <summary>
/// Allows you to register an interceptor on a new session. This may not be called if there is already
/// an open session attached to the HttpContext. If you have an interceptor to be used, modify
/// the HttpModule to call this before calling BeginTransaction().
/// </summary>
public void RegisterInterceptorOn(string sessionFactoryConfigPath, IInterceptor interceptor)
{
ISession session = (ISession)ContextSessions[sessionFactoryConfigPath];
if (session != null && session.IsOpen)
{
throw new CacheException("You cannot register an interceptor once a session has already been opened");
}
GetSessionFrom(sessionFactoryConfigPath, interceptor);
}
public ISession GetSessionFrom(string sessionFactoryConfigPath)
{
return GetSessionFrom(sessionFactoryConfigPath, null);
}
/// <summary>
/// Gets or creates an ISession using the web / app config file.
/// </summary>
/// <returns></returns>
public ISession GetSessionFrom()
{
return GetSessionFrom(DefaultConfigFile, null);
}
/// <summary>
/// Gets a session with or without an interceptor. This method is not called directly; instead,
/// it gets invoked from other public methods.
/// </summary>
private ISession GetSessionFrom(string sessionFactoryConfigPath, IInterceptor interceptor)
{
var allSessions = ContextSessions;
ISession session = null;
if (!allSessions.TryGetValue(sessionFactoryConfigPath, out session))
{
if (interceptor != null)
{
session = GetSessionFactoryFor(sessionFactoryConfigPath).OpenSession(interceptor);
}
else
{
session = GetSessionFactoryFor(sessionFactoryConfigPath).OpenSession();
}
allSessions[sessionFactoryConfigPath] = session;
}
//session.FlushMode = FlushMode.Always;
Check.Ensure(session != null, "session was null");
return session;
}
/// <summary>
/// Flushes anything left in the session and closes the connection.
/// </summary>
public void CloseSessionOn(string sessionFactoryConfigPath)
{
ISession session;
if (ContextSessions.TryGetValue(sessionFactoryConfigPath, out session))
{
if (session.IsOpen)
{
session.Flush();
session.Close();
}
ContextSessions.Remove(sessionFactoryConfigPath);
}
}
public ITransaction BeginTransactionOn(string sessionFactoryConfigPath)
{
ITransaction transaction;
if (!ContextTransactions.TryGetValue(sessionFactoryConfigPath, out transaction))
{
transaction = GetSessionFrom(sessionFactoryConfigPath).BeginTransaction();
ContextTransactions.Add(sessionFactoryConfigPath, transaction);
}
return transaction;
}
public void CommitTransactionOn(string sessionFactoryConfigPath)
{
try
{
if (HasOpenTransactionOn(sessionFactoryConfigPath))
{
ITransaction transaction = (ITransaction)ContextTransactions[sessionFactoryConfigPath];
transaction.Commit();
ContextTransactions.Remove(sessionFactoryConfigPath);
}
}
catch (HibernateException he)
{
try
{
RollbackTransactionOn(sessionFactoryConfigPath);
}
finally
{
throw he;
}
}
}
public bool HasOpenTransactionOn(string sessionFactoryConfigPath)
{
ITransaction transaction;
if (ContextTransactions.TryGetValue(sessionFactoryConfigPath, out transaction))
{
return !transaction.WasCommitted && !transaction.WasRolledBack;
}
return false;
}
public void RollbackTransactionOn(string sessionFactoryConfigPath)
{
try
{
if (HasOpenTransactionOn(sessionFactoryConfigPath))
{
ITransaction transaction = (ITransaction)ContextTransactions[sessionFactoryConfigPath];
transaction.Rollback();
}
ContextTransactions.Remove(sessionFactoryConfigPath);
}
finally
{
ForceCloseSessionOn(sessionFactoryConfigPath);
}
}
/// <summary>
/// Since multiple databases may be in use, there may be one transaction per database
/// persisted at any one time. The easiest way to store them is via a hashtable
/// with the key being tied to session factory. If within a web context, this uses
/// <see cref="HttpContext" /> instead of the WinForms specific <see cref="CallContext" />.
/// Discussion concerning this found at http://forum.springframework.net/showthread.php?t=572
/// </summary>
private Dictionary<string, ITransaction> ContextTransactions
{
get
{
if (IsInWebContext())
{
if (HttpContext.Current.Items[TRANSACTION_KEY] == null)
HttpContext.Current.Items[TRANSACTION_KEY] = new Dictionary<string, ITransaction>();
return (Dictionary<string, ITransaction>)HttpContext.Current.Items[TRANSACTION_KEY];
}
else
{
if (CallContext.GetData(TRANSACTION_KEY) == null)
CallContext.SetData(TRANSACTION_KEY, new Dictionary<string, ITransaction>());
return (Dictionary<string, ITransaction>)CallContext.GetData(TRANSACTION_KEY);
}
}
}
/// <summary>
/// Since multiple databases may be in use, there may be one session per database
/// persisted at any one time. The easiest way to store them is via a hashtable
/// with the key being tied to session factory. If within a web context, this uses
/// <see cref="HttpContext" /> instead of the WinForms specific <see cref="CallContext" />.
/// Discussion concerning this found at http://forum.springframework.net/showthread.php?t=572
/// </summary>
private Dictionary<string, ISession> ContextSessions
{
get
{
if (IsInWebContext())
{
if (HttpContext.Current.Items[SESSION_KEY] == null)
HttpContext.Current.Items[SESSION_KEY] = new Dictionary<string, ISession>();
return (Dictionary<string, ISession>)HttpContext.Current.Items[SESSION_KEY];
}
else
{
if (CallContext.GetData(SESSION_KEY) == null)
CallContext.SetData(SESSION_KEY, new Dictionary<string, ISession>());
return (Dictionary<string, ISession>)CallContext.GetData(SESSION_KEY);
}
}
}
private bool IsInWebContext()
{
return HttpContext.Current != null;
}
private Dictionary<string, ISessionFactory> sessionFactories = new Dictionary<string, ISessionFactory>();
private const string TRANSACTION_KEY = "CONTEXT_TRANSACTIONS";
private const string SESSION_KEY = "CONTEXT_SESSIONS";
public bool HasOpenTransactionOn()
{
return HasOpenTransactionOn(DefaultConfigFile);
}
public void CommitTransactionOn()
{
CommitTransactionOn(DefaultConfigFile);
}
public void CloseSessionOn()
{
CloseSessionOn(DefaultConfigFile);
}
public void ForceCloseSessionOn()
{
ForceCloseSessionOn(DefaultConfigFile);
}
public void ForceCloseSessionOn(string sessionFactoryConfigPath)
{
ISession session;
if (ContextSessions.TryGetValue(sessionFactoryConfigPath, out session))
{
if (session.IsOpen)
{
session.Close();
}
ContextSessions.Remove(sessionFactoryConfigPath);
}
}
public void BeginTransactionOn()
{
this.BeginTransactionOn(DefaultConfigFile);
}
public void RollbackTransactionOn()
{
this.RollbackTransactionOn(DefaultConfigFile);
}
}
I've had great success in the past using Spring.NET's NHibernate support modules. See http://www.springframework.net/downloads/Spring.Data.NHibernate/. You should be able to use the OpenSessionInView module and extend your DAOs off of the NHibernateSupport DAO to get full management support of the open session in view pattern.
Additionally, although I've never tried it, you should be able to use the above stated framework even if you opt out of the reset of Spring.NET's offerings (namely IoC and AOP).
Sure, this is what I used when I was getting started with NHibernate:
Session Factory
public class BaseDataAccess
{
protected ISession m_session;
public BaseDataAccess()
{
m_session = NHibernateHttpModule.CurrentSession;
}
public static ISession OpenSession()
{
Configuration config;
ISessionFactory factory;
ISession session;
config = new Configuration();
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
if (factory == null)
{
throw new ArgumentNullException(nameof(factory);
}
if (session == null)
{
throw new ArgumentNullException(nameof(session));
}
config.AddAssembly("My.Assembly.Here");
factory = config.BuildSessionFactory();
session = factory.OpenSession();
return session;
}
}
Let me know if that helps.
Two suggestions:
Jeffrey Palermo's HybridSessionBuilder (jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple)
See the code examples (specifically see Session 13) in the Summer of NHibernate (www.summerofnhibernate.com)
You might like to consider making your DAL less concerned with managing NHibernate sessions by leveraging NHibernate.Burrow (or implementing a similar pattern yourself).
"NHibernate.Burrow is a light weight middleware developed to support .Net applications using NHibernate by providing advanced and smart session/transaction management and other facilitates."
If you decide to roll your own there are some useful links at the bottom of this page:
A useful google search term would be 'NHibernate Session Management' and 'Contextual Sessions'...
There's no shortage of ideas - you could say there are too many choices, hopefully opinion will start to gravitate around Burrow or something like it...