subtext comments edit

One feature of Windows Live Writer that Subtext supports is the ability to edit your post slug? What is the URL slug associated with a blog post? What is the URL slug?

Take a quick look in the address bar and you should notice that the URL ends with “editing-post-slugs.aspx”. That bold part is the post slug. It’s a human friendly URL portion that identifies this blog post, as opposed to using some integer id.

For a long time, Subtext had the ability to automatically convert your blog post title into friendlier URLs. However, as with most automatic efforts, there are cases where it falls a bit short.

For example, suppose I started writing the following post with the following title:

editing-post-in-wlw

When I post it, the URL ends up being a bit ugly, though Subtext does give a good faith effort.

ugly-url-subtext

With Windows live writer, there’s a little double hash mark at the bottom that you can click to expand, providing more options. In the Slug: field, enter a cleaner URL.

editing-slug-in-wlw

Now when you publish this post, the URL will end with the slug that you specified.

If you use the Subtext Web Admin to post, we’ve had this feature all along in the Advanced Options section. It’s the Entry Name field (which I think we should call Entry Name Slug since Slug seems to be the standard term for this.

Of course when we come out with our MVC version, we can get rid of that annoying .aspx at the end. :)

Technorati Tags: subtext,windows live writer,wlw

personal comments edit

It’s been a long time coming, but we are finally ready to release Subtext 2.0. As I mentioned in April (was it that long ago!?), this is scaled down a bit from our original 2.0 plans. But even so, we have a lot of new goodness in here. It’s not just a bug fix release, though there are plenty of those too.

Highlights

With this release, Subtext has top notch support for Windows Live Writer thanks to some check-ins from Tim Heuer.

  • Enhanced MetaWeblog API implementation to support providing a “slug” URL name for the post.  This gives the user the option to use the default URL naming, the “auto-friendly” or now to override that with your own slug name.
  • Fixed a bug in the SiteMap handler for blogs not hosted at root domains.  Would love people to test this out.
  • Added support for WordPress API functions of: newPage, editPage, getPages, newCategory
  • Simple modification to the Windows Live Writer manifest to prevent those who think they can future post :-)
  • Tag-based RSS syndicator

Other highlights

  • New CSS-Based Admin Design That Makes Better Use of Space
  • Ability to set a separate skin for mobile devices
  • Streamlined Installation Process. I tried to remove unnecessary steps and make this more robust.
  • Support for Enclosures (See Simo’s great post on this for more details)
  • CSS and JS optimizations (Simo has more interesting details on this).
  • Setting a date in the future for publishing posts (again, Simo has more details).
  • Login to your blog using OpenID, as well as use your blog as an OpenId Delegate

Notes for new installations

The install package includes a default Subtext2.0.mdf file for SQL

  1. If you plan to run your blog off of SQL Express, installation is as easy as copying the install files to your webroot. If you’re not using SQL Express, but plan to use SQL Server 2005, you can attach to the supplied .mdf file and use it as your database.

Notes for upgrading

In the app_data folder of the install package, feel free to delete the database files there. They only apply to new installs.

We also include a zip file with just the SQL upgrade scripts. This is sometimes useful for those who run into problems with the upgrade procedure.

Full upgrade notes are on the Subtext project website.

So what’s next for Subtext?

The Subtext team is fired up to get their feet wet using ASP.NET MVC, and I can’t blame them. So at this point, we’re starting preliminary planning work for Subtext 3.0, the next major version of Subtext which will be a ground-up rewrite pulling in as much code from 2.0 along the way of course.

But that doesn’t mean we’re abandoning the 2.0 line immediately. I would expect to see several small incremental releases of the 2.* line even as we start on 3.0 with fires lit under our butts. Subtext 3.0 is in the very early stages of planning taking a long term look into the future.

After all, there’s still a lot of infrastructure decisions to be made, as well as requirements gathering. In what ways do we want to be just like Subtext 2.0? In what ways do we want to completely change the architecture?

Some of the decisions we need to make, just as a start:

  1. Where do we host? Do we stick with SourceForge or go elsewhere?
  2. What data access layer/ORM tooling should we use?
  3. What DI framework do we choose?
  4. What do we use for communication and documentation?
  5. What should our database design look like?
  6. Should we change how we handle multi-tenancy?

In any case, it’s been a fun ride so far, and I hope we can keep our momentum going in producing a great blogging platform for ASP.NET.

And before I forget, here’s the download page link.

Tags: subtext

asp.net, asp.net mvc comments edit

In his Practical Review of ASP.NET MVC, Josh Charles provides a helpful review of ASP.NET MVC from a Rails developer’s perspective. It seemed fair and balanced, and the end result is that there’s room for improvement, which we’re taking to heart.

However, that’s not the part that caught my attention. He mentioned that he wrote a cycle method but couldn’t write it as an extension method to HtmlHelper.

this was an instance method that would take two strings and return the one that it didn’t return the last time it was called. In my templates, I used this to change the classes for each row of data, to give them different background colors. I considered writing an extension method to the Html object used for other Html operations in the view page, but this method specifically required the use of an additional private variable, so that would not work.

If you don’t mind cheating a bit, there is a way to write this as an extension method. And while we’re doing that, why stop at only two strings? Why not take an indefinite number? :)

public static string Cycle(this HtmlHelper html, params string[] strings) {
    var context = html.ViewContext.HttpContext;
    int index = Convert.ToInt32(context.Items["cycle_index"]);

    string returnValue = strings[index % strings.Length];

    html.ViewContext.HttpContext.Items["cycle_index"] = ++index;
    return returnValue;
}

Perhaps allowing an indefinite number of strings is overkill (who ever heard of a table with tri-color highlighting?) but I thought it was fun to do regardless. Here’s an example of usage with three different CSS styles:

<style>
    .first {background-color: #ddd;}
    .second {background-color: khaki;}
    .third {background-color: #fdd;}
</style>

<table>
<% for (int i = 0; i < 5; i++) { %>
    <tr class="<%= Html.Cycle("first", "second", "third") %>">
        <td>Stuff</td>
    </tr>
<% } %>
</table>

And the output…

<table><tbody>
    <tr class="first">
      <td>Stuff</td>
    </tr>

    <tr class="second">
      <td>Stuff</td>
    </tr>

    <tr class="third">
      <td>Stuff</td>
    </tr>

    <tr class="first">
      <td>Stuff</td>
    </tr>

    <tr class="second">
      <td>Stuff</td>
    </tr>
  </tbody></table>

With this, go forth and spread tri-color highlighted tables all over the web. Or if you’re really crazy player, go with four color highlighting!

Technorati Tags: aspnetmvc,helpers,review

asp.net, asp.net mvc comments edit

phil-in-office

Recently, Adam Kinney came by my office to interview me for a Channel 9 episode discussing ASP.NET MVC CodePlex Preview 4.

I’ve known Adam for a long time, even before he joined Microsoft. I think we met (in person) at Tech-Ed 2003.

In any case, we talk a bit about ASP.NET MVC and Preview 4, all the while I tried very hard not to put my foot in my mouth. At the end there are some outtakes of me impersonating Scott Hanselman doing an impersonation of Sean Conery. That wasn’t to make fun of Scott, but totally out of love and respect. ;)

On Gaming

In the interview, I mentioned that I used to work at a skill gaming company called SkillJam which is no longer around. We had a tournament engine that allowed users to play games of skill for money. I worked on the back-end technologies such as our mobile gaming infrastructure which was well reviewed by GameSpot.

SkillJam is no longer around as it was bought by FUN Technologies (yes, I literally worked for “Fun” back then) and subsumed into World Winner.

In any case, one of the sharpest coworkers that I worked with there went out on his own to start a new game development company called CasualCafe. This guy was the one who lived in the world of writing low-level C++ code, anti-cheat techniques, and game engines. If you are into the genre of “Casual Games” (such as Bejewelled, Solitaire, etc…) be sure to check it out.

Books on My Shelf

Via Twitter, James Avery was more interested in the books on my shelf than what I was saying (I don’t blame him). In case you were wondering, here’s a partial list:

There are other books up there, but these are the ones I’ve read cover-to-cover and can recommend.

Technorati Tags: aspnetmvc,books,channel9

tdd, code comments edit

A while back I talked about how testable code helps manage complexity. In that post, I mentioned one common rebuttal to certain design decisions made in code in order to make it more testable.

Why would I want to do XYZ just do improve testability?

integrated-circuit Recently, I heard one variation of this comment in the comments to my post on unit test boundaries. Several people suggested that it’s fine to have unit tests access the database, after all, the code relies on data from the database, it should be tested.

Implicit in this statement is the question, “Why would I want to abstract away the data access just to improve testability?

Keep in mind, I never said you shouldn’t test your code’s interaction with the database. You absolutely should. I merely categorized that sort of test as a different sort of test - an integration test. You might still use your favorite unit testing framework to automate such a test, but I suggest trying to keep it in a separate test suite.

The authors of The Pragmatic Programmer: From Journeyman to Master have a great answer to this question with their comparison to Integrated Circuit’s, which have features designed specifically to enable testability.

The “Design For Test” Wikipedia entry refers to name as encompassing a range of design techniques for adding features to microelectronic hardware in order to make it testable. Examples of these techniques show up as early as the 1940s/50s. So designing for testability is not some whiz-bangy latest methodology flavor of the day the crazy kids are doing.

One key benefit to these techniques is that components can be tested in relative isolation. You don’t have to place them into a product in order to test them, though at the same time, they can be tested while within the product.

So in answer to the original question, I’d ask, “Why wouldn’t we design for testability?”

I think this analogy illustrates one reason why I don’t want my unit tests talking to the database (apart from wanting the tests to run fast). Ideally, someone else down the road, new to the project, should be able to get the latest code from source control and run the unit tests immediately without having to go through the pains of setting up an environment with the correct database.

Another benefit of abstracting away the database so that your code is testable and doesn’t cross boundaries is that your code is then not so dependent on a particular database. I used to argue that there’s no need to insulate your code from the particular database that you are using. I’ve never been on a project where the customer suddenly switches from SQL Server to Oracle. That sort of drastic change very rarely happens.

But it turns out that I have been on projects where we switched from SQL Server 6.5 to 7 (and from 7 to 2000 and so on). Upgrades can be nearly as drastic as choosing a different database vendor. Having your code isolated from your choice of database provides some nice peace of mind here.

Tags: IC , Integrated Circuit , TDD , Unit Testing

asp.net mvc, asp.net comments edit

UPDATE: I linked to the wrong post. I corrected the link.

During the recent Insiders summit, Wally cornered me into recording a really short video demonstrating a feature of ASP.NET MVC. I decided to sprinkle a little Ajax in my demo by showing how to use jQuery to call an action that returns a JsonResult.

Specifically, I show how to update a couple of regions in the page (two dom elements) with data pulled from the server. I then add a little sparkle to the demo by implementing the ubiquitous yellow fade when adding the content to the DOM. As you’re watching it, you’ll notice that I’m making it up on the fly based on another demo I did earlier that day.

He’s posted the video here in show #106 121. That’s heckuva a lot of shows Wally!

Technorati Tags: aspnetmvc,ajax,jquery

personal, code comments edit

It’s a quiet friday afternoon with all of our devs in training today, so I figured I’d take a breather and respond to this meme I’ve been tagged with by Simone, Keyvan, Steve and others.

How Old Were You When You Started Programming?

Have I even started really programming yet? I guess I got my first taste when I was around eight with my first computer, a TRS-80 Color Computer.

phil-with-trs-80

That sucker could display 9 colors, all at once, believe it or not. My programming experience back then was pretty minimal. My dad and I mostly spent hours typing in program listings from books, complete with pages of DATA lines consisting entirely of 0s and 1s. Pretty much typing by hand the equivalent of binary resources. I also wrote simple programs that would draw pictures and my dumb attempts at Zork-like text adventures.

How Did You Get Started In Programming?

Well I would write dumb little programs for my TRS-80, then Commodore 128, then Amiga. But I never wrote any programs of any significance till I took a C and C++ class in college. Even then, those programs were not “real world” programs, but simple assignments. It wasn’t till after college when I had to get a J-O-B that I learned how to really program.

And it was a rough start, writing the most knotty spaghetti ASP code in VBScript ever. It wasn’t till I read Code Complete that I realized that I wasn’t programming yet, I was barfing code.

What Was Your First Language?

English. My first programming language was BASIC for the TRS-80. My first professional language was VBScript. My first Object Oriented language was C++.

What Was The First Real Program You Wrote?

Man, I can barely remember that far back. All I remember was on my first day of my first programming job, a helpful consultant/coworker showing me the ropes. The main thing she taught me that day was when looping through a RecordSet, don’t forget the rs.MoveNext call, or else!

Around that time, I started working on a website for a company called MyLaunch.com which later became Launch.com which later got bought by Yahoo. That was the first large website I worked on and the place I had my first and worse major production bug ever. It was a lot of fun because I also signed up on the site and would interact with the other members, since it was a community music site.

What Languages Have You Used Since You Started Programming?

What is this? Some sort of interview? The programming languages I’ve used professionally are: BASIC, Visual Basic, VBScript, Java, J++, Ruby, C#.

What Was Your First Programming Gig?

As I mentioned before, it was right after college I got a job at a consulting firm named Sequoia Softworks in Seal Beach, CA. We had an office right on main street near the beach above some antique store or something. We later changed our name to Solien. They’re still around, but their site needs some love.

If You Knew Then What You Know Now, Would You Have Started Programming?

Well in between investing large sums of money in the right stocks and getting out at the right time, yes, absolutely! I love to write code and write about code.

If There is One Thing You Learned Along the Way That You Would Tell New Developers, What Would It Be?

Learn to write and communicate well. Software development is rich in ideas and being able to communicate your ideas well will get you places. And keep an open mind. Things you’re absolutely sure about now, you might not be so sure about tomorrow.

What’s the Most Fun You’ve Ever Had … Programming?

Hacking on Open Source projects such as Subtext. Recently, working on my [IronRuby

  • MVC prototype](https://haacked.com/archive/2008/07/20/ironruby-aspnetmvc-prototype.aspx “IronRuby and MVC”) has been a lot of fun. I find it fun to try out new things as well as making old things better.

Technorati Tags: Personal

tdd, code comments edit

One principle to follow when writing a unit test is that a unit test should ideally not cross boundaries.

965948_51171615

Michael Feathers takes a harder stance in saying…

A test is not a unit test if:

  • It talks to the database
  • It communicates across the network
  • It touches the file system
  • It can’t run at the same time as any of your other unit tests
  • You have to do special things to your environment (such as editing config files) to run it

Tests that do these things aren’t bad. Often they are worth writing, and they can be written in a unit test harness. However, it is important to be able to separate them from true unit tests so that we can keep a set of tests that we can run fast whenever we make our changes.

Speed isn’t the only benefit of following these rules. In order to make sure your tests don’t reach across boundaries, you have to make sure the unit under test is easily decoupled from code across its boundary, which provides benefits for the code being tested.

Suppose you have a function that pulls a list of coordinates from the database and calculated the best fit line for those coordinates. Your unit test for this method should ideally not make an actual database call, as that is reaching across a boundary and coupling your method to a specific data access layer.

Reaching across a boundary is not the only sin of this method. Data access is an orthogonal concern to calculating the best-fit line of a series of points. In The Pragmatic Programmer, Andrew Hunt and Dave Thomas tout Orthogonality as a key trait of well written code. In an interview on artima.com, Andy describes orthogonality like so:

The basic idea of orthogonality is that things that are not related conceptually should not be related in the system. Parts of the architecture that really have nothing to do with the other, such as the database and the UI, should not need to be changed together. A change to one should not cause a change to the other. Unfortunately, we’ve seen systems throughout our careers where that’s not the case.

Ideally, you would refactor the method so that the data the method needs is provided to it via some other means (another method passing the data via arguments, dependency injection, whatever). That other means, whatever it is, can perform the necessary data access: that’s not your concern at this moment. You aren’t testing that other means (right now at least, you might later), you’re focused on testing this unit.

This isolation enforced by unit test can be challenging, as it’s easy to get distracted by these other orthogonal concerns. For example, if this method doesn’t do data access, which one does? However, having the discipline to focus on the unit being tested can help shape your code so that it follows the single responsibility principle (SRP for short). If your test needs to access an external resource, it might just be violating SRP.

This provides several key benefits.

  • Your function is no longer tightly coupled to the current system. You could easily move it to another system that happened to have a different data access layer.
  • Your unit test of this function no longer needs to access the database, helping to keep execution of your unit tests extremely fast.
  • It keeps your unit test from being too fragile. Changes to the data access layer will not affect this function, and therefore the unit test of this function.

All this decoupling will provide long term benefits for the maintainability of your code.

Technorati Tags: TDD,Unit Test,Orthogonality,Single Responsibility Principle

asp.net mvc, code, dlr comments edit

UPDATE 02.17.2009: I posted about a newer version of this prototype for ASP.NET MVC RC

Update: I updated the source today. It now has minimal support for layouts. It needs more improvement for sure.

In June, John Lam wrote about a demo he gave at Tech-Ed 2008 where he showed IronRuby running on ASP.NET MVC. He posted the code for the demo online, but it relied on an unreleased version of MVC, so the code didn’t actually work.

IronRuby on ASP.NET MVC
Demo Now that Preview 4 is out, I revisited the prototype and got it working again. I use the term working loosely here. Yeah, it works, but it is really rough around the edges. As in, get a bunch of splinters rough. At least it looks better as I did take a moment to use a CSS layout from Free CSS Templates slightly tweaked by me.

Getting the Prototype Up And Running

The IronRuby assemblies are based on an internal build, so they aren’t the same version as the publicly available ones. As such, they are not fully signed so you might get an ugly error message when you try to run the demo. You’ll need to add a verification entry into the GAC using the sn –Vr assemblyname.dll command.

I was lazy and just ran the following to add a verification entry for any assembly (note: there is a security risk in doing this):

sn –Vr *,*

And when I was done, I ran:

sn –Vu *,*

to remove that catch-all verification entry.

Other Notes

I made a few small improvements to the project since John posted the code. I added helper overloads that accept ruby hashes, for example. This allows you to do the following within the view:

<%= $html.ActionLink("Home", {:controller => "Home", :action => "index"}) %>

I also implemented more of the application, including the ability to edit an item. That forced me to get some more of the form helpers working with IronRuby.

As I mentioned in my previous post on this topic, IronRuby and ASP.NET MVC BFFs Forever:

Disclaimer: This is all a very rough prototype that we’ve been doing in our spare time for fun. We just wanted to prove this could work at all.

If this sort of stuff interests you, have fun with it. I’ll try and post updates as we take this prototype further. It has definitely been a worthwhile exercise as we’ve found many areas for improvement in our extensibility layer. I believe ASP.NET MVC will be better overall because we spent the time to do this.

And before I forget, here’s the DOWNLOAD LINK.

Attributions: The CSS layout and ruby logo are both licensed under the Creative Creative Commons Attribution-ShareAlike 2.5 License. Full attribution is within the source.

Technorati Tags: Ironruby,aspnetmvc

asp.net mvc, asp.net comments edit

(If you want to skip all the blah blah blah, go straight to the release)

What I love about working with The Gu (aka ScottGu, the man with many aliases) is that he makes my life easier with his gargantuan and detailed blog posts covering the features of each release. This allows me to follow up and fill in some details with a much shorter post, as by the time we get a release out the door, I’m usually too exhausted to write such a detailed post as he does. Yeah, excuses excuses.

In his latest post, Scott covers the ASP.NET MVC CodePlex Preview 4 release in two parts. This is the next in a continuing series of preview releases that alternate between full CTP level releases on ASP.NET and interim releases on CodePlex. Unlike previous CodePlex releases, this one contains an MSI installer for convenience. There are still some rough spots with some of the new features as we tried to get a lot into this release to elicit feedback. In fact, I’ve been doing some app building today and have already run into some areas for improvements with the Ajax helpers. I look forward to hearing your feedback as well.

MVC Futures

One thing you’ll notice in the project template that Scott didn’t cover in much detail is that we include a new assembly, Microsoft.Web.Mvc.dll. The release notes explain what this is.

The ASP.NET MVC team builds prototypes for a lot of features during the course of normal development. Some of these features will not be included in the RTM release, but are very likely to be included in a future full release. We’ve moved many of these features into a separate assembly, Microsoft.Web.Mvc.dll.

This follows what the ASP.NET’s team intends the term Futures to mean when it comes to products. Futures should contain features that we think has a decent chance of making it into the framework. If we implement something we are pretty sure we have no intention of including in the framework, we’ll typically post it as a blog sample or something to that effect.

Component Controller

For those that have used this, you’ll notice that we removed the ComponentController class. Instead, we renamed RenderComponent to be RenderAction and re-implemented it so that it works against a normal controller. This code is was moved to the MVC Futures assembly since we’re not planning to include it in the RTM.

My personal opinion is that this violates the separation of concerns so important to the MVC pattern. Having a method within your view calling back into a controller in order to render out a bit more view makes me feel a wee bit dirty ;). We’re developing prototypes for an alternative approach. In the meanwhile, I recognize that for a small sacrifice of pattern purity, this method is very useful, hence its inclusion in the MVC Futures assembly, but do understand that you use it at your own risk.

What’s Next?

The roadmap for ASP.NET MVC has been up on the CodePlex site for a while. We still have more cleanup and implementation work to do on the Ajax features, as well as existing and new helper methods. Likewise, we are tackling the problem of how should you report validation errors to the user via a common error reporting mechanism. This might not handle validation itself, but gives everyone a common place to put validation messages and allows for some of HTML helpers to be aware of these messages and render themselves accordingly.

And before I forget, you can download ASP.NET MVC CodePlex Preview 4 from the release page.

Technorati Tags: aspnetmvc

asp.net mvc, asp.net comments edit

By default, ASP.NET Routing ignores requests for files that do not exist on disk. I explained the reason for this in a previous post on upcoming routing changes.

Long story short, we didn’t want routing to attempt to route requests for static files such as images. Unfortunately, this caused us a headache when we remembered that many features of ASP.NET make requests for .axd files which do not exist on disk.

To fix this, we included a new extension method on RouteCollection, IgnoreRoute, that creates a Route mapped to the StopRoutingHandler route handler (class that implements IRouteHandler). Effectively, any request that matches an “ignore route” will be ignored by routing and normal ASP.NET handling will occur based on existing http handler mappings.

Hence in our default template, you’ll notice we have the following route defined.

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

This handles the standard .axd requests.

However, there are other cases where you might have requests for files that don’t exist on disk. For example, if you register an HTTP Handler directly to a type that implements IHttpHandler. Not to mention requests for favicon.ico that the browser makes automatically. ASP.NET Routing attempts to route these requests to a controller.

One solution to this is to add an appropriate ignore route to indicate that routing should ignore these requests. Unfortunately, we can’t do something like this: {*path}.aspx/{*pathinfo}

We only allow one catch-all route and it must happen at the end of the URL. However, you can take the following approach. In this example, I added the following two routes.

routes.IgnoreRoute("{*allaspx}", new {allaspx=@".*\.aspx(/.*)?"});
routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"});

What I’m doing here is a technique Eilon showed me which is to map all URLs to these routes, but then restrict which routes to ignore via the constraints dictionary. So in this case, these routes will match (and thus ignore) all requests for favicon.ico (no matter which directory) as well as requests for a .aspx file. Since we told routing to ignore these requests, normal ASP.NET processing of these requests will occur.

Technorati Tags: aspnetmvc,routing

asp.net mvc, asp.net, code comments edit

We all know that it is bad bad bad to trust user input. I don’t care if your users are all ascetic monks in a remote monastery, do not trust their input. However, user input often likes to put on sheep’s clothing and disguise itself as something else entirely, such as the case with ViewState.

Another example of this is highlighted in the latest entry of his excellent series of ASP.NET MVC tips. In this post, Stephen Walther writes about how cookie values and server variables can be passed as parameters to action methods.

Immediately, commenters understably asked whether this was safe or not. One person went so far as to call this a security hole in controller actions.

However, to be extremely nitpicky, the security implication isn’t in passing server variables this way. That’s perfectly safe. The security implication is in trusting the values passed to an action method in the first place. If your action method makes decisions with security implications based on assuming that these values are accurate, then you have a potential security problem.

Keep in mind, many of these values can be spoofed with or without ASP.NET MVC. Many of the server variables should never be trusted no matter how you access them, whether via this technique or a call to Request.ServerVariables["variable_name"].

In fact, right there near the top of the MSDN documentation for the IIS Server Variables, it warns against trusting these values:

Some server variables get their information from HTTP headers. It is recommended that you distrust information in HTTP headers because this data can be falsified by malicious users.

In the same way, in a typical configuration for ASP.NET MVC, the parameter values for action methods come directly from the user in the form of the URL or Request parameters. This makes sense after all, since the whole point of a controller in the MVC pattern, according to Wikipedia, is to:

Processes and responds to events, typically user actions, and may invoke changes on the model.

The parameters to an action method generally correspond to user input. It’s really asking for trouble to have parameters in an action method that you consider to be anything but user input.

In the end, I don’t consider this a security flaw so much as a security lure. This is the type of thing that might tempt someone to do the wrong thing and trust these values. We will review this particular case and consider not passing in server variables into action methods, but doing so doesn’t really solve the fundamental issue. There are other ways to pass data to an action method (defaults on a route) that a developer might be tempted to trust (don’t trust it!).

Whether we change this or not, the fundamental issue is that developers should never trust user input and developers should always treat action parameter values as user input.

Tags: aspnetmvc , security

asp.net, asp.net mvc, code comments edit

Yesterday, I wrote a quick and dirty ASP.NET HttpModule for displaying the time that a request takes to process. Note that by turning on trace output for a page, you can get timing information for that page. But as far as I understand, and I need to double check this, this only applies to the page lifecycle, which might not have all the information you want in the context of ASP.NET MVC.

Not to mention, I just wanted to see a simple number at the end of the page and not have to wade through all that trace output. Also keep in mind that this number only applies to the time spent in the ASP.NET pipeline. It obviously doesn’t tell you the full time of the request from browser sending the request to the browser rendering the response. For that I would use something like Firebug in Firefox.

Here’s the code for the module. Note that it only works from local requests in Debug mode. That’s a safety precaution so that if someone accidentally deploys this to a production machine, they won’t see this number at the bottom.

using System;
using System.Diagnostics;
using System.Web;

public class TimingModule : IHttpModule {
  public void Dispose() {
  }

  public void Init(HttpApplication context) {
    context.BeginRequest += OnBeginRequest;
    context.EndRequest += OnEndRequest;
  }

  void OnBeginRequest(object sender, System.EventArgs e) {
    if (HttpContext.Current.Request.IsLocal 
        && HttpContext.Current.IsDebuggingEnabled) {
      var stopwatch = new Stopwatch();
      HttpContext.Current.Items["Stopwatch"] = stopwatch;
      stopwatch.Start();
    }
  }

  void OnEndRequest(object sender, System.EventArgs e) {
    if (HttpContext.Current.Request.IsLocal 
        && HttpContext.Current.IsDebuggingEnabled) {
      Stopwatch stopwatch = 
        (Stopwatch)HttpContext.Current.Items["Stopwatch"];
      stopwatch.Stop();

      TimeSpan ts = stopwatch.Elapsed;
      string elapsedTime = String.Format("{0}ms", ts.TotalMilliseconds);

      HttpContext.Current.Response.Write("<p>" + elapsedTime + "</p>");
    }
  }
}

Notice that I made use of the System.Diagnostics.Stopwatch class, which provides more accuracy than simply calling taking the difference between two calls to DateTime.Now.

In my web.config, I just needed to add the following to the httpModules section (replacing Namespace and AssemblyName with their appropriate values):

<httpModules>
  <!-- ...other modules... -->
  <add name="TimingModule" type="Namespace.TimingModule, AssemblyName" />
</httpModules>

For IIS 7, this configuration would go in the <modules /> section.

Lastly, don’t forget to set your website to debug mode by adding the following in your Web.config. If you want to test your perf in release mode, just remove the IsDebuggingEnabled clause in the module and you don’t need to make the following change.

<compilation debug="true">
<!-- ... -->
</compilation>

Hope you find this useful.

Technorati Tags: ASP.NET,performance,stopwatch

personal comments edit

I credit Google AdSense for really opening up the possibility for small blogs to become sources of passive income. Look around the web and you’ll see nearly every blog sport an AdSense ad or two…or three.

For most people, it amounts to a bit of pocket change - maybe enough money for a coffee or an occasional indulgence. But soon, the lure of adding more ads from other ad networks overwhelms publishers and soon blogs start to look more like the movie Idiocracy.

idiocracy

A while back, Jeff Atwood wrote about how content is becoming dwarfed by advertisements in his post, A World of Endless Advertisements, which is where I took that photo. I was heading down that path when I read his post and it gave me pause.

At that time, I had recently started a new business with a friend and we were struggling, so any source of extra income was welcome. But I was always hoping to tone it down a bit.

Now I’m at a pretty stable company, so I don’t necessarily need the extra income, but I don’t mind it because I also have a kid who can eat us out of house and home. Fortunately, I have the opportunity to have my cake and eat it too by removing all of my ads except for The Lounge. Hopefully this makes my site move farther and farther from the screenshot above.

James Avery and I go way back. He’s been involved with Subtext in the past, I contributed some chapters to a book he and Jim Holmes put together. Like many relationships forged in the online community, we’ve never actually met in person, but I feel like I’ve known the guy for a long time.

What I like about James is he’s a real hustler, which you have to be as an independent entrepreneur/consultant/contractor. He seems to be executing on a huge roster of ideas all at once all the time. I’ve gone that route, and found it both exhilarating and downright tough. So my hats off to James.

The other notable thing about The Lounge is that James is using ASP.NET MVC to build it out and is so far finding the experience to be a good one. Right James?

Technorati Tags: The Lounge,blog,ads

humor, personal comments edit

…and the feeling’s right.

phil-and-akumi If I can muster up the time and motivation, I like to try and post lighter more humorous fare on Fridays such as my recent RAS Syndrome post.

On this beautiful Friday day (is that redundant too?), I started off fresh out of ideas (and motivation) so I wasn’t planning on writing a blog post at all, until this was just handed to me.

Which Software Blogger Do Girls Like Better?

In this post, Nick Berardi takes a quick look around at the demographic information collected by Google’s new ad planner.

Consider for a moment, what this data represents. It is a huge database of information on surfing habits of perhaps nearly the entire Internet, collected via huge data centers consisting of unfathomable computing power (as well as power consumption). Not to mention the huge amount of data it represents and the incomprehensibly advanced statistical analysis algorithms that must be employed to properly sift this data.

Nick has all this power at his disposal to answer the pertinent question of the digital age.

Which geek blogger do chicks dig?

In the list, he compares bloggers such as Jeff Atwood (aka CodingHorror or is it CodingWhore, which might explain his results), Joel Spolsky (aka big red WTF guy), Scott Hanselman (aka Mr. “Writes About Hair”)… and then there’s me, the short end of the stick.

Now Jeff might have over 10 times the subscribers I have, Joel may be the most famous and respected of the bunch, and Scott may have the edge on me in terms of forefivehead, but guess who wins the only metric that matters?

That’s right, me suckas!

Eat that, CodingHorror!

Map Reduce FogCreek to FogWeak, Joel Spolsky!

Hanselminute is a minute too late, Scott Hanselman!

Of course, at this point is when my wife pinches her fingers together and holds them up to my temple and makes a loud hissing sound of air rushing out. After all, compared to the traffic level of these guys, my traffic is small enough that her periodic visits to my site would make a dent in the percentages.

And as my coworker Eilon points out, I’m celebrating what is effectively a made up score. “Hey everyone, I created this chart with this made up score, for which I have the highest one. I rock!” My retort is that his fascination with X-Box Achievement points is no different.

I guess I won’t quit my day job and become a male exotic dancer then. Carry on everyone.

Technorati Tags: humor,Friday,Ego

asp.net mvc, asp.net, code comments edit

When you create a new ASP.NET MVC project using our default templates, one of the things you might notice is that there is a web.config file within the Views directory. This file is there specifically to block direct access to a view.

Let’s look at the relevant sections.

For IIS 6 (and Cassini)

<add path="*.aspx" verb="*" 
  type="System.Web.HttpNotFoundHandler"/>
 

For IIS 7

<add name="BlockViewHandler" path="*.aspx" verb="*" 
  preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>

What these sections do is block all access to any file with the .aspx extension within the Views directory (or subdirectories). Note that access is blocked by mapping these file extensions to the HttpNotFoundHandler, so that a 404 error is returned when trying to access a view directly.

This works great if you are using all the ASP.NET MVC defaults, but what if you’re using an alternative view engine such as NHaml or NVelocity? It turns out you can directly request the view and see the code.

You’ll want to make sure to add extra lines within this web.config file with the appropriate file extensions. For example, if I were using NVelocity, I might add the following (in bold).

For IIS 6 (and Cassini)

<add path="*.aspx" verb="*" 
  type="System.Web.HttpNotFoundHandler"/>
<add path="*.vm" verb="*" 
  type="System.Web.HttpNotFoundHandler"/>
 

For IIS 7

<add name="BlockViewHandler" path="*.aspx" verb="*" 
  preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
<add name="BlockViewHandler" path="*.vm" verb="*" 
  preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>

You might be wondering why we don’t block access to all files within the Views directory. Excellent question! In part, because the Views directory is a common place to put other static content such as images, pdfs, audio files, etc… and we decided not to prevent that option.

However, we’re open to suggestions. We do have a content directory in the default template. We could consider requiring putting static files in there or in another directory other than Views. I’m not sure how people would feel if they couldn’t put assets intended to support Views within the Viewsfolder.

Technorati Tags: aspnetmvc,security,view engines

code comments edit

UPDATE: Updated the registry settings per James Curran’s comment. Thanks James!

One of the most useful registry hacks I use on a regular basis is one Robert McLaws wrote, the “ASP.NET 2.0 Web Server Here” Shell Extension. This shell extension adds a right click menu on any folder that will start WebDev.WebServer.exe (aka Cassini) pointing to that directory.

Webserver-Here

I recently had to repave my work machine and I couldn’t find the .reg file I created that would recreate this shell extension. When I brought up Robert’s page, I noticed that the settings he has are out of date for Visual Studio 2008.

Here is the updated registry settings for VS2008 (note, edit the registry at your own risk and this only has the works on my machine seal of approval).

32 bit (x86)

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\VS2008 WebServer]
@="ASP.NET Web Server Here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\VS2008 WebServer\command]
@="C:\\Program Files\\Common Files\\microsoft shared\\DevServer
\\9.0\\Webdev.WebServer.exe /port:8080 /path:\"%1\""

64 bit (x64)

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\VS2008 WebServer]
@="ASP.NET Web Server Here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\VS2008 WebServer\command]
@="C:\\Program Files (x86)\\Common Files\\microsoft shared\\DevServer
\\9.0\\Webdev.WebServer.exe /port:8080 /path:\"%1\""

For convenience, here is a zip file containing the reg files. The x64 one I tested on my machine. The x86 one I did not. If you installed Visual Studio into a non-standard directory, you might have to change the path within the registry file.

Technorati Tags: Tips,Registry,Visual Studio,Web Server

code comments edit

I used to find the smart tag really annoying in Visual Studio because it is such a small target to hit with the mouse. Silly me, trying to expand a smart tag with a mouse.

VS-smart-tag 

When you highlight the tag with your mouse, it tells you that the keyboard combination of ALT + SHIFT + F10 will expand the menu.

What it doesn’t tell you is that there’s a two key combination that will also expand it. I learned this one from Karen Liu of the C# IDE team who also happens to have a blog post with a nice collection of other tips and tricks written last year.

Just hit the CTRL key plus the period key (CTRL + .)

VS-smart-tag-expansion

I really like this approach when performing renames within Visual Studio because it’s totally contextual. Rather than starting with a rename refactoring, I can instead just start renaming something and the smart tag shows up and all I have to do is hit CTRL + . and then ENTER. Booyah!

Technorati Tags: Tips,Visual Studio,Shortcuts,Keyboard

asp.net mvc, asp.net, code comments edit

When approaching an extensibility model, I often find cases in which I want to merely tweak the existing behavior of the default implementation and wish I didn’t have to create a whole new specific type to do so.

paint

Instead of creating a specific type, I tend to write a decorator class that implements the interface and takes in both the default instance of that interface and a delegate (specified using a lambda of course).

Let’s look at a quick example to make all this abstract talk more concrete. I’m playing around with the NVelocity View Engine for ASP.NET MVC from the MvcContrib project. Rather than have each controller specify the view engine, I’d really like to specify this in just one place.

I could take the time to setup a DI container, but I’m feeling lazy and this is just a simple prototype application so I planned to just implement the IControllerFactory interface and have it set the view engine after creating the controller.

For those not intimately acquainted with ASP.NET MVC, you can override how the framework instantiates controllers by implementing the IControllerFactory interface.

However, at this point, I realized I was creating these one-off controller factories all the time. What I really wanted was some way to decorate the existing controller factory with a bit of extra logic. What I did was write an extension method that allowed me to do the following in my Global.asax.cs file.

ControllerBuilder.Current.Decorate(
  (current, context, controllerName) => 
  {
    var controller = current.CreateController(context, controllerName) 
      as Controller;
    if (controller != null) {
      controller.ViewEngine = new NVelocityViewFactory();
    }
    return controller;
  }
);

It’s a little funky looking, but what is happening here is that I am calling a new Decorate method and passing it a lambda. That lambda will be used to decorate or wrap the current controller factory and will get called when it is time to instantiate a Controller instance.

However, the lambda always receives the original controller factory so it can use it if needed. So in effect, the lambda wraps or decorates whatever the current controller factory happens to be.

In this case, all my lambda is doing is using the default controller to create the controller, and then it sets a property of that controller after the fact. However, if I wanted to, I could have had my lambda completely override creating the controller.

Here is the the code for the extension method to ControllerBuilder.

public static class ControllerFactoryExtensions {
  public static void Decorate(this ControllerBuilder builder
  ,Func<IControllerFactory, RequestContext, string, IController> decorator) {
    IControllerFactory current = builder.GetControllerFactory();
    builder.SetControllerFactory(
      new DelegatingControllerFactory(current, decorator));
  }
}

As you can see, under the hood, I am actually replacing the current controller factory with a new one called DelegatingControllerFactory. But the implementation for this new factory is really simple. It simply calls a delegate that you supply. As far as the user of the Decorate method is concerned, this class doesn’t really exist.

internal class DelegatingControllerFactory : IControllerFactory {
  Func<IControllerFactory, RequestContext, string, IController> _factory;
  IControllerFactory _wrappedFactory;

  public DelegatingControllerFactory(IControllerFactory current
    , Func<IControllerFactory
    , RequestContext, string, IController> factoryDelegate) {
    if (factoryDelegate == null) {
      throw new ArgumentNullException("factoryDelegate");
    }
    _wrappedFactory = current;
    _factory = factoryDelegate;
  }

  IController IControllerFactory.CreateController(RequestContext context
  , string controllerName) {
      return _factory(_wrappedFactory, context, controllerName);
  }

  void IControllerFactory.DisposeController(IController controller) {
    if (controller is IDisposable) {
      ((IDisposable)controller).Dispose();
    }
  }
}

With this in place, the next time I need to implement a one-off controller factory, I can simply decorate the current controller factory instead.

I’m starting to find myself using this pattern in a lot of places. The potential downside of this approach is that if someone else comes along who has to maintain it, they might find it difficult to understand if they’re not well acquainted with lambdas and delegates.

So it is a bit of a tradeoff between convenience for the code author and readability for the code reader.

Technorati Tags: aspnetmvc,controller factor,decorator,patterns

aspnet, aspnetmvc, code, patterns comments edit

Or, as my recent inbox tells me, you’re not afraid to ask. ;)

A coworker recently asked for some good resources on getting up to speed on the Model View Controller (MVC) pattern. Around the same time, I received another email talking about how people are confused around the difference between MVC and the Model View Presenter (MVP) pattern.

mvcNo better opportunity to apply the DRY principle by answering some of these questions with a blog post.

MVC

The first place to start digging into the MVC pattern is to look at the Wikipedia entry. That’ll get you a nice brief summary of the pattern along with a list of resources.

In MVC, the Model represents the information (the data) of the application and the business rules used to manipulate the data, the View corresponds to elements of the user interface such as text, checkbox items, and so forth, and the Controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.

trygve If you’re really into it, you can go directly to the source and read the original papers from Trygve Reenskaug, the inventor of the pattern.

There you’ll learn from the original paper (pdf) that the initial name for the pattern was Thing-Model-View-Editor. The pattern was baked via a process of extracting, improving, and articulating existing command and control patterns used in the operation of Norwegian ship yards in order to streamline and improve operations.

MVP

That ought to get you going with the MVC pattern. Now onto Model View Presenter, which was a response to the inadequacies of the MVC pattern when applied to modern component based graphical user interfaces. In modern GUI systems, GUI components themselves handle user input such as mouse movements and clicks, rather than some central controller.

MVP was popularized by Taligent in this paper on the subject (pdf). More recently, Martin Fowler suggested retiring this pattern in favor of two variants: Supervising Controller and Passive View.

The Difference?

So what’s the diff between MVC and MVP? Using GitHub, here it is!

246

Sorry, bad joke but I couldn’t resist.

The two patterns are similar in that they both are concerned with separating concerns and they both contain Models and Views. Many consider the MVP pattern to simply be a variant of the MVC pattern. The key difference is in how both patterns solve the following question: Who handles the user input?

With MVC, it’s always the controller’s responsibility to handle mouse and keyboard events. With MVP, GUI components themselves initially handle the user’s input, but delegate to the interpretation of that input to the presenter. This has often been called “Twisting the Triad”, which refers to rotating the three elements of the MVC triangle and replacing the “C” with “P” in order to get MVP.

What About The Web?

If you were playing close attention, most of these articles focus on rich client applications. Applying these patterns to the web is a very different beast because of the stateless nature of the web.

ASP.NET WebForms, for example, attempts to emulate the rich client development paradigm via the use of ViewState. This is why many attempts to apply patterns to ASP.NET focus on the MVP pattern because the MVP pattern is more appropriate for a rich client application with GUI components. A while back I even tossed my Supervising Controller sample into the ring. The Patterns and Practices group at Microsoft ship an MVP Bundle for ASP.NET.

However, many web platforms embrace the stateless nature of the web and forego attempting to simulate a state-full rich client development environment. In such systems, a tweaked MVC pattern is more applicable.

This pattern has been adjusted for the Web for your application development enjoyment.

AFAIK, Struts, a Java web framework, is one of the first widely used web frameworks employing the MVC pattern, though most people now look at Rails as being the tipping point that really brought MVC to the web and popularized the MVC pattern for web applications.

ASP.NET MVC is a new (in development) alternative framework for ASP.NET developers that makes it easy for developers to follow the MVC pattern. This framework employs the MVC pattern rather than the MVP pattern because it does not attempt to emulate rich client development, and thus the MVC pattern is more appropriate.

More Reading

There’s a lot of good content out there that puts these patterns into historical and categorical perspective. Besides the links already mentioned in this paper, I recommend checking out…