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

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

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.

<authentication mode="Forms">
    <forms loginUrl="/Registration/Login.aspx"
           protection="All"
           timeout="30"
           name="AppNameCookie"
           path="/FormsAuth"
           requireSSL="false"
           slidingExpiration="true"
           defaultUrl="default.aspx"
           cookieless="UseCookies"
           enableCrossAppRedirects="false"/>
</authentication>
  • 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.

C#: Windows to Unix/Linux Time Conversions

From what I have learned on a recent project is that Windows machines calculate the current date starting on 1/1/0001 where as Linux machines are calculating their time off of what is called the “Start of Epoch” which turns our to be 1/1/1970. I guess we could call it an Epoch year with all the disco and bellbottom pants!

When using Time Stamps across operating system boundaries it is always a good idea to use UTC time (Universal Time) so that you don’t have to mess with time zones. But as I came to find out, that is not enough, you also have to calculate that time stamp from the same origin date.

Below is how you accomplish this in C#:

DateTime startOfEpoch = new DateTime(1970, 1, 1);
long milliseconds = (long)(DateTime.UtcNow - startOfEpoch).TotalMilliseconds;

ASP.net: Disabling Form Auto-Complete in Browsers

We have all experienced our favorite browser asking us if it should save the data we just entered into a form on a web page so it can auto-complete / auto-populate that information the next time we visit the page.

Unfortunately, our browsers are not intelligent enough to think about security on their own and therefore they like to cache anything typed into a form including our passwords. This of course poses a security risk that not many web developers think about when building applications.

For obvious security reasons turning the auto-complete functionality off for all password input fields in a form is a great idea. In fact it is such a great idea it should be second nature to all developers creating forms with any input fields accepting sensitive information (passwords, SSN, account numbers, etc… ).

To turn the auto-complete functionality of on ASP.net TextBox controls you use the AutoCompleteType attribute. Simply add it to your TextBox markup in your aspx or ascx file like so.

Markup Method:

<asp:TextBox id="tbPassword" runat="server" TextMode="Password" Columns="35" AutoCompleteType="Disabled"></asp:TextBox>

Or if you prefer to do it in code you can alter the AutoCompleteType property of the TextBox control in your C# code like so:

Code-Behind Method:

tbPassword.AutoCompleteType = AutoCompleteType.Disabled;

Now the above is what the MSDN documentation tells you to do to turn auto-complete off. But I must say in one of my applications, a rather complicated one, setting the AutoCompleteType property of the ASP.net control to Disabled did not cause the actual HTML attribute of “autocomplete” to be rendered with the off value. I spent time trying to figure out why it was never added to the final HTML output but could not find a reason.

In this particular case I ended up giving in and just adding the attribute to the control manually as follows:

Code-Behind Method:

tbPassword.Attributes.Add("autocomplete", "off");

You can also turn auto-complete off for all input fields in an entire form by adding the “autocomplete” attribute to the From directly and setting its value to “off”.

Markup Method:

<form autocomplete="off">

 

Note: the “autocomplete” attribute we have been discussing here is not found in the actual HTML documentation for either the “input” or “form” tags as defined by the W3C which means that it is selectively implemented by browsers and therefore not universally functional across all browsers. 

JavaScript: Simple Open New Window

Since I don’t do this on a daily basis it doesn’t stick around so I figured I would blog it so I have a reference to it:

window.open('http://www.yourdomain.com','','scrollbars=no,menubar=no,height=700,width=900,resizable=yes,toolbar=no,location=no,status=no');

Silverlight 3: Transparent Background Controls

The first time you add a Silverlight 3 control which is supposed to have transparent portions to let your site design shine through you might notice that those sections are black and not the anticipated transparency.

Silverlight controls by default have a window that surrounds them and is set to black. Transparency of course takes a lot of resources to accomplish and as you would guess it is turned off by default. In order to get the desired effect you need to alter an existing parameter and add an additional one.

Existing Parameter: <param name="background" value="white" />

Changed To: <param name="background" value="transparent" />

Additional Parameter: <param name="windowless" value="true" />

ASP.net: MySQL Membership Provider – Clear Passwords

When you install the MySQL Connector it adds several configuration entries to your Machine.config. By default the newly installed Membership provider has been set up for a development environment.

The main reason I have come to this conclusion is that the MySQLMembershipProvider configuration entry has the passwordFormat attribute set to ‘Clear’ and the applicationName attribute set to ‘/’.

Just like in the ASP.net Membership provider the MySQL provider allows multiple applications to use the Membership database by keying off the applicationName attribute configured in the Provider. Being that the provider entry is added to the Machine.config file the default applicationName attribute of ‘/’ will be used for all applications using the provider. This is fine if you want the same users to have access across all of the applications using the Membership database. But if your plan is to use a single membership database across multiple applications but would like to keep the users segregated this setup will not work.

I also mentioned that the passwordFormat is set to ‘Clear’. This means that all passwords will be saved in the database in clear text. This of course is only to be used during development to you can pull test user’s passwords when you forget them. In a production environment that passwordFormat should be set to ‘Hashed’. This of course forces the password and the password recovery question’s answer to be hashed using a cryptographic algorithm, thus protecting the user’s password from anyone including rogue application and database administrators or hackers that manage to infiltrate the database.

To override the MySQL Membership Provider’s default settings you need to add the following to each of your application’s web.config files.

    <membership defaultProvider="MySQLMembershipProvider">
      <providers>
        <remove name="MySQLMembershipProvider"/>
        <add name="MySQLMembershipProvider" autogenerateschema="true" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.1.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="GndCoreMembership" requiresUniqueEmail="True" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
      </providers>
    </membership>
    <profile>
      <providers>
        <remove name="MySQLProfileProvider"/>
        <add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.1.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="true" defaultProvider="MySQLRoleProvider" >
      <providers>
        <remove name="MySQLRoleProvider"/>
        <add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.1.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
      </providers>
    </roleManager>

The ‘remove’ element is necessary before you add the provider because it already exists in your machine.config file. If you don’t the first attempt to access a protected resource will fail with a configuration error stating the provider already exists.

.Net: MySQL and Entity Framework

With the arrival of the MySQL .Net 6.1 Connector you now have an alternative to Microsoft SQL server or SQL Server Express when it comes to using the new Microsoft Entity Framework.

This new connector library is provided free directly from the MySQL website and actually integrates with Visual Studio 2008. Simply download the installer, install and you will now have access to your MySQL databases directly from within the Visual Studio Server Explorer.

By having access to your MySQL databases from the Server Explorer within Visual Studio you can simply drag and drop tables directly onto your Entity model.