Tuesday, March 18, 2014

ASP.NET Identity Basics

ASP.NET Identity is a system for handling authentication and authorization.  It was released with .NET 4.5.1 that shipped with Visual Studio 2013.  It replaces ASP.NET Membership.

Like Membership, it is a (sort of) simple way to implement forms authentication in a .NET application.  Identity differs from Membership in that it can be unit tested, allows external providers (such as Facebook and Google), and it works for all .NET technologies.

It is surprisingly easy to configure a new MVC web application for forms authentication using Identity.  Simply add an ASP.NET Web Application project and choose MVC with Individual User Accounts.  Remember to set the Framework version of the new project to 4.5.1 or you will not have these options.

The resulting project will contain:
  1. An AccountController class that will handle all authentication and user profile functionality.
  2. A web.config with a connection string pointing at a yet-to-be-created LocalDB database.
  3. A set of Account views that handles logging in, registrations, and user profile management.
  4. An AccountViewModels file that contain view models the Account views use.
  5. An IdentityModel file that contain classes that derive from the built in Identity classes.
  6. A Startup.Auth file that contains code to configure authentication on start up.
All of this is nicely integrated with the default views and controllers that the ASP.NET template has included for a standard MVC application.  You can run it and start registering and logging in immediately with no additional configuration.

It is important to understand the users and passwords are stored in the LocalDB database referred to in the web.config file.  This database is created by ASP.NET when you register the first user.  When you want to go to production, you can just script this thing out and move it to a production SQL Server.

If you look at the AccountController code, you'll notice that a Microsoft.AspNet.Identity.UserManager class is called for much of the authentication functionality.  The UserManager class almost exclusively offers asynchronous methods.  Therefore, you have to follow the rules of calling asynchronous methods when using this class.

Monday, March 17, 2014

Calling an asynchronous method

.NET 4 included a programming model and a few extra operators (await and async) to support asynchronous programming.  Even if you're not interested in doing anything asynchronously, there are certain classes in .NET that only offer asynchronous methods.  An asynchronous method can be identified by 3 things:
  1. The Async operator in the method signature.
  2. The word Async in the method name.  (This is only a standard and is not enforced)
  3. A return type of Task or Task(Of TResult).
An asynchronous method can only be called from another asynchronous method.  The method or event handler you are calling it from must be designated with the Async operator.

As an example, we are going to call the GetStringAsync method of the HttpClient class.

    Private Async Sub ButtonKickOff_Click(sender As Object, e As EventArgs) Handles ButtonKickOff.Click

        Dim Client As New System.Net.Http.HttpClient

        TextBoxResults.Text = Await Client.GetStringAsync("http://www.google.com")

    End Sub

This event handler is from a Windows Forms application.  Note that I added the Async operator to the event signature.  In this case, I'm calling the asynchronous function in a synchronous way, so I simply use the Await operator to signal that I'm just going to wait until it completes.

    Private Async Sub ButtonKickOff_Click(sender As Object, e As EventArgs) Handles ButtonKickOff.Click

        Dim Client As New System.Net.Http.HttpClient

        Dim Results As System.Threading.Tasks.Task(Of String) = _
            Client.GetStringAsync("http://www.google.com")

        LabelStatus.Text = "Processing..."

        TextBoxResults.Text = Await Results

    End Sub

Here, I am calling GetStringAsync and while it is executing, I am moving on. I immediately display a message to the user and then wait for the result.

LocalDB

When developing applications that use SQL Server for persistence, you now have 3 options:

  1. Install a full version of SQL Server.
  2. Install SQL Server Express.
  3. Use LocalDB.
Option 1 is expensive, and has a big footprint.

Option 2 is free, is limited, and has a big footprint.

Option 3 is free, is limited, and has a small footprint.

LocalDB seems to be the preferred way for developers to connect to databases while in the development process.  It is installed with Visual Studio 2012 forward.  Any databases created require no administration or configuration.

To connect to you LocalDB instance, simply use (localdb)\v11.0.  Databases, tables, and stored procedues can all be created in Visual Studio, so there is no need to install SQL Server at all while developing or doing research.

Friday, March 14, 2014

modern.IE

Modern.IE (literally just type modern.ie in your address bar) is a great site that contains a lot of resources if you are writing code to take advantage of new HTML5 features or just looking to ensure your site behaves itself across multiple versions of IE.

The most useful thing it offers is free downloadable virtual machines that have the various versions of IE installed.  You need a separate virtual machine for each version since multiple versions of IE cannot be installed on the same PC.  When you download a VM, there are several files you must download.  Typically there is an exe with one or more rar files.  They're big, so if your connection is slow, consider a download manager program like Free Download Manager.  Once the four files are in place, just kick off the exe and it will extract everything and produce the VM files for you.  I used Virtual PC for Windows 7 and it worked great.  Virtual PC is part of Windows 7 so you don't have to install or configure it.  Just open the file and it boots up.  After a while, you'll be prompted to activate the Windows software on the vpc, but you should ignore this per the license agreement.

Thursday, February 27, 2014

Two ways to validate a string against a regular expression

The .NET framework provides at least two ways to accomplish regular expression validation.  Microsoft seems to prefer you use RegExStringValidator for simple validation, but as you can see below, it is anything but simple.  I see no reason not to use the RegEx class which is much cleaner.

Use the RegExStringValidator class


Dim MyRegEx As String = "(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})"

Dim MyRegExValidator As New System.Configuration.RegexStringValidator(MyRegEx)

Try

    Dim StringToValidate As String = "gDLDdE12"

    If MyRegExValidator.CanValidate(StringToValidate.GetType()) Then
        MyRegExValidator.Validate(StringToValidate)
    End If

    'If no exception occurs, then the validation succeeded.
    
Catch ex As Exception

    'If an exception occurs, then the validation failed.

End Try


Use the RegEx class


Dim RegExEngine As System.Text.RegularExpressions.Regex = _
    New System.Text.RegularExpressions.Regex("(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})")

If RegExEngine.IsMatch(NewPassword.Text) Then
    'Validation is successful.
Else
    'Validation is not successful.
End If

Wednesday, February 26, 2014

Regular Expressions for password validation

Regular Expressions can look like Greek and be a real pain to wrap your head around, but sometimes they are necessary.  It's fairly easy to find a regular expression for common uses like email and phone numbers.  However, I didn't have much luck finding a regular expression to validate the format of a password.  This is probably because there are so many variations on what is considered an acceptable password.

By reverse engineering some Microsoft examples, I've discovered an easy way to create a regular expression for your specific password validation needs.

Let's walk through this:

What is the minimum length of the password?  Let's say 8.  So start with:

(?=.{8,})

Do you require at least one number?  If yes, then append:

(?=(.*\d){1,})

Do you require at least one capital letter?  If yes, then append:

(?=(.*[A-Z]){1,})

Do you require at least one lower case letter?  If yes, then append:

(?=(.*[a-z]){1,})

Do you require at least one "special" character?  If yes, then append:

(?=(.*\W){1,})

When we string these requirements together, we get:

(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*\W){1,})

By omitting and including the various sections, you should be able to create a regular expression that matches your application's definition of an "acceptable" password.

Wednesday, February 5, 2014

Use PowerShell to add an event log source.

Open PowerShell and Run as an Administrator.

[System.Diagnostics.EventLog]::CreateEventSource(name of source goes here, "Application")