How to set connection string dynamically in NHibernate - nhibernate

I want assign connection string for NHibernate using following code but it throw an exception.
log4net.Config.DOMConfigurator.Configure();
Configuration config = new Configuration();
IDictionary props = new Hashtable();
props["hibernate.connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
props["hibernate.dialect"] = "NHibernate.Dialect.MsSql2000Dialect";
props["hibernate.connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
props["hibernate.connection.connection_string"] = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Sample;Data Source=HYDHTC92318D\SQLEXPRESS";
props["hibernate.connection.current_session_context_class"] = "web";
props["hibernate.connection.show_sql"] = "true";
props["hibernate.connection.proxyfactoryfactory.factory_class"] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
foreach (DictionaryEntry de in props)
{
config.SetProperty(de.Key.ToString(), de.Value.ToString());
}
config.AddAssembly("nhibernator");
factory = config.BuildSessionFactory();
session = factory.OpenSession();
Exception:
The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
Example:
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle**
Please let me know the solution.

See here for a solution:
How to load application settings to NHibernate.Cfg.Configuration object?
I haven't tested this, but you may want to try changing:
props["hibernate.connection.proxyfactoryfactory.factory_class"] =
"NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
to:
props["proxyfactory.factory_class"] =
"NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
The proxyfactory isn't part of the connection.

Related

LDAP Records Password Change Automatic in C#

I'm new in Ldap
now I tried changed ldap records' password with c#.
for example;
users in ldap
username:12345678900
password:78900
I can do bellow with help
try
{
searchRoot = new DirectoryEntry(String.Format("LDAP://{0}/{1}",
domainController, container),
adminUser, adminPassword, authenticationTypes);
searcher = new DirectorySearcher(searchRoot);
searcher.Filter = String.Format("sAMAccountName={0}", userName);
searcher.SearchScope = SearchScope.Subtree;
searcher.CacheResults = false;
SearchResult searchResult = searcher.FindOne();
catch (Exception ex)
{
return ex.ToString();
}
how to do I?
I'm not familiar with the C# LDAP API but it looks similar to JNDI, where the SearchResult gives you either a Context or a DN from which you can get a Context via a lookup, and you can then change the attribute via the Context.

Multiple sessions with Fluent NHibernate and Ninject

I am working on setting up a multi-tenant, seperate database application and have made some good progress from reading this post below on stackoverflow.
Multitenancy with Fluent nHibernate and Ninject. One Database per Tenant
I see two sessions being setup. One is the 'master' session that will be used to get the tenant information and then the tenant session which is specific to the subdomain. I have the app switching nicely to the specified database based on domain and have questions on how to setup the 'master' database session and how to use it.
I tried registering a new session specifically for the master session be get an error regarding having already registered an ISession.
I'm new to nHibernate and not sure the best route to take on this.
NinjectWebCommon.cs
kernel.Bind<WebApplication1.ISessionSource>().To<NHibernateTenantSessionSource>().InSingletonScope();
kernel.Bind<ISession>().ToMethod(c => c.Kernel.Get<WebApplication1.ISessionSource>().CreateSession());
kernel.Bind<ITenantAccessor>().To<DefaultTenantAccessor>();
ITenantAccessor.cs
public Tenant GetCurrentTenant()
{
var host = HttpContext.Current.Request.Url != null ? HttpContext.Current.Request.Url.Host : string.Empty;
var pattern = ConfigurationManager.AppSettings["UrlRegex"];
var regex = new Regex(pattern);
var match = regex.Match(host);
var subdomain = match.Success ? match.Groups[1].Value.ToLowerInvariant() : string.Empty;
Tenant tenant = null;
if (subdomain != null)
{
// Get Tenant info from Master DB.
// Look up needs to be cached
DomainModel.Master.Tenants tenantInfo;
using (ISession session = new NHibernateMasterSessionSource().CreateSession())
{
tenantInfo = session.CreateCriteria<DomainModel.Master.Tenants>()
.Add(Restrictions.Eq("SubDomain", subdomain))
.UniqueResult<WebApplication1.DomainModel.Master.Tenants>();
}
var connectionString = string.Format(ConfigurationManager.AppSettings["TenanatsDataConnectionStringFormat"],
tenantInfo.DbName, tenantInfo.DbUsername, tenantInfo.DbPassword);
tenant = new Tenant();
tenant.Name = subdomain;
tenant.ConnectionString = connectionString;
}
return tenant;
}
Thanks for you time on this.
Add another session binding and add some condition. E.g.
kernel
.Bind<ISession>()
.ToMethod(c => c.Kernel.Get<NHibernateMasterSessionSource>().CreateSession())
.WhenInjectedInto<TenantEvaluationService>();

Generate HBM files using mapping by code

I'm using NHibernate mapping by code and I'm creating the session factory in this way:
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
const bool executeScript = false;
var configuration = new Configuration();
configuration.DataBaseIntegration(c =>
{
c.Dialect<MsSql2005Dialect>();
c.ConnectionString =
ConfigurationManager.ConnectionStrings["ShopConnectionString"]
.ConnectionString;
c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
});
configuration.AddMapping(domainMapping);
_sessionFactory = configuration.BuildSessionFactory();
I need to get the corresponding HBM files.
How can I achieve that?
Two ways:-
//This will write all the XML into the bin/mappings folder
mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();
be careful of this method above as your asp.net app will recycle as changes are detected in your bin folder, another way is:-
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
//you could add a breakpoint here!
var mappingXml = mapping.AsString();
Use the AsString() extension method:
domainMapping.AsString()
It will give you the xml which you can save into a file. You can call that method e.g. before you build the SessionFactory.

How to lookup JNDI resources on WebLogic?

I deployed a legacy application on WebLogic 11g. The application has the following code:
Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("java:myDataSource");
I also have a data source configured in WebLogic with the JNDI name of:
jdbc/myDataSource
When the above java code runs, I get the following exception:
javax.naming.NameNotFoundException: While trying to look up /myDataSource in /app/webapp/axis2.war/60105275.; remaining name '/myDataSource'
at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
at weblogic.jndi.internal.ApplicationNamingNode.lookup(ApplicationNamingNode.java:144)
I'm fairly new to JNDI, so my question is? Where is the disconnect in naming? What does it mean when a context lookup has a prefix of "java:" ?
Thanks!
You should be able to simply do this:
Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
If you are looking it up from a remote destination you need to use the WL initial context factory like this:
Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);
InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
weblogic.jndi.WLInitialContextFactory
java is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource"); if the resource reference name is jdbc/myDataSource).
To avoid having to change your legacy code I think if you register the datasource with the name myDataSource (remove the jdbc/) you should be fine. Let me know if that works.
I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string.
Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.

WCF: Why does passing in a remote endpoint fail?

The problem I am having connecting a wcf client application to a host running on a separate machine is documented in a question previously asked:
WCF: Why does passing in a remote endpoint fail?
However, the solution provided here says you need to use a SpnEndpointIdentity with an empty string. Since my code doesn't look anything like the case in the example I have referenced, I need to know what to do with the SpnEndpointIdentity object I have created.
I have a ChannelFactory upon which I call Create channel, passing in an EndpointAddress:
public override void InitialiseChannel()
{
SpnEndpointIdentity spnEndpointIdentity = new SpnEndpointIdentity("");
var address = new EndpointAddress(EndpointName);
Proxy = ChannelFactory.CreateChannel(address);
}
(NB: ChannelFactory is of type IChannelFactory, where T is the service contract interface)
So what do I do with spnEndpointIdentity? I can't pass it to CreateChannel.
Or perhaps I can use it somehow when I create the channel factory:
private ChannelFactory<T> CreateChannelFactory()
{
var binding = new NetTcpBinding
{
ReaderQuotas = { MaxArrayLength = 2147483647 },
MaxReceivedMessageSize = 2147483647
};
SpnEndpointIdentity spnEndpointIdentity = new SpnEndpointIdentity("");
var channelFactory = new ChannelFactory<T>(binding);
return channelFactory;
}
Again, I can't pass it into the constructor, so what do I do with it?
Thanks.
You almiost got it.
What you're missing is that you associate the EndpointIdentity with the EndpointAddress, and then provide that to CreateChannel():
SpnEndpointIdentity spnEndpointIdentity = new SpnEndpointIdentity("");
var address = new EndpointAddress(EndpointName, spnEndpointIdentity);