My new favorite phrase

I found this little jewel in Martin Fowler's recent post OneLanguage

... a jigger of 80 proof ugliness ...

Check the post for the full context if you need to know what is a jigger of 80 proof ugliness, but this phrase, for whatever reason, gave me large amounts of joy just now.

Tags:

Forcing redirection to HTTPS in ASP.Net

I ran into this issue today when trying to find a quick and dirty script to enforce redirection from HTTP to HTTPS for an intranet site we're enabling for HTTPS (yes, I know SSL on an intranet???  One word - Audit).  I thought this would be easy...I half expected that there would be an IIS setting to handle this for me; I was wrong on both counts.  So what I ended up doing is using an old DNN HttpModule which was set up to allow the user to specify specific tabs in DNN for SSL, and greatly simplifying things to work to my advantage.  I thought I would post it so I wouldn't have to look for it again.

To give a quick overview of what is going on, this is an HTTP Module which looks at a value in the web.config to determine whether or not to enforce HTTPS or not.  If the setting is set to true (or yes), then I'm just grabbing the Url property from the Request object, loading it up in a UriBuilder, and setting the Scheme to "https", and the port to 443 (this may not be necessary, but it was generating an URL with a port of 80 before, which defeats the purpose so I decided to play it safe).  It then feeds the generated URI to Response.Redirect(), and your off.  There is some additional code in there to disable the feature if your on localhost, which is mostly to keep from blowing up your dev box.

Here is the class:

using System;
using System.Configuration;
using System.Web;


namespace HTTPSRedirectHandler
{
    /// <summary>
    /// An HttpModule which redirects traffic to HTTPS based on configuration settings.
    /// </summary>
    public class HttpsRedirector : IHttpModule
    {
        HttpApplication _context;

        public HttpsRedirector()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        /// <summary>
        /// Initializes a module and prepares it to handle
        /// requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the
        /// module that implements <see langword="IHttpModule."/>
        /// </summary>
        public void Dispose()
        {
            _context.BeginRequest -= new EventHandler(context_BeginRequest);
            _context.Dispose();
        }

        #endregion

        /// <summary>
        /// Handles the BeginRequest event of the current Http Context.
        /// </summary>
        private void context_BeginRequest(object sender, EventArgs e)
        {
            bool useSSL = false;
            string result = null;
            if((result = ConfigurationSettings.AppSettings["RequireSSL"]) != null)
            {
                if(result.ToUpper() == "TRUE" || result.ToUpper() == "YES")
                    useSSL = true;
            }
            if (useSSL)
                EnforceSSL();
        }

        /// <summary>
        /// Enforces a redirection to HTTPS if the current connection is using HTTP (port 80).
        /// </summary>
        private void EnforceSSL()
        {
            if(_context.Request.ServerVariables["SERVER_NAME"].ToLower() != "localhost")
            {
                if(_context.Request.ServerVariables["SERVER_PORT"] == "80")
                {
                    UriBuilder uri = new UriBuilder(_context.Request.Url);
                    uri.Scheme = "https";
                    uri.Port = 443;
                    _context.Response.Redirect(uri.ToString());
                }
            }
        }
    }
}

 

Here is the web.config settings you need to use it:

<httpModules>
    <add name="SSLRedirect" type="HTTPSRedirectHandler.HttpsRedirector, HTTPSRedirectHandler" />
</httpModules>
 
<appSettings>
<add key="RequireSSL" value="True" /> </appSettings>

Tags:

Protect Yourself - Use TDD

So I had this analogy pop into my head a while back and I've been sitting on it because, quite frankly, I was almost embarrassed to have thought of it.  I finally decided that I might as well post it since no one is going to read this anyway, so here goes:

Writing software without TDD is like having unprotected sex.  Its extremely irresponsible in this day and age when everyone is supposed to know better, but it still happens a lot.  Sure, it feels better, and let's face it in the heat of the moment you really don't want

 to take the time to make sure you've taken all of the right precautions...you might loose your edge.  The problem is if we don't do it we have that lingering fear in the back of our minds, that "What if?" that keeps popping up at the worst moments.  Most of the time its okay, and everything is fine, but it only takes one time for things to go wrong to make you regret your decisions.

So come on folks, we all know what we should be doing, so no more making excuses.  After a while you get used to it, and you find that the peace of mind it gives you far outweighs the momentary delights of living on the wild side.

Tags:

Taking the CodeRush Plunge

I recently decided to take the plunge and get CodeRush and Refactor! Pro (along with DxCore) loaded instead of Resharper.  Now, don't get me wrong, there is a lot I like about Resharper, but overall the performance was becoming an issue.  There were often problems with VS freezing for no particular reason, and then coming back as if nothing was wrong...I swear it was like my IDE had narcolepsy or something.

One of the things I noticed immediately about CodeRush was the fact that there was a single installer, and when I went to run it I was able to install it on all versions of Visual Studio, including the Orcas Beta.  This was nice when compared to Resharper's separate install for vs 2005 and vs 2003.  It also makes me feel good about improvements in the product being available for all versions of the IDE.  One thing that I noticed about R# was that there was some work being done in the VS 2005 version around performance, but that did not seem to trickle down to the VS 2003 version.  I think the big reason for this is the fact that CodeRush and Refactor! are implemented on top of DxCore, which provides a very clean abstraction from the scariness that is the Visual Studio integration layer.

Here are the things I really like about CodeRush/Refactor:

  • The visualizations are stunning!  No, seriously this is some amazing stuff.  Circles, arrows, animations, eye candy yes, but useful eye candy.
  • The Refactoring Live Preview is crazy brilliant.  Mark Miller mentioned this on a DNR episode, and I agree with his comment that the live preview allows you to discover new useful refactorings that may not be completely obvious from the name.
  • Performance is great.  'Nuf said.
  • It works with VB.Net.  Granted I don't use VB.Net, but some of my co-workers do, and occasionally I have to work on VB.Net projects.
  • Dynamic Templates rock.  The fact that I can create a new mnemonic for my type, and then use predefined prefixes and do vee<space> to create a new Employee Entity for example is pure bliss.
  • Template contexts are way cool.  By default they have NUnit templates defined, and with contexts, t<space> creates both a TestFixture class and a Test method
  • Markers and navigation are dreamy.
  • There are some crazy-cool template functions, like the ability to do a foreach within a template, so things like creating a switch/case statement for all items in an enum can be done easily.  This also powers a conditional to case refactoring that is pretty sweet.

Here are the things that I miss from Resharper:

  • Automatically adding a using statement in VS 2003 was sweet.  VS 2005 can do it with the buit-in intellisense features, but I got very used to it.
  • The VS 2003 test runner was very nice.  I use the Testdriven.Net plugin, which I cannot live without, but I like the graphical runner in the IDE.  The free test runner from JetBrains is for VS 2005 only, so it doesn't help those of us in VS 2003.  I do like the fact that they released it as a free tool, though.
  • The "Extract Field" refactoring doesn't exist in Refactor!...This shocked me a lot.
  • The Find Usages task.  This I think is part of the reason why R# was slow, but it did a brilliant job.  I think the rename in R# was more powerful as well.  I think there is a rename in Beta for Refactor! that is supposed to be able to work accross an entire project/solution, but I haven't had a chance to really test it yet.
  • The pre-build error checking is nice.

The good news is that the DxCore extensibility model means that most if not all of these items could be recreated.  The bad news is that there isn't a lot of documentation around the extensibility model, particularly when it comes to creating new refactorings.  The test runner is one of the most painful points for me right now, so I've started exploring the process of creating one using the DxCore APIs.  It opens up the possibility of refining things too, which would be nice.  What I would really like would be the ability to detect and integrate with TestDriven.Net.

The folks over at Eleutian are evidently running both, which they claim is possible with some tweaking, but the performance issues for VS 2003 are the biggest downer on the R# side, so I will probably not go down that path.  I may load up the test runner for VS 2005, unless I get some time to try and build one using DxCore, in which case I'll share it with the rest of the world.

Tags:

More On Testing and &quot;Friend&quot; Assemblies

So if you recall from some of my earlier posts, I've talked about the concept of the "Friend" class in C++ and how it could apply to TDD within .Net.  Well, today, with the help of Roy Osherove, I just stumbled upon the InternalsVisibleToAttribute within .Net 2.0.  This allows you to specify within one assembly, another assembly that should have access to the internal members of your assembly.  This is genius, and goes a long way towards allowing you to keep your code encapsulated, while still being testable.  If we could just get them to go one step farther, and allow for access to private and protected members as well, life would be good, and there would be no more of this OOD vs TOOD junk.

The other interesting thing about this is that it could allow you to give a separate utility...say the Castle Microkernel, access to internal class constructors, and thus enforce creation of your objects through the Kernel from outside assemblies.  This is actually a feature I am desperately wanting in my current project,  but sadly, I am limited to .Net 1.1, so I can't quite get there.

Here is a quick look at how this works.  Here is a very unrealistic class in an assembly that I want to test:

class TestClass
{
    internal TestClass()
    {}

    private bool PrivateMethod()
    {
        return false;
    }

    internal bool SomeMethod()
    {
        return true;
    }

    public string PublicMethod()
    {
        return "You can see me";
    }
}

Now, I add the following to the AssemblyInfo.cs file:

[assembly: InternalsVisibleTo("TestAssembly")]

And here is what Intellisense looks like in my test class

Not bad.  Overall I would say this is defiantly a good feature to have in your toolbox.  Internals are not perfect, but they are much more versatile than a lot of folks give them credit for.  Now if only I could get something like this in .Net 1.1

Tags: