Blog

ActiveRecord: Multiple Database Configuration

Perhaps you have a web application which not only has a database in which it stores its content but also has one to hold logging data (Exceptions, Log Entries).
This can be a common practice used to keep unrelated data separate and to off load the load created by logging data for purely health monitoring reasons.
If you are using Castle ActiveRecord as your ORM (Object Relational Mapping) layer and are familiar with setting it up for one database you may not be familiar with configuring it to handle more than one database for your objects.
ActiveRecord decides which database to send an object to based on a combination of a Abstract base class which inherits from ActiveRecordBase and a separate configuration section for each of those base classes. Each of those base classes must also be registered with ActiveRecord at application startup just like any Entity you plan on using within the application.
Below are the steps you need to take to properly setup your ASP.net web application to use 2 databases.
1. Create a ActiveRecordBase class for each of the databases you will be using. Each entity which inherits from that base class will be mapped to the corresponding database.

public abstract class ApplicationActiveRecordBase : ActiveRecordBase{}

public abstract class LoggingActiveRecordBase : ActiveRecordBase{}

2. Initialize each of the base classes so that ActiveRecord is aware of the classes

        static ActiveRecordInitializer()
        {
            IConfigurationSource source = ActiveRecordSectionHandler.Instance;
            ActiveRecordStarter.Initialize(
                source,
                typeof(LoggingActiveRecordBase),
                typeof(ApplicationActiveRecordBase));
        }

3. All entities belonging to a specific database should inherit from the base class associated with that database in the configuration.

    [DataContract]
    [ActiveRecord(Table = "exceptionentry")]
    public class ExceptionEntry : LoggingActiveRecordBase<ExceptionEntry>
    {

4. Add configuration sections to the ActiveRecord configuration for each database specifying the ActiveRecordBase class that will be used to identify the database.

  <activerecord isWeb="true" isDebug="false" threadinfotype="Castle.ActiveRecord.Framework.Scopes.HybridWebThreadScopeInfo, Castle.ActiveRecord">
 
    <config type="ActiveRecord.BaseClasses.ApplicationActiveRecordBase`1, Data.Core, Version=1.0.0.0, Culture=neutral">
      <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
      <add key="hibernate.dialect" value="NHibernate.Dialect.MySQLDialect" />
      <add key="hibernate.connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" />
      <add key="hibernate.connection.connection_string" value="Server=localhost; Database=YOURAPPLICATIONDATABASE; User Id=YOURUSER; Password=YOURPASSWORD" />
    </config>
 
    <config type="ActiveRecord.BaseClasses.LoggingActiveRecordBase`1, Data.Core, Version=1.0.0.0, Culture=neutral">
      <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
      <add key="hibernate.dialect" value="NHibernate.Dialect.MySQLDialect" />
      <add key="hibernate.connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" />
      <add key="hibernate.connection.connection_string" value="Server=localhost; Database=YOURLOGGINGDATABASE; User Id=YOURUSER; Password=YOURPASSWORD" />
    </config>
 
  </activerecord

ASP.net: Login Control Styling Convert to Template

If you are looking for an easy way to style the ASP.net Login Control and don’t want to use all the built-in control properties because you want unfettered access to all the elements that make up the Login Control all you have to do is the following.

  1. Open the ascx or aspx page which holds the Login Control.
  2. Switch to design view.
  3. Right-click the actual Login Control on the design surface and in the context menu select “Convert to Template”.

Visual Studio will automatically add the “LayoutTemplate” element to the Login Control markup and populate it with all the controls and elements that made up the control as it was setup at the time of conversion.
You now have access to everything you need to extensively style the Login Control to your liking.

ASP.net: Adding Re-Captcha to your Forms

In order to stop malicious applications (robots) from submitting your forms over and over again creating extremely painful data and performance problems the best thing you can do is add captcha to your forms.

Captcha stands for “Completely Automated Public Turing test to tell Computers and Humans Apart”. It uses an image containing deformed text which is impossible for computers to read but can be deciphered by a human. When submitting a form the user must enter the text correctly which is validated by the Captcha control. If the text is correct the validation passes if not it fails. When the validation fails the form cannot be submitted.

A nice free Captcha library and services is the ReCaptcha services which is completely free and extremely easy to use.

1. Download the library

2. Register for an API key

3. Add a reference to that library

4. Register the control on the page


5. Add the control to the page


<recaptcha:RecaptchaControl
      ID="recaptcha"
      runat="server"
      PublicKey=""
      PrivateKey=""
      />

6. Validate the ReCaptcha control in a form event

            recaptcha.Validate();

            if (!recaptcha.IsValid)

            {

                e.Cancel = true;

            }

            else

            {

                recaptcha.Visible = false;

            }

ASP.net: Changing Forms Authentication Defaults

By default ASP.net expects to find the Login.aspx page in the root directory of the application. When a request comes in for a protected resource and the user is not authenticated or authorized to access that resource it will automatically redirect the user to /Login.aspx so the user can login.
Personally I do not like to place all of my Membership pages in the root of the application. I like a little order to my madness and prefer to place the Login.aspx page in a folder like Registration which is publicly accessible. But if you try to place the Login.aspx page in any folder except the root of the application you will see an error stating the page cannot be found when you try to access a protected resource. This is because of the default settings discussed above.
To fix this you simply need to alter the default setup for Forms Authentication by adding some configuration entries to your web.config as follows.


<forms loginUrl="/Registration/Login.aspx"
protection="All"
timeout="30"
name="AppNameCookie"
path="/FormsAuth"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseCookies"
enableCrossAppRedirects="false"/>

  • loginUrl: allows you to alter the default location of your Login.aspx page

You can look up the rest of the attributes by going to the MSDN documentation for ASP.net Membership.

Vista: Missing SMTP Server

Microsoft decided to remove the SMTP server feature from the Vista operating system (all versions).
This of course is a real problem for those of us who are developers as we can no longer use the local SMTP server to send emails from our applications as we are developing and testing them.
Luckily there are a few applications out there which we can use instead. Here are just a few alternatives for use as your local SMTP server for development.
Free SMTP Server from SoftStack.com: This is a good alternative as it is extremely easy to setup and use. But on the downside it is limited to 10 emails a day unless you purchase the full version.
If you need to be able to send more than just 10 emails during a day Pegasus Mail provides a free SMTP server titled Murcury SMTP Server.

SVN: .Net Solution and Project files to be Ignored

The following items should be added to your Tortoise SVN global ignore list before importing a .Net project into a Subversion Repository.


*.suo *.user bin obj *.pdb *.cache *_svn *.svn *.suo *.user *.build-res TestResults _ReSharper*

You can add them by right-clicking in Explorer and going to TortoiseSVN /  Settings. This will open the Tortoise SVN settings window and should be on the General settings window. The second section “Subversion” has a filed called “Global ignore pattern” go to the end of the list and paste in the ones above then click apply and ok.