Connecting to multiple databases in Active Record - nhibernate

I'm trying to connect to multiple databases in castle active record (which uses nhibernate.) My config file looks like this:
<configSections>
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<activerecord>
<config type="Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.NavtrakOperationsDatabase`1, CommonSchemas">
<add key="hibernate.connection.connection_string" value="myconnstring" />
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
</config>
<config type="Navtrak.Business.Schemas.CommonSchemas.Models.Errors.ErrorsDatabase`1, CommonSchemas">
<add key="hibernate.connection.connection_string" value="Data Source=myconnstring" />
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
</config>
</activerecord>
And then I have a base abstract class for each database like this:
public abstract class NavtrakOperationsDatabase<T> : ActiveRecordBase<T>
{
}
And then each class inherits from this. I'm then initializing active record like this:
ActiveRecordStarter.Initialize(typeof(SimpleModel).Assembly, ActiveRecordSectionHandler.Instance);
Which gives me the error:
Could not find the dialect in the configuration
If I change the activation code to this:
ActiveRecordStarter.Initialize(
ActiveRecordSectionHandler.Instance,
typeof(NavtrakOperationsDatabase<>),
typeof(ErrorsDatabase<>)
);
Then I get the following error:
You have accessed an ActiveRecord class that wasn't properly initialized. There are two possible explanations: that the call to ActiveRecordStarter.Initialize() didn't include Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.Application class, or that Navtrak.Business.Schemas.CommonSchemas.Models.NavtrakOperations.Application class is not decorated with the [ActiveRecord] attribute.
I obviously don't want to include every single class in the Initialize function.
Any ideas?

In my case - which was the same situation - I have added this to the InitializeAR method:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
It ended up like this:
lock (typeof(SessionManager))
{
if (!initialized)
{
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
System.Reflection.Assembly bin = typeof(SimpleModel).Assembly;
IConfigurationSource s = (IConfigurationSource)ConfigurationManager.GetSection("activerecord");
ActiveRecordStarter.Initialize(bin, s);
}
initialized = true;
}

Drop the "hibernate." prefix from all config keys. That prefix was used in NHibernate 1.x

Related

Connection string error between projects with EF

My solution exits out of 3 Projects:
SP_Class_Library contains my EF model
SP_Control_Library is a class library that contains all my custom and
user controls
SP_EF_TEST is my Form Application
I created a custom control cc_User_DropDown with the following code
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
LoadUsers()
End Sub
Private Sub LoadUsers()
Dim UserList As List(Of SP_User) = Nothing
UserList = (From c In ent.SP_User
Where c.usr_Active = True
Select c
Order By c.usr_Name).ToList
Dim blank As New SP_User
blank.usr_ID = 0
blank.usr_Name = "Please select a user..."
UserList.Insert(0, blank)
Me.DisplayMember = "usr_Name"
Me.ValueMember = "usr_ID"
Me.DataSource = UserList
End Sub
The problem comes when I try and add the custom control to either u_Users or Form1 I get the error:
If I comment the code and build I can add the control, but as soon as I uncomment the code and build I get the following:
I have tried suggestions that say I must add the app.config to all the projects, Copy the connectionstring to all the .config files and remove the .config file from the dll and add it to the Form Application but it does not work.
Here is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<connectionStrings>
<add name="SPEntities" connectionString="metadata=res://*/SP_Model1.csdl|res://*/SP_Model1.ssdl|res://*/SP_Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SPDEV;initial catalog=SP;persist security info=True;user id=sa;password=xxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

Web.config jsonSerialization maxJsonLength ignored

I have an MVC3 application running under .NET 4.0 and when I use JavascriptSerializer.Deserialize I'm getting an error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Reading Can I set an unlimited length for maxJsonLength in web.config I put the jsonSerialization maxJsonLength key in my web.config but it gets ignored. Though I can set the JavaScriptSerializer.MaxJsonLength property in code and it works fine.
I would like to have the value in the Web.config rather than code. Here is how I am using JavaScriptSerializer.
Dim client As New WebClient
...
Dim result = _client.DownloadString("Test")
Dim serializer = New JavaScriptSerializer
Return serializer.Deserialize(Of Foo)(result)
Here is my Web.config
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/Http404"/>
<error statusCode="403" redirect="/Http403"/>
<error statusCode="550" redirect="/Http550"/>
</customErrors>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.webServer>
....
</system.webServer>
</configuration>
According to the link you provided (the 2nd most voted answer), your web.config setting will be ignored because you're using an internal instance of the JavaScriptSerializer.
If you need the value to be stored in the web.config, you could add a key in the <appSettings> section called maxJsonLength with a value of 50000000 and then in your code, you could use it like:
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = ConfigurationManager.AppSettings['maxJsonLength'];

Move simple membership profider functionality to class library project

I'm trying to move my DbSet's to a class library project that is going to be used for database operations.
I've been following this tutorial to a Code First / SimpleMembershipProfider project. I've already got the database filled with new tables etc, via the class lib project.
But i am missing the webpages_ tables you can see on this image.
This is my datacontext class:
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public DbSet<Orders> Orders { get; set; }
public DbSet<Appointment> Appointment { get; set; }
public DbSet<UserProfile> UserProfile { get; set; }
}
And for every DbSet i created a cs file. I copied the connectionString from the web.config and placed it in the app.config in the class lib project. This is how the app.config file looks like:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I'm not sure what to do with the Filters folder (which has the class InitializeSimpleMembershipAttribute) in my webproject.
Can someone tell me how to get the webpages_ created in the database? And how to move websecurity etc to the class lib project?
Thanks in advance!
If you trying to take control of Asp.net Simple Membership Table and or Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model your Project Entity framework, there is a number of steps you need to take. I would explain them step by step but it would take too long so i will just provide you with references.
Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
Building Applications with ASP.NET MVC 4. You can use trial version on pluralsight
If you have any specific questions, i would be happy to answer them.

ASP.NET MVC 4 Razor view not recognizing Dropdownlistfor HTML Helper

I am trying to add a dropdownlist to a strongly typed razor view. ASP.Net MVC 4.0, Razor View engine version 2.0.0.0
#using System;
#model SampleApp.Models.ServiceRequestModel
#{
ViewBag.Title = "ServiceRequest";
}
#Html.DropDownListFor(m=>m.CategoryID, Model.Categories)
and the Model is as below:
public class ServiceRequestModel
{
public int ID { get; set; }
public int CategoryID { get; set; }
public SelectList Category { get; set; }
}
it is always showing an error in intellisense in CSHTML file as:
System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'DropDownListFor' and no extension method 'DropDownListFor' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
and also it is giving errors for :
Error 3 The name 'model' does not exist in the current context
I have checked the web.config in View folder:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
The below line of config code had to be changed to 4.0.0.0
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=3.0.0.0**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
changed to
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=4.0.0.0**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
I spent over a day on this error and it ended up being a data type clash with the VM data source for the dropdownlist (ie it wasn't a list of type IEnumerable). For some reason VS2012 thought the error was with the namespace even though it appeared in Intellipath.
I had this exact issue (only with html.displayFor).
I'm not sure how it started but i solved it by replacing the following:
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
with
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
</appSettings>
in the View folder's Web.config file.
Found my solution here

"No message serializer has been configured" error when starting NServiceBus endpoint

My GenericHost hosted service is failing to start with the following message:
2010-05-07 09:13:47,406 [1] FATAL NServiceBus.Host.Internal.GenericHost [(null)] <(null)> - System.InvalidOperationException: No message serializer has been con
figured.
at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.CheckConfiguration() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\
MsmqTransport.cs:line 241
at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\MsmqTransport
.cs:line 211
at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start(Action startupAction) in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Uni
cast\UnicastBus.cs:line 694
at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Unicast\UnicastBus.cs:l
ine 665
at NServiceBus.Host.Internal.GenericHost.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\host\NServiceBus.Host\Internal\GenericHost.cs:line 77
My endpoint configuration looks like:
public class ServiceEndpointConfiguration
: IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
public void Init()
{
// build out persistence infrastructure
var sessionFactory = Bootstrapper.InitializePersistence();
// configure NServiceBus infrastructure
var container = Bootstrapper.BuildDependencies(sessionFactory);
// set up logging
log4net.Config.XmlConfigurator.Configure();
Configure.With()
.Log4Net()
.UnityBuilder(container)
.XmlSerializer();
}
}
And my app.config looks like:
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
</configSections>
<Logging Threshold="DEBUG" />
<MsmqTransportConfig
InputQueue="NServiceBus.ServiceInput"
ErrorQueue="NServiceBus.Errors"
NumberOfWorkerThreads="1"
MaxRetries="2" />
<UnicastBusConfig
DistributorControlAddress=""
DistributorDataAddress=""
ForwardReceivedMessagesTo="NServiceBus.Auditing">
<MessageEndpointMappings>
<!-- publishers don't need to set this for their own message types -->
</MessageEndpointMappings>
</UnicastBusConfig>
<connectionStrings>
<add name="Db" connectionString="Data Source=..." providerName="System.Data.SqlClient" />
</connectionStrings>
<log4net debug="true">
<root>
<level value="INFO"/>
</root>
<logger name="NHibernate">
<level value="ERROR" />
</logger>
</log4net>
This has worked in the past, but seems to be failing when the generic host starts. My endpoint configuration is below, along with the app.config for the service. What is strange is that in my endpoint configuration, I am specifying to use the XmlSerializer for message serialization. I don't see any other errors in the console output preceding the error message. What am I missing?
Thanks, Steve
It looks like this was my own issue, though I had a hard time figuring that out based on the error message that I received. I have a base class for all of my messages:
public abstract class RequestMessage : IMessage {}
Recently, I created a partner message:
public abstract class ResponseMessage<TRequest>
where TRequest : RequestMessage {}
Apparently, when the host was starting up the IStartableBus, it would hit this generic message type and would not handle it correctly. I only really saw the underlying error when running with the DefaultBuilder, rather than the UnityBuilder that I am using in my project. It had something to do with the generic type constraint. I had assumed that this would work, but sadly it did not.
Regards,
Steve