Custom RouteHandler in ASP.NET 4.0

It’s great that some of the innovations from ASP.NET MVC 1.0 were moved into the ASP.NET 4.0 platform. One of those was the RouteTable. I hadn’t written a custom RouteHandler before, so I thought I’d do a simple one as a demo for myself (and any others who are interested).

This is just an example of how to build one – it’s not secure.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
using System.IO;

namespace TestWebApplication1
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add(new Route("Assets/{locale}/{assetID}", new CustomRouteHandler()));
        }
    }

    public class CustomRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {            
            return new SimpleFileHttpHandler(requestContext);
        }
    }

    public class SimpleFileHttpHandler : IHttpHandler
    {
        private RequestContext _requestContext;
        private HttpContext _httpContext;

        public RequestContext RequestContext { get; private set; }

        public SimpleFileHttpHandler(RequestContext requestContext)
        {
            _requestContext = requestContext;
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            _httpContext = context;

            string assetID = _requestContext.RouteData.Values["assetID"].ToString();
            string locale = _requestContext.RouteData.Values["locale"].ToString();

            if (string.IsNullOrWhiteSpace(assetID) || string.IsNullOrWhiteSpace(locale)) {
                throw new ArgumentException();
            }
            // this is not adaquate and definitely not secure as it would allow any file to be selected and downloaded
            // needs to prevent any sort of hack attempts using encoded paths, etc. should just be a relative path within the
            // folder that contains the content and no more. 
            string path = _httpContext.Request.MapPath("~/Content/" + assetID, "", false);
            if (File.Exists(path))
            {               
                // hard coded to the image/jpg type (obviously needs to adjust)
                context.Response.AddHeader("Content-Type", "image/jpg");
                context.Response.AddHeader("Content-Length", new FileInfo(path).Length.ToString());
                context.Response.WriteFile(path);
            }
        }
    }


}

To use it, I created a folder called Content and copied one of the sample photos included with Windows into the folder, and then modified Default.aspx:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestWebApplication1._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to the Route Table Demonstrator
    </h2>
    <h3>This one should work as it's using the not-so-magical route table and a custom iroutehandler.</h3>
    <p>
        &lt;img src=&quot;/Assets/en-us/Penguins.jpg&quot; width=&quot;320&quot; height=&quot;200&quot; /&gt;
    </p>
    <p>
        <img src="/Assets/en-us/Penguins.jpg" width="320" height="200" />
    </p>
    <h3>THis one shouldn't work due to security in web.config for the folder</h3>
    <p>&lt;img src=&quot;/Content/Penguins.jpg&quot; /&gt;</p>
    <p>
        <img src="/Content/Penguins.jpg" />
    </p>    
</asp:Content>

In the Content Folder, I added a web.config file to prevent direct access to the content within the folder:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <authorization>
      <deny users="*"/>
    </authorization>
 
  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

This should work without modification on IIS7+ and Visual Studio 2010.

image

Tom Bihn Smart Alec Backpack Review

I recently purchased a Tom Bihn Smart Alec Backpack. Tonight, I put it back in its original shipping box and will be shipping it back to Tom Bihn tomorrow. I wanted to review the bag here on my web site to provide some unbiased and alternative opinions to this bag that I didn’t find elsewhere.

IMG_0326My goals in purchasing a new backpack were:

  1. Reduce the number of zippers and pockets in my backpack to a manageable number. My current REI bag has too many pockets and I’m always forgetting where I’ve put things in the bag.
  2. Bag should Made in the USA.
  3. Be somewhat unique and not like every other bag.
  4. Have room for: 13” Laptop, DSLR with attached lens, magazines, kindle, assorted cables, external portable hard drive, travel meds, pens, markers, pocket digital camera, mouse, adapters, and a full sized computer book.
  5. Works well on vacation, but would also serve me well as an everyday bag.
  6. Fit under a typical airline seat.
  7. Easy access to contents, and easy to put things into bag.
  8. Be waterproof as much as possible.
  9. Be reasonably priced, but be willing to spend more to get a better product.

Non goals:

  1. Last a “life-time.” I want high quality, but I get bored with things like this and am likely to replace it in 3-4 years anyway. But, if it’s a good bag, I’ll buy a new bag from the same place.
  2. Stand-up on it’s own. I’ve owned those types of bags and although handy, it adds too much weight for my needs for little goal.

The Smart Alec seemed to cover my goals quite well.

So, why did I return it? Because looks and customer reviews can be deceiving. IMG_0338

The ordering process and receipt of the bag were quite painless. The staff responded to e-mails when I asked about the right sized storage for my laptop (after a bit of prodding and tweeting).

The bag itself is put together extremely well and it’s obviously assembled with a very watchful eye. I definitely appreciated that. From the zippers to the fabric, it’s made of really nice materials and constructed well. I was very impressed.

First off, the bag could easily hold all of my gear. However, and this is what really irked me the most, is the fact that the main (and only real) compartment has an extremely inadequate opening for accessing the claimed 26L (1600 cu. in.) of available space within the bag. With the custom sized Vertical brain cell (an extra $60) designed to hold my 13” laptop clipped into the bag, the opening that may have been reasonable without the laptop bag became far too tight.

The bag has a few external and internal pockets. One side has a pocket intended for pens and the like. I think it held about 3 pens (unfortunately, I always carry more than that). There was another space in the same pocket for some other random stuff, but nothing felt overly secure and it all bounced around and jingled when carrying the bag. Since it was on the outside of the bag I wasn’t willing to put in my portable mouse or any electronic gear for fear of damage. I really wasn’t sure what was intended for this outside pocket. On the opposite side of the bag there is another pocket, that is intended for a water bottle. Although I didn’t test it, I saw no reason it wouldn’t perform adequately.

The side pocket did have a handy clip for things such as a keychain, which is a nice touch.

IMG_0329

IMG_0330

Below is a photo of the bag opened fully with the laptop carrying case inside.

 IMG_0332

And here you can see how the opening relates compared to a Nikon D300 with a 18-200mm lens attached.

IMG_0333

Inside the main opening flag on the front of the bag is a zippered pocket which at first I thought was perfect. That is, until I realized this too wasn’t protected from external strikes and drops that could easily happen in a busy day (maybe putting it in the car, or riding the bus, etc.). So, some of the common things, like my ZuneHD and my pocket-sized camera would have to be stored elsewhere (things I use frequently). It would work fine for a pair of in-the-ear headphones and any gear like that (non-breakables). Unfortunately, I never found a location for those types of things to which I want quick access.

In the photo below, I’d stored my headphones and a portable mouse, but didn’t really like putting it there. Although I would have easy access to my laptop, the accessories for the laptop, such as the power adapter and my mouse would be difficult to access. There was a side pocket on the Vertical Brain Cell which did fit my power adapter. However, if the bag was reasonably full, I wouldn’t have been able to gain easy access to the pocket and the power adapter. 

IMG_0334

For my wires and cables and portable hard drives, I went to Target and bought a $10 make-up case (although it just contained a few travel containers inside). Tom Bihn sells a product called the “Snake Charmer” for $30, but that seemed too expensive to me for what it is. Target had men’s shaving cases and such, but they were two to three times as expensive, and I really liked the clear bag idea (rather than the traditional “black bag”). This went into the bag. Here’s where the second big problem with this bag comes into play if you’re intending to use it frequently. Since the opening to the main compartment is quite limited, you’ll be forced to pull out the things on the top to access items lower in the bag. That was a big deal for me. I couldn’t imagine being on a plane, with my DSLR packed, and then need something at the bottom of the bag. I’d end up needing to hand things to my seat neighbors to hold while I dug through the bag! :)

IMG_0340

The bottom of the Smart Alec does have a bit of padding, which is somewhat inconsistent with the manufacture IMG_0339of the rest of the bag (with so many pockets and such not having any protection).

IMG_0336

In the photo on the left, it’s probably difficult to see that there’s another pocket deep in the bag (3/4 of the way down the inside of the bag). I didn’t know what to put there, as it would be completely inaccessible if the bag was even slightly full. There was no zipper either, so if the bag wasn’t full, the contents would have slid out if the bag was tilted beyond 90 degrees.

The photos on the Tom Bihn web site show a fully packed bag. I can’t imagine how much careful layering and work it would take to properly organize and fill the bag like that, and how much time it would take to unpack/repack. Again, a larger opening for this bag would help dramatically, especially if using one of the Vertical Brain cells.

If your needs are similar to mine, I wouldn’t buy the Tom Bihn Smart Alec.

The total price, with the Vertical Brain Cell was $190 US.

Not recommended.

Valid Trust Anchor?

On the off chance someone understands this error and can help, I’m posting the wifi errors my Windows 7 Ultimate laptops started to encounter at work on wifi. My laptop is not part of the corporate domain (as it’s a personal laptop). Until very recently, everything worked without any trouble, and IT is not aware of any changes that they made that would explain these errors.

I’ve got Personal certificates installed in my user profile, and my employer’s Trusted Root Certification Authorities certificate is installed. Neither have expired.

The first symptom is that I now get prompted for credentials when connecting to the wifi access point:

Network Authentication

We discovered that just hitting OK here without providing any credentials was OK. It should have been automatically using the certificate I have installed.

After a few moments, this confusing dialog is displayed:

 image

“The credentials provided by the server could not be validated. We recommend that you terminate the connection and contact your administrator with the information provided in the details. You may still connect but doing so exposes you to the security risk by a possible rogue server.

The server XYZ presented a valid certificate issued by Company Name Certificate Authority but Company Name Certificate Authority is not configured as a valid trust anchor for this profile.”

Clicking the Connect button then seems to work. So for now, we agreed that it was OK – but, we have no idea what’s going on. If I learn more, I’ll post more details here. But in the meantime – if anyone else has an idea about this – I’d appreciate hearing about it! 

Restoring a machine from a Windows Home Server

I’ve been having a few issues at work with certificates and wifi. So, the other night I decided to do a fresh install of Windows 7 Ultimate onto my laptop. It’s not as easy as I’d like with my Sony Vaio, as there are drivers for Windows 7, but Sony doesn’t document the sequence that they should be installed in for maximum success (and let me tell you – it’s easy to mess up and have problems).

Fast forward several days later and I’m sitting at work again – still having troubles, even after having reinstalled everything! I brought in a second laptop and it too was having the problem. OK. It’s not my laptop. ARRRRGH!

After some significant time spent with a guy from our IT department, we decided to ignore some of the scary warnings that were being presented to me – and forge ahead and successfully connected to the 802.1x network configuration. (“No valid trust anchor for this profile?”)

I decided rather than continuing to restore all of the software, etc. that I had setup prior to doing the fresh installation of Windows 7, I’d use the restore feature of my Windows Home Server.

I downloaded the latest Restore CD from Microsoft and proceeded to follow the instructions. I was reading through some of the technical details of how it all works while waiting for the download and read that there was even a way to get drivers for the laptop if the default drivers available on the restore CD weren’t sufficient. Cool.

I booted from the Restore CD, followed a few steps and a dialog showed up that suggested that it couldn’t find drivers for my network card. OK. I know there’s a work around. I grabbed the files which are stored with the backup of my laptop, and copied them to a USB stick and tried the option to scan for the files. Nothing. Recopied. Nothing. Try different port. Nothing. What the heck??!? I won’t be able to use the backup if I can’t get the network connected.

I keep getting the error, “No Drivers were found for your hardware.” But, THEY ARE THERE! I SWEAR THEY ARE!

I grabbed the memory stick and stomped it into a million pieces.

OK, actually I decided to reformat the stick just to see if there was something odd about it.

I brought up the format dialog and it was suggesting I reformat the USB stick as exFat. Oh drat. That’s what it was formatted with. I reformatted the USB stick as FAT32, copied the files and now my restoration is off and running with an estimated 1 hour and 44 minutes to go over my gigabit network.