Webforms routing - same signatures with different pages? - asp.net

I'm working on an established site. Although small (in terms of pages), there are some big money landing pages as well as the usual stock pages.
Because the site was relatively small, the page structure was flat.
https://example.com/contact
https://example.com/big-money-page
We plan on introducing lots more pages with different page designs. This means we'll either use master pages and/or aspx templated pages and create our own database driven CMS.
Here's the problem I can see is with url routing:
Template type 1
Route url: /{Name} - e.g. /big-money-page
Physica path: ~/template1.aspx
Template type 2
Route url: /{Name} - e.g. /new-supporting-page
Physical path: ~/template2.aspx
I would like to make this work without disruption to the existing money pages and, if possible, keep the familiar website structure, as to visitors, template1 and template2 are similar pages and don't naturally reside in different folders - they just differ in design.
Also, fixed deep routed folder structures make it difficult to make changes in the future.
I've been using WF routing for some time but always in simple ways. Anyone know how I can make the changes work with limited consequences?
UPDATE --------------------------------------------------------------------
Okay, in the absence of any feedback, I've come up with an idea to put on the table. I'd appreciate feedback on the fesibility and any downsides that can be thought of.
My idea is to have a dummy route/page.
The route would take the form http://example.com/{name}.
The dummy page retrieves data from the database for the target page using the placeholder {name}.
We then server.transfer to the correct target page, using the data we retrieved from the database.
I think this will work but I'm concerned about the things I don't know:
Browser compatibility for server.transfer
Performance overhead
Impact on output caching
Other things that haven't even crossed my mind
Of course this is not an ideal solution but I'm also open to any other ideas.

In a WebForm project the task can be implemented using a custom HTTPModule. The implementation includes a few steps. A simplified version is as following:
1. SQL
create table dbo.UrlMap (
publicUrl varchar(255) not null primary key,
PhysUrl varchar(255) not null
)
Fill the table with some data like
publicUrl PhysUrl
big-money-page template1.aspx?id=1
huge-money-page template1.aspx?id=2
no-money-page template2.aspx?id=3
other-page template1.aspx?id=4
2. Create a class in the App_code folder
using System;
using System.Web;
/// <summary>
/// Implements IHttpModule with custom URLs
/// </summary>
public class UrlMap:IHttpModule
{
/// <summary>
/// Initialize the module
/// </summary>
/// <param name="context"></param>
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
context.PostMapRequestHandler += Context_PostMapRequestHandler;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
Url2PhysPath(app.Request.Path, app);
}
private void Context_PostMapRequestHandler(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var pg = app.Context.Handler as System.Web.UI.Page;
if (pg != null)
{
pg.PreRenderComplete += Pg_PreRenderComplete;
}
}
private void Pg_PreRenderComplete(object sender, EventArgs e)
{
ProcessPageTree((System.Web.UI.Control)sender);
}
/// <summary>
/// Replaces physical URLs on the page with "beutified" version
/// </summary>
/// <param name="control"></param>
private void ProcessPageTree(System.Web.UI.Control control)
{
var form = control as System.Web.UI.HtmlControls.HtmlForm;
if (form != null)
{
form.Action = BeautifyUrl(form.Page.Request.Url.PathAndQuery);
}
//other types in a similar way
if (control.HasControls())
{
foreach(System.Web.UI.Control c in control.Controls)
{
ProcessPageTree(c);
}
}
}
/// <summary>
/// Helper function. Can be inlined.
/// Searches "beautified" url in a DB and rewrites path
/// </summary>
/// <param name="url"></param>
/// <param name="app"></param>
private static void Url2PhysPath(string url, HttpApplication app)
{
using (var cnn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SiteCnn"].ConnectionString))
{
var cmd = new System.Data.SqlClient.SqlCommand("select physPath from dbo.urlMap where publicUrl=#url", cnn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#url", System.Data.SqlDbType.VarChar, 255).Value = url;
cnn.Open();
string physPath = null;
using(var r = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
if (r.Read())
{
physPath = (string)r["physPath"];
}
r.Close();
}
if (!string.IsNullOrEmpty(physPath))
{
app.Context.RewritePath("/" + physPath);
}
}
}
/// <summary>
/// Helper function
/// </summary>
/// <param name="physUrl"></param>
/// <returns>returns original url when nothing is found</returns>
private static string BeautifyUrl(string physUrl)
{
using (var cnn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SiteCnn"].ConnectionString))
{
var cmd = new System.Data.SqlClient.SqlCommand("select publicUrl from dbo.urlMap where physPath=#url", cnn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#url", System.Data.SqlDbType.VarChar, 255).Value = physUrl;
cnn.Open();
string pubUrl = physUrl;//to return original url when nothing is found
using(var r = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
if (r.Read())
{
pubUrl = (string)r["publicUrl"];
}
r.Close();
}
return pubUrl;
}
}
/// <summary>
/// Required by interface
/// </summary>
void IHttpModule.Dispose()
{
// throw new NotImplementedException();
}
}
3. Modify Web.config
Register the module. Add following line to configuration \ system.webServer \ modules
<add name="UrlRewriter" type="UrlMap" preCondition="managedHandler"/>
Follow up
Browser compatibility for server.transfer not a issue. Browser receives HTML only
Performance overhead Not much
Impact on output caching Cached better then template.aspx?id=123
Other things that haven't even crossed my mind Both publicUrl and physUrl must be unique. In practice you can cache direct and inverted key lookups in static Dictionary<string, string> variables.

Related

MiniProfiler MVC SQL Timings Not Displaying

I am using MiniProfiler.Mvc5 v4.2.1 with C# for an ASP.NET MVC5 website. I am implementing MiniProfiler based on the Samples.Mvc5 project included in the source code repo and am having an issue with the display of SQL timings. I am curious if something might be off in my setup, but I am not sure exactly what that might be.
Here is an example of loading the homepage, and I am confused why the SQL timings and percentage all show as 0.0:
However, if I actually click on the sql timings I get this view, which does seem to indicate that each SQL call does have timings associated with it:
The DataConnection class I am using to define ProfileDbConnection and other related objects is in a separate CSPROJ, here are some relevant configuration methods:
/// <summary>
/// Creates a new native connection
/// </summary>
protected override IDbConnection CreateNativeConnection()
{
var connection = new SqlConnection(ConnectionString);
return new ProfiledDbConnection(connection, MiniProfiler.Current);
}
/// <summary>
/// Creates a new SQL command
/// </summary>
/// <param name="cmdText">Command text</param>
protected override DbCommand CreateCommand(string cmdText)
{
var command = new SqlCommand(cmdText, null, (SqlTransaction)Transaction);
return new ProfiledDbCommand(command, (DbConnection)NativeConnection, MiniProfiler.Current);
}
/// <summary>
/// Creates a new command parameter
/// </summary>
/// <param name="name">Parameter name</param>
/// <param name="value">Parameter value</param>
protected override DbParameter CreateParameter(string name, object value)
{
return new SqlParameter(name, value);
}
/// <summary>
/// Creates a data adapter
/// </summary>
protected override DbDataAdapter CreateDataAdapter()
{
return new ProfiledDbDataAdapter(new SqlDataAdapter(), MiniProfiler.Current);
}
In the MVC app's Global.asax.cs:
public MvcApplication()
{
AuthenticateRequest += (sender, e) =>
{
var app = (HttpApplication) sender;
if (Request.IsLocal || app.User != null && app.User.Identity.IsAuthenticated && app.User.Identity.Name == "administrator")
{
MiniProfiler.StartNew();
}
};
EndRequest += (sender, e) =>
{
MiniProfiler.Current?.Stop();
};
}
Can anyone help direct me as to why I might not be seeing them aggregated in the initial view, or where I might start looking to gather more info?
I'm not sure exactly why Mini Profiler would behave like that, as I am not an expert in it. I would, however, wager it's because the Kentico API calls use their own DBContext inside of Kentico, and your DataConnection class does not share the same exact context as Kentico's. The strange thing is that you do see some on the individual level...But it is kinda of hard to tell with out more source code being shared.
But with that being said, Kentico offers automatic integration with Glimpse. Kentico's customized version of Glimpse does show SQL timings and many other profiling options. Check out my blog on how to use that. https://www.mcbeev.com/Blog/January-2018/Why-Kentico-Glimpse-is-a-Must-Have-Tool-for-Kentico-MVC-Developers and a follow up post on adding more memory debugging information at https://www.mcbeev.com/Blog/September-2019/KenticoCacheDoctor-2-Now-With-Kentico-Glimpse.
In the MVC5 world I think Glimpse is still a viable option.

Custom Control with Template that allows child control HTML Response to be manipulated

I'm trying to create an ASP.NET Custom Control that has uses ITemplate to allow the developer to place their own inner ASP/HTML controls in it. The purpose of the control is to parse the rendered HTML of the template contents and search/replace certain placeholder text that might appear (such as [Location], [Division], [FirstName]) with context specific values.
I'm struggling on how to "capture" the generated HTML and "replace" aspects of it as required prior to going out to the response object.
My thoughts are on the lines of using RenderContents(HtmlTextWriter output) to replace output with my own stream and get the controls to write to that. I can then do what I need to do with the rendered content before sending out to output.
However, I am unsure if this is the right method.
Here is a snippet of what I have:
/// <summary>
/// This custom control allows replacement fields to be picked up
/// </summary>
[DefaultProperty("Text")]
[ToolboxData("<{0}:ReplaceableText runat=\"server\" Text=\"[Text]\"></{0}:ReplaceableText>")]
public partial class ReplaceableText : WebControl
{
public ReplaceableText()
{
TokenReplacer = new TokenReplacer();
}
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
/// <summary>
/// The component the performs the replacement
/// </summary>
/// <remarks>
/// An alternative TokenReplacer component could be installed by the caller if required.
/// More typically, you will use the AddResolver(s) methods to apply callbacks to do the
/// actual replacement.
/// </remarks>
public ITokenReplacer TokenReplacer { get; set; }
public bool HasTokenReplacer { get { return (TokenReplacer != null && !DesignMode); } }
protected override void RenderContents(HtmlTextWriter output)
{
System.Diagnostics.Debug.WriteLine("RenderContents() enter");
if (HasTokenReplacer)
{
using (var memStream = new MemoryStream())
{
using (var sw = new StreamWriter(memStream))
{
using (var htw = new HtmlTextWriter(sw))
{
base.RenderContents(htw);
}
}
// !! memStream is still empty (0 bytes) !!
var text = Encoding.UTF8.GetString(memStream.GetBuffer());
var text2 = TokenReplacer.Convert(text);
output.Write(text2);
}
}
else
{
base.RenderContents(output);
}
output.Write(ConvertedText);
System.Diagnostics.Debug.WriteLine("RenderContents() exit");
}
protected override void CreateChildControls()
{
if (Content != null)
{
Controls.Clear();
Content.InstantiateIn(this); // !!! I need this to write to my own alternative temporary stream
}
base.CreateChildControls();
}
Unfortunately, I don't seem to get any mark-up deposited into my Memory Stream.
Silly sausage that I am, I hadn't put any controls into my Contents ITemplate.
This solution does appear to work well, just make sure you check that Controls.Count > 0 if you find your MemoryStream ends up with 0 bytes.

EntityFramework: Update single field with detached entity

Unlike normal, I have code that actually works, but I'm wondering if it's the only (or best approach).
The basic Idea is I have an existing application that's handmade data layer is being ported to Entity Framework. As a compromise to minimize code changes, I'm working with existing methods, which tend to take a more disconnected approach. For example I have a lot of things like this:
UpdateNote(int noteId, string note)
I seem to have a method that works for this type of update without requiring a re-fetch:
var context = new MyEntities();
context.Configuration.ValidateOnSaveEnabled = false;
var note = new Model.Note{ Id = noteId, Note = ""};
context.Notes.Attach(note);
note.Note = "Some Note";
context.SaveChanges();
It's a little ugly (though concise enough), so I would like to know if there is there a better approach to use with EF? Any downsides to this method, other than loosing built-in validation?
This is a pattern that will be used all over my app.
The following extension method for DbContext is an approach which would avoid to initialize your entities with some values different to the values you want to change it to.
public static class EFExtensions
{
public static void MarkAsModified(this DbContext context, object entity,
params string[] properties)
{
foreach (var property in properties)
context.Entry(entity).Property(property).IsModified = true;
}
}
You could then use it this way:
var context = new MyEntities();
context.Configuration.ValidateOnSaveEnabled = false;
var note = new Model.Note { Id = noteId }; // only key properties required to set
note.Note = "Some Note";
note.SomeOtherProperty = 1234;
note.AndAnotherProperty = "XYZ";
context.Notes.Attach(note);
context.MarkAsModified(note, "Note", "SomeOtherProperty" , "AndAnotherProperty");
context.SaveChanges();
Note: This only works for scalar properties, not navigation properties.
Besides validation I could imagine that this approach is problematic for a proper concurrency checking.
Edit
According to #Adam Tuliper's comment below concurrency is likely not a problem because the concurrency check is skipped when an entity is attached manually to the context (without reading it from the database) and marked as modified to send an UPDATE command to the database. It just overwrites the lastest version in the DB. Thanks to Adam for pointing this out!
See the following code I use to easily attach a disconnected object back to the graph, assuming we're now going to save it.
public static class EntityFrameworkExtensions
{
/// <summary>
/// This class allows you to attach an entity.
/// For instance, a controller method Edit(Customer customer)
/// using ctx.AttachAsModified(customer);
/// ctx.SaveChanges();
/// allows you to easily reattach this item for udpating.
/// Credit goes to: http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx
/// </summary>
public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
objectSet.Attach(entity);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
/// <summary>
/// This marks an item for deletion, but does not currently mark child objects (relationships).
/// For those cases you must query the object, include the relationships, and then delete.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectSet"></param>
/// <param name="entity"></param>
public static void AttachAsDeleted<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
objectSet.Attach(entity);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted);
}
public static void AttachAllAsModified<T>(this ObjectSet<T> objectSet, IEnumerable<T> entities) where T : class
{
foreach (var item in entities)
{
objectSet.Attach(item);
objectSet.Context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
}
}
}

Managing NHibernate sessions for a multi-tenant ASP.NET application

I have an existing multi-tenant ASP.NET application where all users authenticate against a single SQL Server database. This database also contains several other settings type data that is used within the application. Each client after authentication, utilizes their own SQL Server database for data storage, for isolation purposes. Essentially all of the client database are identical and reside on the same server, but reside on one or more servers as well.
The application is currently written in asp.net 2.5 framework and utilizes the Microsoft Practices Enterprise Library for DAL, and we are looking to migrate to 4.0 and implement NHibernate to replace the MPEL.
I have implemented a solution already using NHibernate and the 4.0 framework, so I am familiar with the concepts. I found the resources for my current session manager here as a matter of fact. But that application only had a single database, so not much too it. The implementation is essentially what you see here:
http://www.lostechies.com/blogs/nelson_montalvo/archive/2007/03/30/simple-nhibernate-example-part-4-session-management.aspx
The other solutions that I have seen suggest multiple config entries and/or files to manage this, but that is not desirable, since we may add new clients frequently and all of the connection information is already maintained in the authentication database.
Does anyone have any suggestions on how I might be able to pass in the client's connection string to a session manager?
The following is my current session manager class, which is based on the article mentioned above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cache;
using singlepoint.timeclock.domain;
namespace singlepoint.timeclock.repositories
{
/// <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 ISessionFactory idadSessionFactory;
private ISessionFactory clientSessionFactory;
private string _client;
#region Thread-safe, lazy Singleton
// lazy initialisation, therefore initialised to null
private static nHibernateSessionManager instance = null;
/// <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 GetInstance(); }
}
public static nHibernateSessionManager GetInstance()
{
// lazy init.
if (instance == null)
instance = new nHibernateSessionManager();
return instance;
} // GetInstance
/// <summary>
/// Initializes the NHibernate session factory upon instantiation.
/// </summary>
private nHibernateSessionManager()
{
InitSessionFactory();
}
/// <summary>
/// Initializes the NHibernate session factory upon instantiation.
/// </summary>
private nHibernateSessionManager(string client)
{
InitSessionFactory();
InitClientSessionFactory(client);
}
/// <summary>
/// Assists with ensuring thread-safe, lazy singleton
/// </summary>
private class Nested
{
static Nested()
{
}
internal static readonly nHibernateSessionManager nHibernatenHibernateSessionManager = new nHibernateSessionManager();
}
#endregion
private void InitSessionFactory()
{
var configuration = new Configuration();
configuration.Configure(System.Configuration.ConfigurationManager.AppSettings["IDAD_HBM"]);
configuration.AddAssembly(typeof(enterprise).Assembly);
idadSessionFactory = configuration.BuildSessionFactory();
}
private void InitClientSessionFactory(string client)
{
var configuration = new Configuration();
configuration.Configure(System.Configuration.ConfigurationManager.AppSettings["Client_IDAD_HBM"]);
configuration.SetProperty("connection.connection_string", client);
configuration.AddAssembly(typeof(enterprise).Assembly);
clientSessionFactory = configuration.BuildSessionFactory();
}
/// <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 RegisterInterceptor(IInterceptor interceptor)
{
ISession session = ThreadSession;
if (session != null && session.IsOpen)
{
throw new CacheException("You cannot register an interceptor once a session has already been opened");
}
GetSession(interceptor);
}
public ISession GetSession()
{
return GetSession(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 GetSession(IInterceptor interceptor)
{
ISession session = ThreadSession;
if (session == null)
{
if (interceptor != null)
{
session = idadSessionFactory.OpenSession(interceptor);
}
else
{
session = idadSessionFactory.OpenSession();
}
ThreadSession = session;
}
return session;
}
public void CloseSession()
{
ISession session = ThreadSession;
ThreadSession = null;
if (session != null && session.IsOpen)
{
session.Close();
}
}
public void BeginTransaction()
{
ITransaction transaction = ThreadTransaction;
if (transaction == null)
{
transaction = GetSession().BeginTransaction();
ThreadTransaction = transaction;
}
}
public void CommitTransaction()
{
ITransaction transaction = ThreadTransaction;
try
{
if (transaction != null && !transaction.WasCommitted && !transaction.WasRolledBack)
{
transaction.Commit();
ThreadTransaction = null;
}
}
catch (HibernateException ex)
{
RollbackTransaction();
throw ex;
}
}
public void RollbackTransaction()
{
ITransaction transaction = ThreadTransaction;
try
{
ThreadTransaction = null;
if (transaction != null && !transaction.WasCommitted && !transaction.WasRolledBack)
{
transaction.Rollback();
}
}
catch (HibernateException ex)
{
throw ex;
}
finally
{
CloseSession();
}
}
/// <summary>
/// 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 ITransaction ThreadTransaction
{
get
{
if (IsInWebContext())
{
return (ITransaction)HttpContext.Current.Items[TRANSACTION_KEY];
}
else
{
return (ITransaction)CallContext.GetData(TRANSACTION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[TRANSACTION_KEY] = value;
}
else
{
CallContext.SetData(TRANSACTION_KEY, value);
}
}
}
/// <summary>
/// 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 ISession ThreadSession
{
get
{
if (IsInWebContext())
{
return (ISession)HttpContext.Current.Items[SESSION_KEY];
}
else
{
return (ISession)CallContext.GetData(SESSION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[SESSION_KEY] = value;
}
else
{
CallContext.SetData(SESSION_KEY, value);
}
}
}
private static bool IsInWebContext()
{
return HttpContext.Current != null;
}
private const string TRANSACTION_KEY = "CONTEXT_TRANSACTION";
private const string SESSION_KEY = "CONTEXT_SESSION";
[Obsolete("only until we can fix the session issue globally")]
internal ISession OpenSession()
{
return idadSessionFactory.OpenSession();
}
}
}
This is being called from a repository class like so:
public string getByName(string name)
{
return getByName(nHibernateSessionManager.Instance.GetSession(), name);
}
What I would really like to be able to do is the following:
public string getByName(string name, string clientConnectionString)
{
return getByName(nHibernateSessionManager.Instance.GetSession(clientConnectionString), name);
}
But I am having trouble modifying my existing session manager to accomodate this.
You appear to be asking to swap a connection for a given session. Or rather that is certainly what the code you have written is asking - "return a session identified by the name parameter, and it should also now use the connection string provided by this method."
That is not possible. NHibernate builds a session (and actually really a session factory) per connection and once built the factory and session are immutable. You cannot change connections for an existing session.
I got the impression that your application involves mostly in initial connection string that is the moving target, but after that your "real" session is on a single database. If that is the case, NHibernate can easily do this. If that is not the case, well, some things NHibernate is just not that well suited for. Maybe understanding a little more about the basis NHibernate operates on is helpful either way?
One of my genuine criticisms of NHibernate is that you have a somewhat arcane use of terminology and the well known unhelpful nature of it's exception messages. These coupled with the fact that what it is doing is in reality mechanically complicated tends to really obscure that there is a relatively simple and technically sound underlying model.
In this case, if you think about it this business of an immutable session makes a lot of sense. NHibernate connects to a database, but it also maintains objects in the session so they can be persisted back to that database at a later time. NHibernate does not support changing connections per session because there may already be other objects in the session and if you change connections their persistence is no longer assured.
Now, what you can do is create a factory/session per database for multiple databases and access them in one application, but objects still belong to their own session. You can even move objects to a new session with a different connection. In this case you have what would logically be a "replication" scenario. NHibernate supports this but you have to do most of the work. This also makes sense - they really cannot give you that as stable out of the box functionality, you have to manage a process like that on your own.
You can also build code to do exactly what you are asking. But think about what that is. Make a session, not per database, but only for this specific instance of this specific repository. I am thinking that is most likely not really what you want. But that is exactly what the semantics of your request are saying to do. Your existing class, On the other hand, was built on different semantics which are more typically what people want - "Build a session for this particular connection definition, i.e this database."
A real need to inject a connection string at the repository level implies that now not only is the database a moving target, but at the actual table level the target also moves. If that is the case, NHibernate is possibly not a good option. If that is not the case, you may be trying to mix programming paradigms. NHiberate imposes a few what I would call "assumptions" rather than any sort of real "limitations" and in return you don't have to write a bunch of code that would allow you a finer grain of control because often you really don't need that additional control.
Sorry if this is no longer a direct answer to your question, hopefully it is helpful somehow.
Original Answer:
Sure, since the connection info is in the authentication database this is easy.
1) Configure NHibernate in the "usual" fashion and point the config at the authentication database. Get the db connection for the user, and then close that session and session factory. You are done with that one now.
2) Create a new session etc this time in code instead of a config file.
class MyNewSession
{
private ISession _session;
private ISessionFactory _factory;
public void InitializeSession()
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
config.Properties.Clear();
IDictionary props = new Hashtable();
// Configure properties as needed, this is pretty minimal standard config here.
// Can read in properties from your own xml file or whatever.
// Just shown hardcoded here.
props["proxyfactory.factory_class"] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
props["dialect"] = "NHibernate.Dialect.MsSql2000Dialect";
props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
props["connection.connection_string"] = "<YOUR CONNECTION STRING HERE>";
props["connection.isolation"] = "ReadCommitted";
foreach (DictionaryEntry de in props)
{
config.Properties.Add(de.Key.ToString(), de.Value.ToString());
}
// Everything from here on out is the standard NHibernate calls
// you already use.
// Load mappings etc, etc
// . . .
_factory = config.BuildSessionFactory();
_session = _factory.OpenSession();
}
}
I know this is old but if you have not found a solution I hope this will help,
I created a solution that uses multisessionfactory using unhaddins (I made alterations to suit my needs).
Basically the multisession factory creates session factories for each database and stores in Application object.
Depending on the client the call to getfactory("name of factory from factory config file") returns correct database to query on.
You will have to alter your management module to support this and all of your repositories to support the change in management. This may be impractical at first but you have to alter them anyway. Your calls from your repository can be something like this:
public string getByName(string name)
{
return getByName(nHibernateSessionManager.SessionFactoryManager.GetFactory(Session["session variable that holds client session factory name that was set on login"]).GetCurrentSession(), name);
}
or (creating a method in the sessionmanager to return session of a given factory) your code could be like this
public string getByName(string name)
{
return getByName(nHibernateSessionManager.GetSession(Session["session variable that holds client session factory name that was set on login"]), name);
}

Custom PageHandlerFactory for .aspx

I am building a fairly simple CMS. I need to intercept requests for the majority of .aspx pages in my web application, in order to gain complete control over the output. In most cases, the output will be pulled from cache and will just be plain HTML.
However, there still are a couple of pages that I am going to need to use asp: controls on. I assume the best way for me to bypass a few particular requests would be to inherit System.Web.UI.PageHandlerFactory and just call the MyBase implementation when I need to (please correct me if I am wrong here). But how do I transfer all other requests to my custom handler?
When I wrote a simple CMS, I had a difficult time using the PageHandlerFactory to get it to do what I wanted. In the end I switched to a IHttpModule.
My module would first check to see if there was an .aspx file in the requested path. I'd only do that if the page has user controls on it or didn't fit into the CMS for some reason. So if the file existed, it would return out of the module. After that it would look at the requested path and condense it into a "navigation tag." Thus ~/aboutus/default.aspx would become page.aspx?nt=aboutusdefault. page.aspx would load the proper content form the CMS. Of course, the redirect occurs server-side so the users/spiders never know anything different happened.
using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
namespace MyCMS.Handlers {
/// <summary>
/// Checks to see if we should display a virutal page to replace the current request.
/// Code adapted from:
/// Rewrite.NET -- A URL Rewriting Engine for .NET
/// By Robert Chartier
/// http://www.15seconds.com/issue/030522.htm
/// </summary>
public class VirtualPageModule : IHttpModule {
/// <summary>
/// Init is required from the IHttpModule interface
/// </summary>
/// <param name="Appl"></param>
public void Init(System.Web.HttpApplication Appl) {
// make sure to wire up to BeginRequest
Appl.BeginRequest += new System.EventHandler(Rewrite_BeginRequest);
}
/// <summary>
/// Dispose is required from the IHttpModule interface
/// </summary>
public void Dispose() {
// make sure you clean up after yourself
}
/// <summary>
/// To handle the starting of the incoming request
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void Rewrite_BeginRequest(object sender, System.EventArgs args) {
// Cast the sender to an HttpApplication object
HttpApplication httpApp = (HttpApplication)sender;
// See if the requested file already exists
if (System.IO.File.Exists(httpApp.Request.PhysicalPath)) {
// Do nothing, process the request as usual
return;
}
string requestPath = VirtualPathUtility.ToAppRelative(httpApp.Request.Path);
// Organic navigation tag (~/aboutus/default.aspx = nt "aboutusdefault")
Regex regex = new Regex("[~/\\!##$%^&*()+=-]");
requestPath = regex.Replace(requestPath, string.Empty).Replace(".aspx", string.Empty);
string pageName = "~/page.aspx";
string destinationUrl = VirtualPathUtility.ToAbsolute(pageName) + "?nt=" + requestPath;
SendToNewUrl(destinationUrl, httpApp);
}
public void SendToNewUrl(string url, HttpApplication httpApp) {
applyTrailingSlashHack(httpApp);
httpApp.Context.RewritePath(
url,
false // RebaseClientPath must be false for ~/ to continue working in subdirectories.
);
}
/// <summary>
/// Applies the trailing slash hack. To circumvent an ASP.NET bug related to dynamically
/// generated virtual directories ending in a trailing slash (/).
/// As described by BuddyDvd:
/// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=105061
/// </summary>
/// <param name="httpApp">The HttpApplication.</param>
/// <remarks>
/// Execute this function before calling RewritePath.
/// </remarks>
private void applyTrailingSlashHack(HttpApplication httpApp) {
if (httpApp.Request.Url.AbsoluteUri.EndsWith("/") && !httpApp.Request.Url.AbsolutePath.Equals("/")) {
Type requestType = httpApp.Context.Request.GetType();
object clientFilePath = requestType.InvokeMember("ClientFilePath", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty, null, httpApp.Context.Request, null);
string virtualPathString = (string)clientFilePath.GetType().InvokeMember("_virtualPath", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField, null, clientFilePath, null);
clientFilePath.GetType().InvokeMember("_virtualPath", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField, null, clientFilePath, new object[] { virtualPathString });
requestType.InvokeMember("_clientFilePath", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField, null, HttpContext.Current.Request, new object[] { clientFilePath });
object clientBaseDir = requestType.InvokeMember("ClientBaseDir", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty, null, httpApp.Context.Request, null);
clientBaseDir.GetType().InvokeMember("_virtualPath", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField, null, clientBaseDir, new object[] { virtualPathString });
requestType.InvokeMember("_clientBaseDir", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField, null, HttpContext.Current.Request, new object[] { clientBaseDir });
}
}
}
}
Do you mean that you are going to inject controls? If that is the case, you might want to consider a required base class instead of the Page class. Page implements IHttpHandler, so you can create a derived class and then change your pages to derive from your derived class. You will have much more control over your page and be able to hook into it and its rendering.

Resources