Friday, March 28, 2014

"Classic" ASP

"Classic" ASP is the version of ASP that existed prior to ASP.NET being introduced in 2002.  It was only given the name "Classic" after ASP.NET superseded what was then called just ASP.  A Classic ASP site consists of a bunch of .asp files with associated .html, .js, and .css files.  Nothing within a Classic ASP site is compiled.  It is all interpreted at run-time, which is why ASP.NET offered performance gains.  An .asp page is just HTML with a bunch of server scripts inside of <% ... %> tags.  The scripting language of choice is VBScript although technically you could use JScript (not to be confused with Javascript).

Of course, no one writes "Classic" ASP anymore.  But you may have an old application that you need to host while you ponder a rewrite.  Here are a few things you'll need to do if you don't have a time machine:

  1. Classic ASP is disabled by default in IIS.  Go to Control Panel, Programs, Turn Windows features on or off.  Expand Internet Information Services, World Wide Web Services, and Application Development Features.  Check the ASP box.
  2. Set up the site in IIS like you normally would.
  3. By default, you're not going to see error messages that you need to see.  Open up IIS as an administrator and double click the ASP icon under IIS.  Expand Debugging Properties, and set Send Errors to Browser to True.
  4. Then, if you're using IE, you need to go into Internet Options, on the Advanced tab, and uncheck the box for Show friendly HTTP error messages.

Tuesday, March 25, 2014

Add a Bootstrap jQuery widget to an MVC view.

Bootstrap is an awesome open source UI framework that uses both CSS and jQuery to provide a great user experience.  Besides straight up CSS, they offer some "widgets" that offer some functionality that jQuery UI does not provide.  The process for getting a widget on your view is almost exactly the same as using jQuery UI.

You have to render both the jQuery and Bootstrap bundles in your layout view.  If you don't have a Bootstrap bundle, you just need Bootstrap.js.  Also ensure Bootstrap.css is in your CSS bundle.

This markup will render a button that will produce the popover widget when clicked.

<button type="button" id="Example" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="top" data-content="Phone:  555-5555">
   Popover on top
</button>

Then, add a jQuery file with the following:

$(document).ready(function () {
    $("#Example").popover();
});

Friday, March 21, 2014

ASP.NET Identity - Get a user id

After a user logs in, how do you get the user id, which is stored as a GUID?  You don't have to go through the UserManager class which would require a trip to the database.  You can use the following code but you have to include the Imports statement or it won't work.

Imports Microsoft.AspNet.Identity

...

User.Identity.GetUserId()

Thursday, March 20, 2014

ASP.NET Identity - Using Roles

Roles allow you to restrict parts of your application to specific roles.  These roles are stored in the AspNetRoles table that is created by ASP.NET Identity.  You can create roles programatically or just insert them directly into the table using SQL.  If you're using SQL, you can just use an INSERT statement with a GUID and a name.  Programmatically, you would do the following:

Dim MyRoleStore As New RoleStore(Of IdentityRole)
Dim MyRoleManager As New RoleManager(Of IdentityRole)(MyRoleStore)

MyRoleManager.Create(New IdentityRole("Support Staff"))

IdentityRole is the Entity Framework object that ultimately represents (mapped to) a row in the AspNetRoles table.

Once you have some roles defined, you can associate a role to a user like this:

Dim Result As IdentityResult = _
     Await UserManager.AddToRoleAsync(MyUser.Id, "Support Staff")

Finally in order to restrict parts of your application, you simple add an Authorize filter to the ActionMethod you want restricted like this:

<Authorize(Roles:="Support Staff")>
Function MyActionMethod() As ActionResult

    ...

    Return View()

End Function

Finally, if the user is not authorized, they will be redirected to a specific page, usually the login page.  ASP.NET Identity is not forms authentication so this redirect is not in the web.config.  In an MVC app, it is in the Startup.Auth class ConfigureAuth method:

app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
.LoginPath = New PathString("/Account/Login")})

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.