Saturday, May 12, 2007

NHibernate Configuration from Code

Sometimes you do not want the connectstring in your NHibernate.config file. In fact setting it there without encryption seems not the right thing to do. Before you open sessions in NHibernate you can configure NHibernate to take connection settings from code. This way you can for instance let the user log in with his/her database username and or password:

_configuration = new NHibernate.Cfg.Configuration();
_configuration.SetProperty("hibernate.connection.provider",@"NHibernate.Connection.DriverConnectionProvider");
_configuration.SetProperty("hibernate.dialect",@"NHibernate.Dialect.Oracle9Dialect");
_configuration.SetProperty("hibernate.connection.driver_class",@"NHibernate.Driver.OracleDataClientDriver");
_configuration.SetProperty("hibernate.connection.connection_string",@"persist security info=True;data source=MyServer; user id=MyUserid; password=MyPassword;");

This example uses Oracle settings.
On the Web you will probably get the username and password somewhere from a session variable.

string _username = HttpContext.Current.Session["Username"].ToString();
string _password = HttpContext.Current.Session["Password"].ToString();
_Configuration.SetProperty("hibernate.connection.connection_string", @"persist security info=True;data source=RADORA9; user id=" + _username + "; password=" + _password + ";");

No comments: