Monthly Archives: June 2011

Nl2br example in ASP.NET MVC 3

I’ve been playing around with ASP.NET 3.5 this weekend, and am building my first real website with it. Much to my horror, as a long-time Java developer, I’m finding it to be incredibly delightful to work with.

C# feels like a slightly-improved version of Java, the tooling is pretty good (even though I’m still not thrilled with the code editor in VS2010), the Razor syntax used in views is quite clean, and the whole thing is pretty easy to work with. It isn’t perfect, and I haven’t tried to go to production with my website yet, but all-in-all, it is a pretty good developer experience.

Working on my website this weekend, I ran into a problem that I – like probably every other web developer – have run into many times before: I needed to take some data that had line breaks in it and display it on a page, and somehow figure out how to convert those line endings into <br> tags. A lot of languages and frameworks have something built-in to handle this – PHP’s nl2br(), for example – but I couldn’t find anything in the documentation far ASP.NET MVC. This is a fairly trivial problem, but it is also a pretty common one and doing it wrong can lead to security problems, so I figured it was worth spending a few minutes figuring out the best way to do it and documenting it.

Doing some research, it seems like folks were recommending 2 main approaches to solving this:

1. Convert the line-endings to <br>’s before saving the content to the database. I didn’t care for this because saving HTML into the database complicates Cross-Site Scripting (XSS) defense. It also makes it problematic if you later want to display that same content outside of HTML (for example, in a mobile phone app).

2. Call Replace(“\r\n”, “<br>”) on the string when displaying it. I don’t care for this either – it seems repetitive (I’m lazy – I hate having to do something once, much less 500 times), and even worse, since you have to use @Html.Raw() to display it, it can open you up to XSS attacks.

Thankfully, MVC’s Html Helpers and C#’s extension methods provide a way to come up with a relatively simple and robust solution. My requirements were:

1. It had to be easy to use.
2. It had to protect against XSS attacks.
3. It should probably try to take into account the fact that there are (naturally) a number of different ways to end a line: \r\n on Windows, \r on really old Macs, and \n just about everywhere else.

This is what it ended up looking like:

static Regex LineEnding = new Regex(@"(\r\n|\r|\n)+");
public static MvcHtmlString Nl2br(this HtmlHelper html, string text, bool isXhtml = true)
  var encodedText = HttpUtility.HtmlEncode(text);
  var replacement = isXhtml ? "<br />" : "<br>";
  return MvcHtmlString.Create(LineEnding.Replace(encodedText, replacement));

And here is how you’d use it:


And here are a few tests for good measure:

public void TestCRLF()
    var input = "Hello\r\nWorld!";
    string result = MyHelpers.Nl2br(null, input).ToHtmlString();
    var expected = "Hello<br />World!";
    Assert.AreEqual(expected, result);
public void TestLF()
    var input = "Hello\nWorld!";
    string result = MyHelpers.Nl2br(null, input).ToHtmlString();
    var expected = "Hello<br />World!";
    Assert.AreEqual(expected, result);
public void TestNonXhtmlOnOldMac()
    var input = "Hello\rWorld!";
    string result = MyHelpers.Nl2br(null, input, false).ToHtmlString();
    var expected = "Hello<br>World!";
    Assert.AreEqual(expected, result);
public void TestXSS()
    var input = "Hello\nWorld!\r\nSpecial Message: <script>alert('pwned!');</script>";
    string result = MyHelpers.Nl2br(null, input).ToHtmlString();
    var expected = "Hello<br />World!<br />Special Message: &lt;script&gt;alert(&#39;pwned!&#39;);&lt;/script&gt;";
    Assert.AreEqual(expected, result);

A few notes:

– You’ll note that we HtmlEncode the raw text first, then replace the line breaks with <br> tags. This is so that any potentially malicious user-supplied content gets escaped, but our HTML doesn’t.
– If the page you are working with is XHTML, the <br> tags should be self-closing. I’ve made this the default in this case, but you could pass in false to denote that they shouldn’t be self-closing.
– It is worth noting that you can’t pass dynamic parameters (such as ViewBag.Message) into an extension method, so you’ll have to explicitly cast them to a string.
– I’m quite new to C# and the .NET platform, so any comments or criticisms about this approach are certainly welcome.

Anyway, extension methods make it pretty easy to create your own HTML helpers – I’ve already ended up making handful of them to save time.

Software Patent Insanity – When will it end?

I’ve been sick today, and so I’ve been laying in bed watching TV and using my iPad for most of the day. As I sat there, I couldn’t help thinking “I’m so grateful for the brilliant insight and tireless effort of Dan Abelow, who has made it possible for me to take my railroad baron skills in Ticket to Ride to the European theater, by way of In App Purchase.”

Actually, though, I did read Fred Wilson’s blog post on how the current patent system, abused more and more by lowly patent trolls, is a threat to innovation.

This isn’t a new problem – I’ve had discussions about the problems with software (and business process) patents over a decade ago, and even then it probably wasn’t new. What is changing, however, is the willingness of patent trolls to go after smaller and smaller businesses, and the fact that technology is so much more a part of every day life for everyone today.

Before, patent suits were largely behind-the-scenes affairs between big companies that resulted in boring settlements or cross-licensing agreements. Or, as I’ve seen firsthand, the threat of patent lawsuits prevented small startups from receiving financing. Unfair and a huge impediment to innovation? Yes. Exciting and interesting to the average American citizen? Not really.

But as actions like the Lodsys suit against mobile apps that utilize in app purchasing become more common, the effects of a horribly-implemented patent system, abused by unscrupulous patent trolls like Lodsys, has the potential to affect the every-day lives of your average person – and perhaps shed some more light on the problem.

The scope of the Problem

The scope of the problem with software patents isn’t obvious at first, but it is an important part of realizing why they are such a threat to innovation and economic growth. Let’s go through a short little exercise –

Grab your smartphone or tablet if you have one. Scroll through the pages and pages of apps you’ve downloaded. Pop open your browser and look through the bookmarks and history items that contain all of your favorite websites. Look through the list of applications listed on your computer.

What do all of these have in common? The vast majority (if not all) of them violate one or more patents. Indeed, any marginally non-trivial app, service, or website probably violates dozens of patents.

Who are these people who have been providing you with applications or services chock-full of patent violations? Are they hardened criminals, numb to the harm they cause others? Or, are they shameless copycats who copy whatever they can find? Or, perhaps, they are hackers who’ve used their computer skills to steal secret designs from competitors?

None of the above. Most patents (especially the ones used by patent trolls) don’t exist as an implemented product, a documented library one can buy, or anything of that nature. They exist solely as one of millions of software patents filed with the PTO, written in legalese so heavy you or I would have a hard time knowing what they are describing.

Figuring out which patents your technology violates is so expensive and time consuming that it is effectively impossible for any small or medium business.

Think about that for a minute. Every small business that creates a technology product or service is sitting on dozens of bombs, any one of which can kill it. How is that fair? How is that good policy for promoting innovation and economic growth?

The worst kind of tax

When it comes to talking about economic growth (or lack thereof), it is hard to get very far without talking about the economic impact of taxes. Patents are a form of a tax, but they are the very worst kind of tax – a tax that is unpublished, seemingly random, and can wipe out your business.

The worst part is that for many of the small victims of these patent trolls, there is very little that can be done to fight this government-enforced monopoly – the very act of defending themselves will at worst case leave them bankrupt, and at best case cost countless hours and tens of thousands (at the very least) of dollars merely to continue to be able to exist.

It isn’t a bad business model – document some basic and broad idea, wait for others to come up with and implement the same idea, then sue them for a percentage of the profits.

Arguments for the patent system

There are lots of arguments for some form of a patent system. The main one is that if I think someone is going to steal my idea (which presumably took a lot of work to come up with), then I won’t bother coming up with new stuff because it will be hard for me to make money off of my work.

As a society that very highly values competition, we are willing to effectively kill competition by granting a monopoly on an idea in exchange for the value of someone coming up with it. This requires 2 things to be true – 1) Your ‘idea’ must be genuinely novel and take a lot of investment to come up with, and 2) The only way you were willing to invest in coming up with the idea was if you were granted a temporary monopoly on it.

A government-enforced monopoly is a pretty drastic – and potentially harmful – thing, so if we are going to buy into that concept we’d better be getting a lot out of it. As I’ll try to explain in the next few sections, I don’t think we are getting even close to enough out of the deal (at least with regards to software patents) to make it worth the cost.

Necessity, the mother of invention

Software development, as a profession, is largely about coming up with solutions to problems. For a given problem, there are generally only a handful of reasonable ways to solve it, and developers independently working on a similar problem will likely come up with generally similar solutions.

If you were to get 100 developers who were ignorant of the Lodsys patents (which, until Lodsys began firing off lawsuits, could have been pretty much any developer) and tell them you need to be able to sell expansions of your game to your users, and give them each an afternoon to come up with a rough solution, you’d likely get back ideas that could be grouped into half a dozen or so similar distinct ideas. Of those half-dozen distinct approaches, at least a few of them would probably violate the Lodsys patents.

The fact is that most of us solve similarly-difficult problems on a consistent basis – it is part of our job, and it is part of the reasons software developers are compensated somewhat more than average. The business side of the organization comes to us and says “We need to be able to do X.” So, we sit in front of a whiteboard for an hour or whatever, and then start implementing it.

Most of us don’t think “Hey, that’s a good idea! I should write my name on it and send it to the PTO so nobody else can do that without my blessing.” If we’re nice enough (and/or our egos are big enough), we’ll even write about it so others can use our idea.

Some people, however, feel like every idea they come up with is special and that nobody else should be able to do something like it unless they first pay for a license. Those people are assholes.

The cost of an idea

When I look at patents involved in some of these lawsuits, one thing almost always jumps out at me – once you get past all the lawyer-speak and understand what the patent is describing, it becomes clear that there wasn’t a lot of work involved in coming up with the idea. In fact, I wouldn’t be shocked to find that the effort to file the patent significantly outweighed the effort in coming up with the original idea.

If your patent is for a medication that your company spent years of effort and billions of dollars to research and produce, I can get behind patenting it. If your software patent describes something I wrote in High School using Perl, I’m going to have a hard time accepting your idea as a patentable one.

Counterpoint: Open Source Software

Open sourcing your software is pretty much the opposite of patenting it – rather than claim a monopoly on my idea, I’m going to go to great lengths to give it away to others so they can use it. It is a powerful counterpoint to the argument that patents foster innovation.

Go back to the original exercise I had you do earlier. Now consider this – all of those apps, services, and websites most likely rely heavily on open-source software (yes, even iOS uses plenty of open-source components). This simple blog relies heavily on open-source: The software used is WordPress – an open-source blogging platform, which is written in PHP – an open-source programming language. The content is stored in mySQL – an open-source database. All of it is running on Linux – an open-source operating system. To write this post, I’m using Chrome – an open-source web browser, which is running on Mac OS X – an operating system that relies heavily on open-source components.

Even you – one of my 3 or 4 readers – are almost certainly utilizing a wide array of open-source software to view this post.

The fact that open-source software plays such a pivotal role in everything we do is clear, convincing evidence to me that we can have invention and innovation on a breathtakingly large scale without the need to patent every idea we come up with.

The ‘small inventor’ myth

The final defense patent supporters like to throw out is a hypothetical one – patents are needed to help the small inventor who has his ideas ripped off by a big, evil corporation. I have to ask – how many times has a small inventor ‘invented’ some software and successfully used a patent to keep a big corporation from stealing it? We have a long history of patent trolls abusing software patents, but have we ever seen someone legitimately use one in this way? I haven’t.


So, to summarize – most software patents encapsulate something that an average developer could reasonably come up with on their own, are overly broad, and don’t typically represent a large amount of investment. The people at the PTO should hate themselves for approving them. Even worse – patents don’t even seem to be required to get people to innovate and invent new software. So why are we continuing to allow them?

A lot of people talk about half-measures that could be used to improve the patent system, while still allowing software patents – and a lot of the ideas are decent, but come with their own set of drawbacks.

The real thing that scares me, though, is the fact that much of the damage has already been done. Millions of incredibly simple, overly broad software patents already litter the landscape – much like how cluster bombs and land mines make an area unsafe even long after the conflict has been resolved. Even if we were to stop issuing software patents immediately, the ones already issued are broad enough to hinder innovation for the next decade.

How will we get out of this mess we’ve allowed to happen? I don’t know. But like Fred Wilson said, enough is enough. At some point, this madness has to end.