Software Development
Me riffing on software development.
In some recent talks I make a reference to Conway’s Law named after Melvin Conway (not to be confused with British Mathematician John Horton Conway famous for Conway’s Game of Life nor to be confused with Conway Twitty) which states: Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure. Many interpret this as a cynical jibe at software management dysfunction. But this was not Melvin’s intent. At least it wasn’t his only intent. On his website, he quotes from Wikipedia, emphasis...
In a recent post, Test Better, I suggested that developers can and ought do a better job of testing their own code. If you haven’t read it, I recommend you read that post first. I’m totally not biased in saying this at all. GO DO IT ALREADY! There was some interesting pushback in the comments. Some took it to mean that we should get rid of all the testers. Whoa whoa whoa there! Slow down folks. I can see how some might come to that conclusion. I did mention that my colleague Drew wants to destroy the role...
Developers take pride in speaking their mind and not shying away from touchy subjects. Yet there is one subject makes many developers uncomfortable. Testing. I’m not talking about drug testing, unit testing, or any form of automated testing. After all, while there are still some holdouts, at least these types of tests involve writing code. And we know how much developers love to write code (even though that’s not what we’re really paid to do). No, I’m talking about the kind of testing where you get your hands dirty actually trying the application. Where you attempt to...
The other day I needed a simple JSON parser for a thing I worked on. Sure, I’m familiar with JSON.NET, but I wanted something I could just compile into my project. The reason why is not important for this discussion (but it has to do with world domination, butterflies, and minotaurs). I found the SimpleJson package which is also on GitHub. SimpleJson takes advantage of a neat little feature of NuGet that allows you to include source code in a package and have that code transformed into the appropriate namespace for the package target. Oftentimes, this is used...
Today I learned something new and I love that! I was looking at some code that looked like this: try
{
await obj.GetSomeAsync();
Assert.True(false, "SomeException was not thrown");
}
catch (SomeException)
{
}
That’s odd. We’re using xUnit. Why not use the Assert.Throws method? So I tried with the following naïve code.
Assert.Throws<SomeException>(() => await obj.GetSomeAsync());
Well that didn’t work. I got the following helpful compiler error:
error CS4034: The 'await' operator can only be used within an async lambda expression....
I love automation. I’m pretty lazy by nature and the more I can offload to my little programmatic or robotic helpers the better. I’ll be sad the day they become self-aware and decide that it’s payback time and enslave us all. But until that day, I’ll take advantage of every bit of automation that I can. For example, I’m a big fan of the Code Analysis tool built into Visual Studio. It’s more more commonly known as FxCop, though judging by the language I hear from its users I’d guess it’s street name is “YOU BIG...
Tony Hoare, the computer scientist who implemented null references in ALGOL calls it his “billion-dollar mistake.” I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led...
I have a confession to make. I sometimes avoid your feedback on the Twitters. It’s nothing personal. I have a saved search for stuff I work on because I want to know what folks have to say. I want to know what problems they might run into or what ideas they have to improve things. Nonetheless, I sometimes just let the unread notifications sit there while I hesitate and cringe at the thought of the vitriol that might be contained within. I know. I know. That’s terrible. It’s long been conventional wisdom that if you’re going to write...
In my last post, I talked about the MonkeySpace conference conference and how it reflects positive trends in the future of open source in .NET. But getting to a better future is going to take some work on our part. And a key component of that is making NuGet better. Several discussions at MonkeySpace made it clear to me that there is some pervasive confusion and misconceptions about NuGet. It also made it clear that there are some dramatic changes needed for NuGet to continue to grow into a great open source project. In this post, I’ll cover some...
At the end of last year, I wrote a blurb about the Open Source Fest event at Mix 2011. Imagine the typical exhibition hall, but filled with around 50 open source projects. Each project had a station in a large room where project members presented what they were working on to others. You could see the gleam of inspiration in the smiles of developers as they exchanged ideas and suggestions. I left this event completely fired up. This is the spirit we tried to capture with the MonkeySpace conference this year. And at least for me, it succeeded. I’m...
With Reactive Extensions you sometimes need one observable sequence to run after another observable sequence completes. Perhaps the first one has side effects the second one depends on. Egads! I know, side effects are evil in this functional world, but it happens. Let’s make this more concrete with some contrived sample code. public static class BlogDemo
{
public static IObservable<int> Extract()
{
return new[] { 10, 20, 70, 100 }.ToObservable();
}
public static IObservable<string> GetStuffs()
{
return new[] { "Family...
When someone says they want to write a technical book, I take a hammer and slam it on the aspiring author’s thumb and ask “How do you like that?” If the answer is, “Very much! May I have another.” This person is ready to write a technical book. Sure, writing a book always starts off full of exciting possibilities. But it soon devolves into drudgery and pain with the constant question of whether the time spent is worth it when weighed against all your other obligations and opportunities in life. But no matter how much I sometimes hate...
I was once accused of primitive obsession. Especially when it comes to strings. Guilty as charged! There’s a lot of reasons to be obsessed with string primitives. Many times, the data really is a just a string and encapsulating it in some custom type is just software “designerbation.” Also, strings are special and the .NET Framework heavily optimizes strings through techniques like string interning and providing classes like the StringBuilder. But in many cases, a strongly typed class that better represents the domain is the right thing to do. I think System.Uri and its corresponding UriBuilder is a...
Next week my wife and I celebrate our tenth anniversary in Oahu with the kids. It’s been a great ten years and I’m just so lucky to have such a wonderful woman and partner in my life along with two deviously great kids. And what better way to celebrate an anniversary than to give a talk on Git and GitHub for Windows Developers!
UPDATE: Immediately after the talk we’re going to have a drinkup! Before I go further, I need you to soak in that logo for a minute. At first glance, it looks like it was...
If you look hard enough at our industry (really at all industries), you’ll find many implicit quotas in play. For example, some companies demand a minimum set of hours worked per week. This reminds me of an apocryphal story of the “know where man”. Here’s one variant of this famous legend as described on snopes: Nikola Tesla visited Henry Ford at his factory, which was having some kind of difficulty. Ford asked Tesla if he could help identify the problem area. Tesla walked up to a wall of boilerplate and made a small X in...
Back in March of this year I had the honor and delight to give the opening keynote at CodeMania, a new conference in New Zealand. This conference was something special. I mean, just look at their beautiful lucha libre inspired site design. Although inexplicably, they switched to a pirate theme when it came to my profile image. Even so, it’s fun and the Twitter integration is a nice touch. It’s time for me to tweet something very inappropriate. On a personal level, this was a particularly special conference for me as it was the...
In one mailing list I’m on, someone ran into a problem where they renamed a controller, but ASP.NET MVC could not for the life of it find it. They double checked everything. But ASP.NET MVC simply reported a 404. This is usually where I tell folks to run the following NuGet command: Install-Package RouteDebugger
RouteDebugger is a great way to find out why a route isn’t matching a controller.
In this particular case, the culprit was that the person renamed the controller and forgot to append the “Controller” suffix. So...
Sometimes, you need to scan all the types in an assembly for a certain reason. For example, ASP.NET MVC does this to look for potential controllers. One naïve implementation is to simply call Assembly.GetTypes() and hope for the best. But there’s a problem with this. As Suzanne Cook points out, If a type can't be loaded for some reason during a call to Module.GetTypes(), ReflectionTypeLoadException will be thrown. Assembly.GetTypes() also throws this because it calls Module.GetTypes(). In other words, if any type can’t be loaded, the entire method call blows up and...
As a kid, I was an impatient little brat. On any occasion that required waiting, I became Squirmy Wormy until I pushed my dad to make the demand parents so often make of fidgety kids, “Sit still!” Recent evidence suggests a rejoinder to kids today in response to this command, “What!? Are you trying to kill me?!” There is compelling evidence that modern workers propensity to sit for prolonged periods every day makes them fat and shortens their lives. Hmmm, you wouldn’t happen to know any professions where sitting limply at a desk for long periods of time...
Take a look at the following code.
const string input = "interesting";
bool comparison = input.ToUpper() == "INTERESTING";
Console.WriteLine("These things are equal: " + comparison);
Console.ReadLine();
Let’s imagine that input is actually user input or some value we get from an API. That’s going to print out These things are equal: True right? Right?!
Well not if you live in Turkey. Or more accurately, not if the current culture of your operating system is tr-TR (which is likely if you live in Turkey).
To prove...
A couple weeks ago I had the great pleasure to speak at the Norwegian Developer’s Conference (NDC). This is my second time speaking at NDC. The first time was back in 2009 and it was a blast! I gave two talks this year. My slides and a video of each presentation are available as well. Git and GitHub for Developers on Windows GitHub.com is the place for open source developers to collaborate on their projects. But there's a perception that GitHub and Git are the domain of Mac and *nix users. Not so! In...
For the past several months I’ve been working on a project with my amazing cohorts, Paul, Tim, and Adam, and Cameron at GitHub. I’ve had the joy of learning new technologies and digging deep into the inner workings of Git while lovingly crafting code. But today, is a good day. We’ve called the shipit squirrel into action once again! We all know that the stork delivers babies and the squirrel delivers software. In our case, we are shipping GitHub For Windows! Check out the official announcement on the GitHub Blog. GitHub for Windows is the easiest and best way...
Around eight years ago I wrote a blog post about Repetitive Strain Injury entitled The Real Pain of Software Development [part 1]. I soon learned the lesson that it’s a bad idea to have “Part 1” in any blog post unless you’ve already written part 2. But here I am, eight years later, finally getting around to part 2. But better late than never! The original reason that led me to write about this topic was a period of debilitating pain I went through when coding. Too many long hours at the keyboard took their toll on me...
For a long time, good folks like Matt Podwysocki have extolled the virtues of Reactive Extensions (aka Rx) to me. It piqued my interest enough for me to write a post about it, but that was the extent of it. It sounded interesting, but it didn’t have any relevance to any projects I had at the time. Fortunately, now that I work at GitHub I have the pleasure to work with an Rx Guru, Paul Betts, on a project that actively uses Rx. And man, is my mind blown by Rx. Hits Me Like A Hurricane What...
Changing a big organizations is a slow endeavor. But when people are passionate and persistent, change does happen. Three years ago, the ASP.NET MVC source code was released under an open source license. But at the time, the team could not accept any code contributions. In my blog post talking about that release, I said the following (emphasis added): Personally (and this is totally my own opinion), I’d like to reach the point where we could accept patches. There are many hurdles in the way, but if you went back in time several years and...
Disclaimer: these opinions are my own and don’t necessarily represent the opinion of any person or institution who are not me. The topic of sexism in the software industry has flared up recently. This post by Katie Cunningham (aka The Real Katie), entitled Lighten Up, caught my attention. As a father of a delightful little girl, I hope someday my daughter feels welcomed as a developer should she choose that profession. In general, I try to avoid discussions of politics, religion, and racism/sexism on my blog not because I don’t have strong feelings about these things, but I...
I recently gave my first talk on Git and GitHub to the Dot Net Startup Group about Git and GitHub. I was a little nervous about how I would present Git. At its core, Git is based on a simple structure, but that simplicity is easily lost when you start digging into the myriad of confusing command switches. I wanted a visual aid that showed off the structure of a git repository in real time while I issued commands against the repository. So I hacked one together in a couple afternoons. SeeGit is an open source instructive visual aid...
Conway’s Law states, ...organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations. Up until recently, there was probably no better demonstration of this law than the fact that Microsoft had two ways of shipping angle brackets (and curly braces for that matter) over HTTP – ASP.NET MVC and WCF Web API. The reorganization of these two teams under Scott Guthrie (aka “The GU” which I’m contractually bound to tack on) led to an intense effort to consolidate these technologies in a coherent...
In my previous post, I attempted to make a distinction between Open Source and Open Source Software. Some folks took issue with the post and that’s great! I love a healthy debate. It’s an opportunity to learn. One minor request though. If you disagree with me, I do humbly ask that you read the whole post first before you go and rip me a new one. It was interesting to me that critics fell into two opposing camps. There were those who felt that it was was disingenuous for me to use the term “open source software” to describe...
UPDATE: I have a follow-up post that addresses a few criticisms of this post.
It all started with an innocent tweet asking whether ASP.NET MVC 3 is “open source” or not? I jumped in with my usual answer, “of course it is!” The source code is released under the Ms-PL, a license recognized that the OSI legally reviewed to ensure it meets the Open Source Definition (OSD). The Free Software Foundation (FSF) recognizes it as a “free software license”1 making it not only OSS, but FOSS (Free and open source software) by that definition. Afterwards, a healthy debate ensued on...
Recently, the Log4Net team released log4net 1.2.11 (congrats by the way!). The previous version of log4Net was 1.2.10. Despite which version of version you subscribe to, we can all agree that only incrementing the third part of a version indicates that the new release is a minor update and one that hopefully has no breaking changes. Perhaps a bug fix release. This is especially true if you subscribe to Semantic Versioning (SemVer) as NuGet does. As I wrote previously, SemVer is a convention for versioning your public APIs that gives meaning to the version...
Back in November, someone asked a question on StackOverflow about converting arbitrary binary data (in the form of a byte array) to a string. I know this because I make it a habit to read randomly selected questions in StackOverflow written in November 2011. Questions about text encodings in particular really turn me on. In this case, the person posing the question was encrypting data into a byte array and converting that data into a string. The conversion code he used was similar to the following: string text = System.Text.Encoding.UTF8.GetString(data);
...
Suppose you have a test that needs to compare strings. Most test frameworks do a fine job with their default equality assertion. But once in a while, you get a case like this: [Fact]
public void SomeTest()
{
Assert.Equal("Hard \tto\ncompare\r\n", "Hard to\r\ncompare\n");
}
Let’s pretend the first value in the above test is the expected value and the second value is the value you obtained by calling some method.
Clearly, this test fails. So you look at the output and this is what you see:
It’s pretty hard to compare those...
In the past, I’ve tried various schemes to structure my unit tests but never fell into a consistent approach. Pretty much the only rule I had (which I broke all the time) was to write a test class for each class I tested. I would then fill that class with a ton of haphazard test methods. That was until I saw the approach that Drew Miller took with NuGet.org. The way he structured the unit tests struck me as odd at first, but quickly won me over. Drew tells me he can’t take all the credit for this approach....
T’is the season for “Year in Review” and “Best of” blog posts. It’s a vain practice, to be sure. This is exactly why I’ve done it almost every year! After all, isn’t all blogging pure vanity? Sadly, I did miss a few years when my vanity could not overcome my laziness. This year I am changing it up a bit to look at some of the highlights, in my opinion, that occurred in 2011 with open source software and the .NET community. I think it’s been a banner year for OSS and .NET/Microsoft, and I think it’s only going...
My last post covered how to improve your Git experience on Windows using PowerShell, Posh-Git, and PsGet. However, a commenter reminded me that a lot of folks don’t know how to get Git for Windows in the first place. And once you do get Git set up, how do you avoid getting prompted all the time for your credentials when you push changes back to your repository (or pull from a private repository)? I’ll answer both of those questions in this post. Install msysgit The first step is to install Git for Windows (aka msysgit). The...
I’m usually not one to resort to puns in my blog titles, but I couldn’t resist. Git it? Git it? Sorry. Ever since we introduced PowerShell into NuGet, I’ve become a big fan. I think it’s great, yet I’ve heard from so many other developers that they have no time to try it out. That it’s “on their list” and they really want to learn it, but they just don’t have the time. But here’s the dirty little secret about PowerShell. This might get me banned from the PowerShell junkie secret meet-ups (complete with secret handshake) for leaking...
Given how central JavaScript is to many modern web applications, it is important to use unit tests to drive the design and quality of that JavaScript. But I’ve noticed that there are a lot of developers that don’t know where to start. There are many test frameworks out there, but the one I love is QUnit, the jQuery unit test framework. Most of my experience with QUnit is writing tests for a client script library such as a jQuery plugin. Here’s an example of one QUnit test file I wrote a while ago (so you know...
So my last day at Microsoft ended up being a very long one as the NuGet team worked late into the evening to deployan updated version of NuGet.org. I’m very happy to be a part of this as my last act as a Microsoft employee. This is complete re-write of the gallery. Why a rewrite? We’ve learned a lot since we first launched, and our needs have evolved to the point where a rewrite made sense. The new implementation is a vanilla ASP.NET MVC 3 application and highly optimized to be a gallery with just the features we need....
Donut caching, the ability to cache an entire page except for a small region of the page (or set of regions) has been conspicuously absent from ASP.NET MVC since version 2. Mmmmm, donuts! – Photo by Pzado at sxc.hu This is something that’s on our Roadmap for ASP.NET MVC 4, but we have yet to flesh out the design. In the meanwhile, there’s a new NuGet package written by Paul Hiles that brings donut caching to ASP.NET MVC 3. I haven’t tried it myself yet, so be forewarned, but judging by the blog post,...
While attending Oredev 2011, I had an interesting conversation with Corey Haines about his perception of the Ruby community as compared to the .NET community. One thing he suggested is that the .NET community is seems a bit insular and self-isolating. He noted that when he attended .NET user groups, he only saw folks he knew to be .NET developers. But when he attends Ruby, Scala, NodeJS, Erlang, etc. user groups, he sees many of the same people at these meet ups. While I’m not completely against identifying oneself as a .NET developer to indicate your primary focus,...
Once in a while folks ask me for details about the hardware and software that hosts my blog. Rather than write about it, a photo can provide all the details that you need. There you have it. Well actuallyTM, my blog runs on a bit more hardware than that these days. Especially after the Great Hard-Drive Failure of 2009. As longtime readers of my blog might remember, nearly two years ago, this blog went down in flames due to a faulty hard-drive on the hosting server. My hosting provider, CrystalTech (now rebranded to be the...
If you’re not familiar with WCF Web API, it’s a framework with nice HTTP abstractions used to expose simple HTTP services over the web. Its focus is targeted at applications that provide HTTP services for various clients such as mobile devices, browsers, desktop applications. In some ways, it’s similar to ASP.NET MVC as it was developed with testability and extensibility in mind. There are some concepts that are similar to ASP.NET MVC, but with a twist. For example, where ASP.NET MVC has filters, WCF has operation handlers. One question that comes up often with Web API...
I like to live life on the wild side. No, I don’t base jump off of buildings or invest in speculative tranches made up of junk stock derivatives. What I do is attempt to run recurring background tasks within an ASP.NET application. Writing code is totally just like this - Photo by DVIDSHUB – CC BY 2.0 But before I do anything wild with ASP.NET, I always talk to my colleague, Levi (sadly, no blog). As a developer on the internals of ASP.NET, he knows a huge amount about it, especially the potential pitfalls. He’s also...
Today, October 15 2011, marks four years of being a Microsoft employee for me. As such, it’s time for a little introspection, but in many ways, Tim Heuer already introspected for me. Much of what he writes echoes my own experience, thus leaving me with less to write about. It’s the Microsoft way, or the highway. Which is conveniently located near Microsoft Way. - Photo by Todd Bishop, CC BY 2.0 Looking back in my archives, I realized I haven’t written a whole lot about what it’s like to work here. I do have a...
A long while ago I wrote about the potential dangers of Cross-site Request Forgery attacks, also known as CSRF or XSRF. These exploits are a form of confused deputy attack. Screen grab from The Police Academy movie.In that post, I covered how ASP.NET MVC includes a set of anti-forgery helpers to help mitigate such exploits. The helpers include an HTML helper meant to be called in the form that renders a hidden input, and an attribute applied to the controller action to protect. These helpers work great when in a typical HTML form post to an action method scenario....
Go that way instead - Photo by JacobEnos CC some rights reserved In an ASP.NET web application, it’s very common to write some jQuery code that makes an HTTP request to some URL (a lightweight service) in order to retrieve some data. That URL might be handled by an ASP.NET MVC controller action, a Web API operation, or even an ASP.NET Web Page or Web Form. If it can return curly brackets, it can be respond to a JavaScript request for JSON. One pain point when hosting lightweight HTTP services on ASP.NET is making a request...
UPDATE: We found an issue with 1.5 when running behind some proxies that caused an “Arithmetic operation resulted in an overflow” exception message and another issue with signed PS1 scripts. We’ve now posted an update (NuGet 1.5.20902.9023) that fixes the issues. I’m happy to announce the release of NuGet 1.5 just in time to make sure our roadmap isn’t a liar. I won’t bore you by repeating the details of the release, but instead direct you to the NuGet 1.5 release notes. If you are running a private NuGet.Server repository, you’ll need to update that repository the latest...
In a recent blog post, I wrote a a controller inspector to demonstrate Controller and Action Descriptors. In this blog post, I apply that knowledge to build something more useful. One pain point when you write Ajax heavy applications using ASP.NET MVC is managing the URLs that Routing generates on the server. These URLs aren’t accessible from code in a static JavaScript file. There are techniques to mitigate this: Generate the URLs in the view and pass them into the JavaScript API. This approach has the drawback that it isn’t unobtrusive and requires some...
EDITOR’S NOTE: Microsoft has an amazing intern program. For a summer, these bright college students work with a feature crew getting real work done, all the while attending cool events nearly every week that, frankly, make the rest of us jealous! Just look at some of the perks listed in this news article! This summer, the ASP.NET MVC is hosting an intern, Stephen Halter, who while very smart, doesn’t have a blog of his own (booo! hiss!). Being the nice guy that I am (and also being amenable to bribes), I’m letting him guest author a post on my...
This is an age old problem and one that’s probably been solved countless times before, but I’m going to write about it anyways. Say you’re writing code like this: <p>You have the following themes:</p>
<ul>
@foreach(var theme in Model) {
<li>@theme.Id</li>
}
</ul>
The natural inclination for the lazy developer is to leave enough alone and stop there. It’s good enough, right? Right?
Sure, when the value of Model.Count is zero or larger than one. But when it is exactly one, the phrase is incorrect English as it should be singular “You have...
I hate code samples in technical books! No seriously, this is bile I’m not afraid to give a permalink to (nor am I afraid to end a sentence with a preposition, so there!). Even the shortest code samples are a pain to type in. And if they show anything reasonably interesting, they’re probably too long to type in. Of course, nobody actually types in the sample code, they grab the code from the companion CD (blech!) or download zip files containing the code from the companion website. With Professional ASP.NET MVC 3 (print edition | kindle edition)...
As a web guy, I’ve slung more than my fair share of angle brackets over the tubes of the Internet. The Razor syntax quickly became my favorite way of generating those angle brackets soon after its release. But its usefulness is not limited to just the web. The ASP.NET team designed Razor to generate HTML markup without being tightly coupled to ASP.NET. This opens up the possibility to use Razor in many other contexts other than just a web application. For example, the help documentation for NuGet.exe is written using the Markdown format that is produced by NuGet.exe....
By default, ASP.NET MVC leverages Data Annotations to provide validation. The approach is easy to get started with and allows the validation applied on the server to “float” to the client without any extra work. However, once you get localization involved, using Data Annotations can really clutter your models. For example, the following is a simple model class with two properties. public class Character {
public string FirstName { get; set; }
public string LastName { get; set; }
}
Nothing to write home about, but it is...
ASP.NET MVC 3 introduced the ability to bind an incoming JSON request to an action method parameter, which is something I wrote about before. For example, suppose you have the following class defined (keeping it really simple here): public class ComicBook {
public string Title { get; set; }
public int IssueNumber { get; set; }
}
And you have an action method that accepts an instance of ComicBook:
[HttpPost]
public ActionResult Update(ComicBook comicBook) {
// Do something with ComicBook and return an...
At the risk of getting punched in the face by my friend Miguel, I’m not afraid to admit I’m a fan of responsible use of dependency injection. However, for many folks, attempting to use DI runs into a roadblock when it comes to ASP.NET HttpModule. In the past, I typically used “Poor man’s DI” for this. I wasn’t raised in an affluent family, so I guess I don’t have as much of a problem with this approach that others do. However, when the opportunity for something better comes along, I’ll take it Daddy Warbucks. I was refactoring some...
When you build an ASP.NET MVC 3 application and are ready to deploy it to your hosting provider, there are a set of assemblies you’ll need to include with your application for it to run properly, unless they are already installed in the Global Assembly Cache (GAC) on the server. In previous versions of ASP.NET MVC, this set of assemblies was rather small. In fact, it was only one assembly, System.Web.Mvc.dll, though in the case of ASP.NET MVC 1.0, if you didn’t have SP1 of .NET 3.5 installed, you would have also needed to deploy System.Web.Abstractions.dll and System.Web.Routing.dll. ...
Not too long ago, I posted a survey on my blog asking a set of questions meant to gather information that would help the NuGet team make a decision about a rather deep change. You can see the results of the survey here. If there’s one question that got to the heart of the matter, it’s this one. We’re considering a feature that would only allow a single package version per solution. As you can see by the response to the question, that would fit what most people need just fine, though there are a...
When installing a package into a project, NuGet creates a packages.config file within the project (if it doesn’t already exist) which is an exact record of the packages that are installed in the project. At the same time, a folder for the package is created within the solution level packages folder containing the package and its contents. Currently, it’s expected that the packages folder is committed to source control. The reason for this is that certain files from the package, such as assemblies, are referenced from their location in the packages folder. The benefit of this approach is that...
In continuing our efforts to release early, release often, I’m happy to announce the release of NuGet 1.3! Upgrade! If you go into Visual Studio and select Tools > Extension Manager, click on the Update tab and you’ll see that this new version of NuGet is available as an update. Click the Upgrade button and you’re all set. It only takes a minute and it really is that easy to upgrade. As always, there’s a new version of NuGet.exe corresponding with this release as well as a new version of the Package Explorer. If you have...
Say you want to apply an action filter to every action except one. How would you go about it? For example, suppose you want to apply an authorization filter to every action except the action that lets the user login. Seems like a pretty good idea, right? Currently, it takes a bit of work to do this. If you add a filter to the GlobalFilters.Filters collection, it applies to every action, which in the previous scenario would mean you already need to be authorized to login. Now that is security you can trust! You can also...
Eric S. Raymond in the famous essay, The Cathedral and the Bazaar, states, Release early. Release often. And listen to your customers. This advice came from Eric’s experience of managing an open source project as well as his observations of how the Linux kernel was developed. But why? Why release often? Do I really have to listen to my customers? They whine all the time! To question this advice is sacrilege to those who have this philosophy so deeply ingrained. It’s obvious! Or is it? When I was asked this in...
The Magic 8-ball toy is a toy usually good for maybe one or two laughs before it quickly gets boring. Even so, some have been known to make all their important life/strategic decisions using it, or an equivalent mechanism. The way the toy works is you ask it a question, shake it, and the answer to your question appears in a little viewport. What you’re seeing is one side of an icosahedron (20-sided polyhedron, or for you D&D folks, a d20). On each face of the d20 is a potential answer to your yes or no question. ...
One aspect of my job that I love is being able to go in front of other developers, my peers, and give presentations on the technologies that my team and I build. I’m very fortunate to be able to do so, especially given the intense stage fright I used to have. But over time, through giving multiple presentations, the stage fright has subsided to mere abject horror levels. Even so, I’m still nowhere near the numbers of much more polished and experienced speakers such as my cohort, Scott Hanselman. Always looking for the silver lining, I’ve...
Another Spring approaches and once again, another Mix is over. This year at Mix, my team announced the release of the ASP.NET MVC 3 Tools Update at Mix, which I blogged about recently. Working on this release as well as NuGet has kept me intensely busy since we released ASP.NET MVC 3 RTM only this past January. Hopefully now, my team and I can take a moment to breath as we start making big plans for ASP.NET MVC 4. It’s interesting to me to think that the version number for ASP.NET MVC is quickly catching up to the version...
I’m at Mix11 all week and this past Monday, I attended the Open Source Fest where multiple tables were set up for open source project owners to show off their projects. One of my favorite projects is also a NuGet package named Glimpse Web Debugger. It adds a FireBug like experience for grabbing server-side diagnostics from an ASP.NET MVC application while looking at it in your browser. It provides a browser plug-in like experience without the plug-in. One of the features of their plug-in is a route debugger inspired by my route debugger. Over time, as Glimpse catches...
Hi there, it’s time to shine the bat-signal, or better yet, the NuGet-Signal! The NuGet community needs your help! We’re wrestling with some interesting wide ranging design decisions and we need data to test out our assumptions and help us make the best possible choices. I won’t go into too much detail about the specific issue as I don’t want to bias the results of the following survey. I simply want to gather information about common practices by answering a set of questions that mostly have empirical answers. I think it’s a given that most Visual Studio solutions...
As you may know, NuGet supports aggregating packages from multiple package sources. You can simply point NuGet at a folder containing packages or at a NuGet OData service. A while back I wrote up a guide to hosting your own NuGet feed. Well, we’ve made it way easier to set one up now! And, surprise surprise, it involves NuGet. I’ll provide step by step instructions here. But first, make sure you’re running NuGet 1.2! Step 1: Create a new Empty Web Application in Visual Studio Go to the File | New | Project menu option (or...
I’m happy to announce the release of NuGet 1.2. It took us a bit longer than we expected to get this release out there, and I’ll explain why later, but for now, go install it! Upgrade! If you go into Visual Studio and select Tools | Extension Manager, click on the Update tab and you’ll see that this new version of NuGet should be available as an update. It only takes a minute and it really is that easy to upgrade. For more details about what’s in this release, check out the announcement on nuget.org. There’s also...
A colleague of mine from the Data and Modeling Group mentioned that they have a new senior developer position open working on their new datajs project. This developer would be responsible for defining how modern web and mobile applications use and interact with data on JavaScript platforms. We deal with and work on defining a number of standards including HTML5’s IndexedDB and OData, as well as provide a new set of end-to-end experiences for accessing, managing, and storing data in JS. What’s interesting to me is that datajs appears to be an open source project under the MIT...
I’m in the beautiful country of Brazil right now (I’ll hopefully blog more about that later) proctoring for the hands-on labs that’s part of the Web Camps agenda. However, the folks here are keeping me on my toes asking me to give impromptu and deeply advanced demos. It almost feels like a form of performance art as I create brand new demos on the fly. During this time, several people reported issues binding to a decimal value that prompted me to write a new demo and this blog post. Let’s look at the scenario. Suppose you...
David Fowler turned me on to a really cool feature of Razor I hadn’t realized made it into 1.0, Templated Razor Delegates. What’s that? I’ll let the code do the speaking. @{
Func<dynamic, object> b = @<strong>@item</strong>;
}
<span>This sentence is @b("In Bold").</span>
That could come in handy if you have friends who’ll jump on your case for using the bold tag instead of the strong tag because it’s “not semantic”. Yeah, I’m looking at you Damian . I mean, don’t both words signify being forceful? I digress.
Note that the delegate that’s...
Renaming a package ID is a potentially destructive action and one we don’t recommend doing. Why? Well if any other packages depend on your package, you’ve effectively broken them if you change your package ID. For example, today I wanted to rename a poorly named package, MicrosoftWebMvc, to Mvc2Futures. What I ended up doing is recreating the same package with the new ID and uploading it. That way existing packages that depend on MicrosoftWebMvc aren’t broken. But now, I have two packages that have the same functionality, but different IDs. Wouldn’t it be nice to eventually remove the...
Today I’m pleased to announce the release of NuGet 1.1 to the VS Extension Gallery and CodePlex. If you have NuGet 1.0 installed, just launch the VS Extension Manager (via Tools | Extension Manager menu) and click on the Updates tab. If you don’t see any updates, make sure to enable automatic detection of available updates. If you are running VS 2010 SP1 Beta, you might run into the following error message when attempting to upgrade to NuGet 1.1 if you have an older version installed. The workaround is to simply uninstall NuGet...
Over the past couple of years, I’ve written several blog posts on ASP.NET Routing where I provided various extensions to routing. Typically such blog posts included a zip download of the binaries and source code to allow readers to easily try out the code. But that’s always been a real pain and most people don’t bother. But now, there’s a better way to share such code. Moving forward, I’ll be using NuGet packages as a means of sharing my code samples. In the case of my routing extensions, I’ve compiled them into a solution I call RouteMagic (source...
The changing of the year is a time of celebration as people reflect thoughtfully on the past year and grow excited with anticipation for what’s to come in the year ahead. Today, there’s one less thing to anticipate as we announce the final release of ASP.NET MVC 3 and NuGet 1.0! Oh yeah, this never gets old. Install it via Web Platform Installer or download the installer directly to run it yourself. Here are a few helpful resources for learning more about this release: What’s New in...
In part 1 of this series, we looked at the scenario for grouping routes and how we can implement matching incoming requests with a grouped set of routes. In this blog post, I’ll flesh out the implementation of URL Generation. Url Generation Implementation URL generation for a group route is tricky, especially when using named routes because the individual routes that make up the group aren’t in the main route collection. As I noted before, the only route that’s actually added to the route table is the GroupRoute. Thus if you supply a route name for...
I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax. It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax. So I thought it might be handy to write up a a really concise quick reference about the Razor syntax. Syntax/Sample ...
A lot has been written about how to get ASP.NET MVC running on IIS 6 with extensionless URLs. Up until now, the story hasn’t been very pretty. When running ASP.NET MVC on ASP.NET 4, it gets a lot easier. To be fair, the part that makes it easier has nothing to do with ASP.NET MVC 3 and everything to do with a little known new feature of ASP.NET 4 creatively called the ASP.NET 4 Extensionless URL feature. ASP.NET MVC 3 requires ASP.NET 4 so it naturally benefits from this new feature. If you have a server running IIS...
We could have done better. That’s the thought that goes through my mind when looking back on this past year and reflecting on NuGet. Overall, I think we did pretty well with the product. Nobody died from using it, we received a lot of positive feedback, and users seem genuinely happy to use the product. So why start off with a negative review? It’s just my way. If you can’t look back on every project you do and say to yourself “I could have done better”, then you weren’t paying attention and you weren’t learning. For example, why...
Almost exactly one month ago, we released the Release Candidate for ASP.NET MVC 3. And today we learn why we use the term “Candidate”. As Scott writes, Visual Studio 2010 SP1 Beta was released just this week and as we were testing it we found a few incompatibilities with it and the ASP.NET MVC 3 RC that we had just released. That’s when we, in the parlance of the military, scrambled the jets to get another release candidate prepared. You can install it directly using the Web Platform Installer (Web PI) download the installer yourself from from...
I don’t normally post lists of links as it’s really not my style. But there’s a lot of great NuGet blog posts I want to call out so I thought I’d try my hand at it. Hey! Here’s a random picture of a goat. I also tend to post links from my twitter account http://twitter.com/haacked. Using NuGet to spice up your development project – Willem Meints writes a nice intro to NuGet and shows how to package up a library. Using the Library Package Manager with Add-on...
Sometimes, despite your best efforts, you encounter a problem with your ASP.NET MVC application that seems impossible to figure out and makes you want to pull out your hair. Or worse, it makes you want to pull out my hair. In some of those situations, it ends up being a PEBKAC issue, but in the interest of avoiding physical harm, I try not to point that out. Thankfully, in the interest of saving my hair, Brad Wilson (recently featured on This Developer’s Life!) wrote a simple diagnostics web page for ASP.NET MVC that you can drop into...
UPDATE: 2011/02/13: This code is now included in the RouteMagic NuGet package! To use this code, simply run Install-Package RouteMagic within the NuGet Package Manager Console.
One thing ASP.NET Routing doesn’t support is washing and detailing my car. I really pushed for that feature, but my coworkers felt it was out of scope. Kill joys. Another thing Routing doesn’t support out of the box is a way to group a set of routes within another route. For example, suppose I want a set of routes to all live under the same URL path. Today, I’d need to make sure all...
A question I often receive via my blog and email goes like this: Hi, I just got an email from a Nigerian prince asking me to hold some money in a bank account for him after which I’ll get a cut. Is this a scam? The answer is yes. But that’s not the question I wanted to write about. Rather, a question that I often see on StackOverflow and our ASP.NET MVC forums is more interesting to me and it goes something like this: How do I get the route...
A while back I wrote about mocking successive calls to the same method which returns a sequence of objects. Read that post for more context. In that post, I had written up an implementation, but quickly was won over by a better extension method implementation from Fredrik Kalseth. public static class MoqExtensions
{
public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup,
params TResult[] results) where T : class {
setup.Returns(new Queue<TResult>(results).Dequeue);
}
}
As good as this extension method is, I...
The beginning of wisdom is to call things by their right names – Chinese Proverb Routing in ASP.NET doesn’t require that you name your routes, and in many cases it works out great. When you want to generate an URL, you grab this bag of values you have lying around, hand it to the routing engine, and let it sort it all out. For example, suppose an application has the following two routes defined routes.MapRoute(
name: "Test",
...
Note, this blog post applies to v1.0 of NuGet and the details are subject to change in a future version. In general, when you create a NuGet package, the files that you include in the package are not modified in any way but simply placed in the appropriate location within your solution. However, there are cases where you may want a file to be modified or transformed in some way during installation. NuGet supports two types of transformations during installation of a package: Config transformations Source transformations ...
Today we’re releasing the release candidate for ASP.NET MVC 3. We’re in the home stretch now so it’ll mostly be bug fixes and small tweaks from here on out. There are two ways to install ASP.NET MVC 3: Via the Web Platform Installer (Web PI) Or by downloading the installer directly Also, be sure to check out the ASP.NET MVC 3 web page for information and content about ASP.NET MVC 3 as well as the release notes for this release. Also, don’t miss Scott Guthrie’s blog post...
My team has been hard at work the past few weeks cranking out code and today we are releasing the second preview of NuGet (which you may have heard referred to as NuPack in the past, but was renamed for CTP 2 by the community). If you’re not familiar with what NuGet is, please read my introductory blog post on the topic. For a detailed list of what changed, check out the NuGet Release Notes. To see NuGet in action, watch the talk that Scott Hanselman’s gave at the Professional Developer’s Conference which was the highest rated talk....
It was a dark and stormy coding session; the rain fell in torrents as my eyes were locked to two LCD screens in a furious display of coding … …sorry sorry, I just can’t continue. It’s all a lie. This actually a cautionary tale describing one subtle way that you can run afoul Code Access Security (CAS) when attempting to run an application in partial trust. But who wants to read about that? Right? Right? Well this isn’t a sordid tale, but if you bear with me, you may just find it interesting. Either...
The polls have closed and we now have a new name for our project, NuGet (pronounced “New Get” and not “Nugget” and not “Noojay” for you hoity-toity) which had the most votes by a large margin. For those who missed it, the following posts will get you up to speed on the name change: A few days ago I wrote about our need to rename NuPack I followed up with more details about the rename And then I wrote about how the community offered its own choices...
Just a quick follow-up to my last posts about naming NuPack. Looks like the community is not content to sit back and let the project be labelled with a lame name. I’ve seen a couple of community inspired names created as new issues in the CodePlex issue tracker. However, NFetch has a huge lead, but the community chosen NRocks is a close second. The name I like the best so far is NuGet. (vote for it here) As before, voting still closes on Tuesday 10/26 at 11:59 PM PDT. If you feel strongly enough around a name,...
UPDATE: The new name is NuGet
The NuPack project is undergoing a rename and we need your help! For details, read the announcement about the rename on the Outercurve Foundation’s blog. What is the new name? We don’t know. You tell us! The NuPack project team brainstormed a set of names and narrowed down the list to four names. I’ve posted a set of names as issues in our NuPack CodePlex.com site and will ask you to vote for your favorite name among the lot. Vote for as many as you want, but realize that if you vote...
Note: Everything I write here is based on a very early pre-release version of NuGet (formerly known as NuPack) and is subject to change. A few weeks ago I wrote a blog post introducing the first preview, CTP 1, of NuGet Package Manager. It’s an open source (we welcome contributions!) developer focused package manager meant to make it easy to discover and make use of third party dependencies as well as keep them up to date. As of CTP 2 NuGet by default points to an ODATA service temporarily located at http://go.microsoft.com/fwlink/?LinkID=204820 (in CTP 1 this was an...
A couple days ago I wrote a blog post entitled, Running Open Source In A Distributed World which outlined some thoughts I had about how managing core contributors to an open source project changes when you move from a centralized version control repository to distributed version control. The post was really a way for me to probe for ideas on how best to handle feature contributions. In the post, I asked this question, Many projects make a distinction between who may contribute a bug fix as opposed to who may contribute a feature. Such projects...
When it comes to running an open source project, the book Producing Open Source Software - How to Run a Successful Free Software Project by Karl Fogel (free pdf available) is my bible (see my review and summary of the book). The book is based on Karl Fogel’s experiences as the leader of the Subversion project and has heavily influenced how I run the projects I’m involved in. Lately though, I’ve noticed one problem with some of his advice. It’s so Subversion-y. Take a look at this snippet on Committers. As the only formally...
UPDATE: This post is a out of date. We recently released the Release Candidate for ASP.NET MVC 3.
Wow! It’s been a busy two months and change since we released Preview 1 of ASP.NET MVC 3. Today I’m happy (and frankly, relieved) to announce the Beta release of ASP.NET MVC 3. Be sure to read Scott Guthrie’s announcement as well. Credits: Image from ICanHazCheezburger http://icanhascheezburger.com/tag/onward/ Yes, you heard me right, we’re jumping straight to Beta with this release! To try it out… Install it immediately via the Web Platform Installer (Web PI). ...
NuGet (recently renamed from NuPack) is a free open source developer focused package manager intent on simplifying the process of incorporating third party libraries into a .NET application during development. After several months of work, the Outercurve Foundation (formerly CodePlex Foundation) today announced the acceptance of the NuGet project to the ASP.NET Open Source Gallery. This is another contribution to the foundation by the Web Platform and Tools (WPT) team at Microsoft. Also be sure to read Scott Guthrie’s announcement post and Scott Hanselman’s NuGet walkthrough. There’s also a video interview with me on Web Camps TV...
By now, you’re probably aware of a serious ASP.NET Vulnerability going around. The ASP.NET team has been working around the clock to address this. Quite literally as last weekend, I came in twice over the weekend (to work on something unrelated) to find people working to address the exploit. Recently, Scott Guthrie posted a follow-up blog post with an additional recommended mitigation you should apply to your servers. I’ve seen a lot of questions about these mitigations, as well as a lot of bad advice. The best advice I’ve seen is this - if you’re running an ASP.NET application,...
I was drawn to an interesting question on StackOverflow recently about how to override a request for a non-existent .svc request using routing. One useful feature of routing in ASP.NET is that requests for files that exist on disk are ignored by routing. Thus requests for static files and for .aspx and .svc files don’t run through the routing system. In this particular scenario, the developer wanted to replace an existing .svc service with a call to an ASP.NET MVC controller. So he deletes the .svc file and adds the following route: ...
On Twitter yesterday I made the following comment: We're not here to write software, we're here to ship products and deliver value. Writing code is just a fulfilling means to that end :) All I see now is blonde, brunette, redhead. For the most part, I received a lot of tweets in agreement, but there were a few who disagreed with me: While I agree in principle, the stated sentiment "justifies" the pervasive lack of quality in development Doctors with this mentality...
In my last blog post, I covered some challenges with versioning methods that differ only by optional parameters. If you haven’t read it, go read it. If I do say so myself, it’s kind of interesting. ;) In this post, I want to cover another very subtle versioning issue with using optional parameters. At the very end of that last post, I made the following comment. By the way, you can add overloads that have additional required parameters. So in this way, you are in the same boat as before. However, this can...
One nice new feature introduced in C# 4 is support for named and optional arguments. While these two features are often discussed together, they really are orthogonal concepts. Let’s look at a quick example of these two concepts at work. Suppose we have a class with one method having the following signature. // v1
public static void Redirect(string url, string protocol = "http");
This hypothetical library contains a single method that takes in two parameters, a required string url and an optional string protocol.
The following shows...
I’ve been working on a lovely little prototype recently but ran into a problem where my code receives a collection of attributes and needs to change them in some way and then pass the changed collection along to another method that consumes the collection. I want to avoid changing the attributes directly, because when you use reflection to retrieve attributes, those attributes may be cached by the framework. So changing an attribute is not a safe operation as you may be changing the attribute for everyone else who tries to retrieve them. What I really wanted...
In ASP.NET MVC 3 Preview 1, we introduced some syntactic sugar for creating and accessing view data using new dynamic properties. Sugar, it’s not just for breakfast. Within a controller action, the ViewModel property of Controller allows setting and accessing view data via property accessors that are resolved dynamically at runtime. From within a view, the View property provides the same thing (see the addendum at the bottom of this post for why these property names do not match). Disclaimer This blog post talks about ASP.NET MVC 3 Preview 1,...
UPDATE: This post is a out of date. We recently released the Release Candidate for ASP.NET MVC 3.
Feels like just yesterday that we released ASP.NET MVC 2 to the world and here I am already talking about an early preview. In a way, we’re right on schedule. It was almost exactly a year ago that we released Preview 1 of ASP.NET MVC 2. Today I’m happy to announce that ASP.NET MVC 3 Preview 1 is available for download. Give it a try out and let us know what you think. Some key notes before you give it a whirl:...
I wanted to confirm something about how to upload a file or set of files with ASP.NET MVC and the first search result for the phrase “uploading a file with asp.net mvc” is Scott Hanselman’s blog post on the topic. His blog post is very thorough and helps provide a great understanding of what’s happening under the hood. The only complaint I have is that the code could be much simpler since we’ve made improvements to the ASP.NET MVC 2. I write this blog post in the quixotic hopes of knocking his post from the #1 spot. Uploading...
In my last blog post, I wrote about the proper way to check for empty enumerations and proposed an IsNullOrEmpty method for collections which sparked a lot of discussion. This post covers a similar issue, but from a different angle. A very long time ago, I wrote about my love for the null coalescing operator. However, over time, I’ve found it to be not quite as useful as it could be when dealing with strings. For example, here’s the code I might want to write: public static void DoSomething(string argument)...
While spelunking in some code recently I saw a method that looked something like this: public void Foo<T>(IEnumerable<T> items) {
if(items == null || items.Count() == 0) {
// Warn about emptiness
}
}
This method accepts a generic enumeration and then proceeds to check if the enumeration is null or empty. Do you see the potential problem with this code? I’ll give you a hint, it’s this line:
items.Count() == 0
What’s the problem? Well that line right there has the potential to be vastly inefficient.
If the...
A while ago I was talking with my manager at the time about traits that we value in a Program Manager. He related an anecdote about an interview he gave where it became clear that the candidate did not deal well with ambiguity. This is an important trait for nearly every job, but especially for PMs as projects can often change on a dime and it’s important understand how to make progress amidst ambiguity and eventually drive towards resolving ambiguity. Lately, I’ve been asking myself the question, doesn’t this apply just as much to software? One of...
ASP.NET 4 introduces a few new extensibility APIs that live the hermit lifestyle away from the public eye. They’re not exactly hidden - they are well documented on MSDN - but they aren’t well publicized. It’s about time we shine a spotlight on them. PreApplicationStartMethodAttribute This new attribute allows you to have code run way early in the ASP.NET pipeline as an application starts up. I mean way early, even before Application_Start. This happens to also be before code in your App_code folder (assuming you have any code in there) has been compiled. To use...
One of my favorite features of ASP.NET MVC 2 is the support for client validation. I’ve covered a bit about validation in the following two posts: ASP.NET MVC 2 Custom Validation covers writing a custom client validator. Localizing ASP.NET MVC Validation covers localizing error messages. However, one topic I haven’t covered is how validation works with globalization. A common example of this is when validating a number, the client validation should understand that users in the US enter periods as a decimal point, while users in Spain will use...
The ASP.NET MVC2 templates feature is a pretty nice way to quickly scaffold objects at runtime. Be sure to read Brad Wilson’s fantastic series on this topic starting at ASP.NET MVC 2 Templates, Part 1: Introduction. As great as this feature is, there is one template that’s conspicuously missing. ASP.NET MVC does not include a template for displaying a list of objects in a tabular format. Earlier today, ScottGu forwarded an email from Daniel Manes (what?! no blog! ;) with a question on how to accomplish this. Daniel had much of it implemented, but was trying to get over...
One annoyance that some developers have run into with ASP.NET MVC is that certain reserved filenames are not allowed in URLs. Often, this is manifested as a Bad Request error or a File Not Found (404) error.
The specifics of this restriction are accounted for in an interesting blog post entitled Zombie Operating Systems and ASP.NET MVC. This actually wasn’t a restriction on ASP.NET MVC but was built into the core of ASP.NET itself. Fortunately, ASP.NET 4 fixes this issue with a new setting. In web.config, simply add <httpRuntime relaxedUrlToFileSystemMapping="true"/> to the system.web node. Here’s a snippet from my...
Like the well disciplined secure developer that you are, when you built your ASP.NET MVC 1.0 application, you remembered to call Html.Encode every time you output a value that came from user input. Didn’t you? Well, in ASP.NET MVC 2 running on ASP.NET 4, those calls can be replaced with the new HTML encoding syntax (aka code nugget). I’ve written a three part series on the topic. Html Encoding Code Blocks With ASP.NET 4 Html Encoding Nuggets With ASP.NET MVC 2 Using AntiXss as the default encoder...
UPDATE: The JsonValueProviderFactory is now registered by default in ASP.NET MVC 3. So if you’re using ASP.NET MVC 3, you can ignore that part of this blog post.
Javier “G Money” Lozano, one of the good folks involved with C4MVC, recently wrote a blog post on posting JSON (JavaScript Object Notation) encoded data to an MVC controller action. In his post, he describes an interesting approach of using a custom model binder to bind sent JSON data to an argument of an action method. Unfortunately, his sample left out the custom model binder and only demonstrates how to retrieve JSON data...
This is the third in a three part series related to HTML encoding blocks, aka the <%: ... %> syntax.
Html Encoding Code Blocks With ASP.NET 4
Html Encoding Nuggets With ASP.NET MVC 2
Using AntiXss as the default encoder for ASP.NET
Scott Guthrie recently wrote about the new <%: %> syntax for HTML encoding output in ASP.NET 4. I also covered the topic of HTML encoding code nuggets in the past as well providing some insight into our design choices for the approach we took. A commenter to Scott’s blog post asked, ...
The “copyleft” provisions of the GPL (GNU General Public License) require that any changes or additions to a GPL licensed work must itself be licensed under terms that adhere to the GPL. Critics of these “copyleft” provisions have derogatively labeled the GPL as a “viral” license. Such criticism points out that any code that seeks to incorporate GPL licensed code must itself adhere to the terms of the GPL, thus potentially “infecting” other code with its restrictions. This has caused many developers of proprietary systems to be concerned about any usage of GPL code within their products for...
UPDATE: After an email exchange with Eric Meijer, I learned that I was a bit imprecise in this treatment. Or, as the colloquial term goes, “wrong”. :) I’ve changed the title to reflect more accurately what Reactive extensions provide. Iterating over a collection of items seems like a pretty straightforward mundane concept. I don’t know about you, but I don’t spend the typical day thinking about the mechanics of iteration, much like I don’t spend a lot of time thinking about how a roll of toilet paper is made. At least I didn’t until watching Elmo Potty Time with...
Last week I spent a few days in Las Vegas attending the Mix 10 conference. Mix is billed as … A 3 day conference for web designers and developers building the world's most innovative web sites. Which certainly reflects its origins as a conference focused on the web and web standards. But this year, it seemed that the scope for Mix was expanded to be about, well, a Mix of technologies as the Windows Phone 7 series figured prominently at the conference. Scott Hanselman and I are seen here attempting to tutor...
Hot on the heels of the release of ASP.NET MVC 2 yesterday, I’m happy to announce that we are releasing the source code to ASP.NET MVC 2 under the Ms-PL license, an OSI approved Open Source license. This continues the trend from nearly a year ago when we released ASP.NET MVC 1.0 under the Ms-PL. You can read my blog post there to learn more about the hard work that goes into such releases. While I’m one who loves lawyer jokes, I do appreciate the work that they do (one of my best friends is a lawyer) and...
It’s that time of year again when the sakura (cherry blossoms) bloom and allergies kick into high gear. When the drive home is no longer shrouded in darkness and when the ASP.NET team releases Software! Earlier today we released the RTM of ASP.NET MVC 2 for Visual Studio 2008 SP1. See Scott Guthrie’s announcement about it. For download and install options, visit the ASP.NET MVC Download Page. Here are a few helpful resources to help you learn more about this release. What’s New in ASP.NET MVC 2 Upgrading an ASP.NET...
If there’s one impression that Austin left on me, besides the one that Rudy’s “extra moist” barbecue left on my gut, is that it’s a developer friendly town. This past week I spent three days in Austin meeting with all sorts of developers and had many great conversations about technology. I met with companies and people with a passion for technology that couldn’t be suppressed. Meeting with Dell The reason I was in town was to give a couple of presentations at a mini-conference for Dell employees. On my first day in Austin, the day...
During the MVP summit, an attendee asked me for some help with a common scenario common among those building content management systems. He wanted his site to use human friendly URLs. http://example.com/pages/a-page-about-nothing/ instead of http://example.com/pages/123/ Notice how the first URL is descriptive whereas the second is not. The first URL contains a URL “slug” while the second one contains the ID for the content, typically associated with the ID in the database. This is easy enough to set up with routing, but there’s a slight twist. He still wanted the action method which...
If you have a model object with a property named Id, you may have run into an issue where your model state is invalid when binding to that model even though you don’t have an “Id” field in your form. The following scenario should clear up what I mean. Suppose you have the following simple model with two properties. public class Product {
public int Id { get; set; }
public string Name { get; set; }
}
And you are creating a view...
UPDATE: We moved the date to February 24th. The stars at night, are big and bright – clap clap clap clap – deep in the heart of Texas! Hold onto your ten gallon hats, I’m visiting Texas for the first time! I’m very excited to visit the second largest state in the union. ;) The purpose of my trip is to meet with some developers at Dell doing interesting things and to give a talk there as well. But since I’ve heard such good things about the vibrant tech community in Austin, I am...
UPDATE: This blog post is out-of date. We released the RTM of ASP.NET MVC 2 in March 2010. Read about it here.
Today I’m pleased to announce the availability of Release Candidate 2 for ASP.NET MVC 2. After receiving feedback from our last release candidate back in December, we decided it would be prudent to have one more release candidate that incorporated the feedback. You can read the release notes for everything that changed, there’s not a whole lot. The biggest change in this release was described by Brad Wilson in his blog post on Input Validation vs. Model...
One question that came up recently during my mid-year review is how am I measuring customer satisfaction with the products that I work on? For example, how can I measurably demonstrate that customers are happy with the work we are doing on ASP.NET MVC and that my team is responding to customer feedback? Umm, I can’t? At least not right now in a measurable manner. I don’t have any such metric and I’m not sure how reliable any metric I might come up with will be. But perhaps that’s simply due to a lack of imagination on...
It’s that time of year again when a young man’s thoughts turn to Las Vegas! Yep, it’s another year and another Mix conference (March 15-17, 2010), but this time they’ve changed locations to Mandalay Bay. It looks like my prediction that the Mix conferences would end at Mix 09 did not pan out. ;) As I did last year, I’ll be giving two talks at Mix 10 this year, one of them with the irrepressible Scott Hanselman. What’s new in ASP.NET MVC 2 Come see and hear about the...
UPDATE: THIS POST IS DEPRECATED!!! I’ve updated the original post for editable routes to work in medium trust and not require a full app domain reload like this approach does. I think that approach may supersede this approach until I learn otherwise. :) Yesterday I wrote about a technique using dynamic compilation to allow editing routes after you’ve deployed an application without having to manually recompile your application. I made use of a FileSystemWatcher to monitor a Config directory and dynamically recompiled code when the code file changed. This has one advantage over using the App_Code directory in...
UPDATE: 2011/02/13: This code is now included in the RouteMagic NuGet package! To use this code, simply run Install-Package RouteMagic within the NuGet Package Manager Console. In general, once you deploy your ASP.NET MVC application, you can’t change the routes for your application without recompiling the application and redeploying the assembly where your routes are defined. This is partly by design as routes are generally considered application code, and should have associated unit tests to verify that the routes are correct. A misconfigured route could seriously tank your application. Having said that, there are many situations in...
This blog is experiencing technical difficulties. Do not adjust your browser. Hi there. If you’ve tried to visit this blog recently you might have noticed it’s been down a lot in the last two days. My apologies for that, but hopefully you found what you needed via various online web caches. I’ve been dogfooding the latest version of Subtext and as CodingHorror points out, dogfood tastes bad. I’ve done a lot of testing on my local box, but there are a class of bugs that I’m only going to find on a high traffic real site, and...
Confirmation dialogs were designed by masochists intent on making users of the web miserable. At least that’s how I feel when I run into too many of them. And yes, if you take a look at Subtext, you can see I’m a perpetrator. Well no longer! I was managing my Netflix queue recently when I accidentally added a movie I did not intend to add (click on the image for a larger view). Naturally, I clicked on the blue “x” to remove it from the queue and saw this. Notice that there’s no confirmation...
UPDATE: 12/30 I had transposed the rgb colors. I corrected the function. I’ve been distracted by a new jQuery plugin that I’m writing. The plugin has certain situations where it sets various background and foreground colors. You can have it set those styles explicitly or you can have it set a CSS class, and let the CSS stylesheet do the work. I’m writing some unit tests to test the former behavior and ran into an annoying quirk. When testing the color value in IE, I’ll get something like #e0e0e0, but when testing it in FireFox, I get rgb(224, 224,...
UPDATE (12/26): I updated this post to use the href instead of the rel attribute It’s Christmas day, and yes, I’m partaking in the usual holiday fun such as watching Basketball, hanging out with the family and eating our traditional Alaskan king crab Christmas dinner. But of course it wouldn’t be a complete day without writing a tiny bit of code! Today I’ve been working on improving the UI here and there in Subtext. One common task I run into over and over is using an anchor tag to trigger the hiding of another element...
When we released ASP.NET MVC 2 Beta back in November, I addressed the issue of support for Visual Studio 2010 Beta 2. Unfortunately, because Visual Studio 2010 Beta 2 and ASP.NET MVC 2 Beta share components which are currently not in sync, running ASP.NET MVC 2 Beta on VS10 Beta 2 is not supported. The release candidate for ASP.NET MVC 2 does not change the situation, but I wasn’t as clear as I could have been about what the situation is exactly. In this post, I hope to clear up the confusion (and hopefully...
Many web applications (such as this blog) allow users to enter HTML as a comment. For security reasons, the set of allowed tags is tightly constrained by logic running on the server. Because of this, it’s helpful to provide a preview of what the comment will look like as the user is typing the comment. That’s exactly what my live preview jQuery plugin does. See it in action This is the first jQuery Plugin I’ve written, so I welcome feedback. I was in the process of converting a bunch of JavaScript code in Subtext to make...
Ok, it wasn’t necessarily my ass that was saved, but it was years worth of images which were important to me! As I wrote yesterday, my blog’s hosting server had a hard-drive failure effectively wiping out my virtual machine, taking my blog down with it. Fortunately, I was able to get back up with a static archive of my site provided by Rich Skrenta, but I was missing all my images and other content (code samples). As Jeff mentions, I have learned the hard way that there are almost no organizations spidering and storing...
Good news! I have contributed my T4 template to the .less project. You can access it from the big download button on their homepage.
Pain is often a great motivator for invention, unless you become dull to the pain. I think CSS is one of those cases where there’s a lot of pain that we as web developers often take in stride. Fortunately not everyone accepts that pain and efforts such as LESS are born. As the home page states: LESS extends CSS with: variables, mixins, operations and nested rules. Best of all,...
This code has been incorporated into a new RouteMagic library I wrote which includes Source Code on CodePlex.com as well as a NuGet package!
I saw a bug on Connect today in which someone offers the suggestion that the PageRouteHandler (new in ASP.NET 4) should handle IHttpHandler as well as Page. I don’t really agree with the suggestion because while a Page is an IHttpHandler, an IHttpHandler is not a Page. What I this person really wants is a new handler specifically for http handlers. Let’s give it the tongue twisting name: IHttpHandlerRouteHandler. Unfortunately, it’s too late to add...
This is the second in a three part series related to HTML encoding blocks, aka the <%: ... %> syntax.
Html Encoding Code Blocks With ASP.NET 4
Html Encoding Nuggets With ASP.NET MVC 2
Using AntiXss as the default encoder for ASP.NET
In a recent blog post, I introduced ASP.NET 4’s new HTML Encoding code block syntax as well as the corresponding IHtmlString interface and HtmlString class. I also mentioned that ASP.NET MVC 2 would support this new syntax when running on ASP.NET 4. In fact, you can try it out now by downloading and installing Visual...
This is the first in a three part series related to HTML encoding blocks, aka the <%: ... %> syntax.
Html Encoding Code Blocks With ASP.NET 4
Html Encoding Nuggets With ASP.NET MVC 2
Using AntiXss as the default encoder for ASP.NET
One great new feature being introduced in ASP.NET 4 is a new code block (often called a Code Nugget by members of the Visual Web Developer team) syntax which provides a convenient means to HTML encode output in an ASPX page or view. <%: CodeExpression %>
...
UPDATE: Looks like the CLR already has something similar to what I did here. Meet the latest class with a superhero sounding name, ExpandoObject
Warning: What I’m about to show you is quite possibly an abuse of the C# language. Then again, maybe it’s not. ;) You’ve been warned. Ruby has a neat feature that allows you to hook into method calls for which the method is not defined. In such cases, Ruby will call a method on your class named method_missing. I showed an example of this using IronRuby a while back when I wrote about monkey patching CLR...
UPDATEThis post is now obsolete. Single project areas are a core part of ASP.NET MVC 2. Preview 1 of ASP.NET MVC 2 introduces the concept of Areas. Areas provide a means of dividing a large web application into multiple projects, each of which can be developed in relative isolation. The goal of this feature is to help manage complexity when developing a large site by factoring the site into multiple projects, which get combined back into the main site before deployment. Despite the multiple projects, it’s all logically one web application. One piece of feedback I’ve already heard...
UPDATE: This post is outdated. ASP.NET MVC 2 RTM was released in March.
Four and a half months after my team released ASP.NET MVC 1.0, I am very happy to announce that the release of our first Preview of version 2 of ASP.NET MVC is now available for download. Go download it immediately and enjoy its coolness. :) Don’t be afraid to install it as it will sit nicely side-by-side with ASP.NET 1.0.
The release notes provide more details on what’s in this release and I’ve also updated the Roadmap on CodePlex, which describes the work we want to do in Preview...
Every now and then some email or website comes along promising to prove Fred Brooks wrong about this crazy idea he wrote in The Mythical Man Month (highly recommended reading!) that there is no silver bullet which by itself will provide a tenfold improvement in productivity, reliability, and simplicity within a decade. This time around, the promise was much like others, but they felt the need to note that their revolutionary new application/framework/doohickey will allow business analysts to directly build applications 10 times as fast without the need for programmers! Ah yeah! Get rid...
This post is now outdated
I apologize for not blogging this over the weekend as I had planned, but the weather this weekend was just fantastic so I spent a lot of time outside with my son. If you haven’t heard yet, Visual Studio 2010 Beta 1 is now available for MSDN subscribers to download. It will be more generally available on Wednesday, according to Soma. You can find a great whitepaper which describes what is new for web developers in ASP 4 which is included. One thing you’ll notice is that ASP.NET MVC is not included...
A while back, I wrote about Donut Caching in ASP.NET MVC for the scenario where you want to cache an entire view except for a small bit of it. The more technical term for this technique is probably “cache substitution” as it makes use of the Response.WriteSubstitution method, but I think “Donut Caching” really describes it well — you want to cache everything but the hole in the middle. However, what happens when you want to do the inverse. Suppose you want to cache the donut hole, instead of the donut? I think we should nickname all of...
Say you’re building a web application and you want, against your better judgment perhaps, to allow end users to easily customize the look and feel – a common scenario within a blog engine or any hosted application. With ASP.NET, view code tends to be some complex declarative markup stuck in a file on disk which gets compiled by ASP.NET into an assembly. Most system administrators would first pluck out their own toenail rather than allow an end user permission to modify such files. It’s possible to store such files in the database and use a VirtualPathProvider to load...
Tim Davis posted an updated version of this solution on his blog. His includes the following:
jqGrid 3.8.2
.NET 4.0 Updates
VS2010
jQuery 1.4.4
jQuery UI 1.8.7
Continuing in my pseudo-series of posts based on my ASP.NET MVC Ninjas on Fire Black Belt Tips Presentation at Mix (go watch it!), this post covers a demo I did not show because I ran out of time. It was a demo I held in my back pocket just in case I went too fast and needed one more demo. A common scenario when building web user interfaces is providing a pageable and sortable grid of data. Even...
A Cross-site request forgery attack, also known as CSRF or XSRF (pronounced sea-surf) is the less well known, but equally dangerous, cousin of the Cross Site Scripting (XSS) attack. Yeah, they come from a rough family. CSRF is a form of confused deputy attack. Imagine you’re a malcontent who wants to harm another person in a maximum security jail. You’re probably going to have a tough time reaching that person due to your lack of proper credentials. A potentially easier approach to accomplish your misdeed is to confuse a deputy to misuse his authority to commit the dastardly act...
I’ve been relatively quiet on my blog lately in part because of all the work on ASP.NET MVC. However, the ASP.NET team is a relatively small team so we often are required to work on multiple features at the same time. So part of the reason I’ve been so busy is that while we were wrapping up ASP.NET MVC, I was also busy working on a core .NET Framework feature we plan to get into the next version (it was a feature that originated with our team, but we realized it belongs in the BCL).
The goal of the feature is...
Recently, I tried to accomplish a simple task on a website which frustrated me because what should have been simple, was not. All I wanted to do was go to the Mix website and quickly find links to my sessions so I could post them here. Even I should be able to figure this out. As a note, I’m using the Mix site as my illustration here, but I do it out of love and not mean spiritedness. Mix is my favorite conference, but its website…leaves something to be desired. It seems particularly interesting that I’d run into...
I don’t know about you, but a great way to learn a new technology is to start using it. But to even start using it, it helps to be able to look at a real-world running application built on that technology. Combine that with source code and a walkthrough, and I think you have a winning combination.
That’s where NerdDinner comes in.
NerdDinner.com is the brainchild (and a big child at that) of Scott Hanselman. The concept is simple, let’s get nerds together over dinner so great ideas can flourish. The site is a great way to organize...
Alternate Title: Linq, it’s not just for SQL. I admit, I’m not very proficient with functional programming. It almost feels like a gang war at times - on one side of the tracks is Turing’s crew, sporting their imperative ways. On the other side is the Church group, luring wayward souls onto their turf with the promise of code salvation in the form of functional language. Matt Podwysocki is one of those Church evangelists, constantly reaching out to me, a lost soul, with the promises of eternal code salvation in the form of F#. I keep meaning to...
Today I read something where someone was comparing Web Forms to ASP.NET MVC and suggested that Web Forms does a lot more than ASP.NET MVC to protect your site from malicious attacks. One example cited was that Server controls automatically handled HTML encoding so you don’t have to really think about it. The idea here is that Web Forms automatically protects you from XSS attacks. My friends, I’m afraid this is just not true. Take a look at the following page code. <%@ Page Language="C#" Inherits="System.Web.UI.Page" %>
<%
//For demo purposes,...
UPDATE: Be sure to read Peli’s post in which he explores all of these implementations using PEX. Apparently I have a lot more unit tests to write in order to define the expected behavior of the code. I recently wrote a post in which I examined some existing implementations of named format methods and then described the fun I had writing a routine for implementing named formats. In response to that post, I received two new implementations of the method that are worth calling out. The first was sent to me by Atif Aziz, who I’ve corresponded...
I’ve been having trouble getting to sleep lately, so I thought last night that I would put that to use and hack on Subtext a bit. While doing so, I ran into an old Asynchronous Fire and Forget helper method written way back by Mike Woodring which allows you to easily call a delegate asynchronously. On the face of it, it seems like you could simply call BeginInvoke on the delegate and be done with it, Mike’s code addresses a concern with that approach: Starting with the 1.1 release of the .NET Framework, the SDK...
DOUBLE UPDATE! Be sure to read Peli’s post in which he explores all of these implementations using PEX. Apparently I have a lot more unit tests to write in order to define the expected behavior of the code. UPDATE: By the way, after you read this post, check out the post in which I revisit this topic and add two more implementations to check out. Recently I found myself in a situation where I wanted to format a string using a named format string, rather than a positional one. Ignore for the moment the issue on whether this...
I was reading Jeff Atwood’s latest post, Programming: Love it or Leave it when I came across this part, emphasis mine. Joel implied that good programmers love programming so much they’d do it for no pay at all. I won’t go quite that far, but I will note that the best programmers I’ve known have all had a lifelong passion for what they do. There's no way a minor economic blip would ever convince them they should do anything else. No way. No how. Unlike Jeff, I will go that far. I love to...
I recently learned about a very subtle potential security flaw when using JSON. While subtle, it was successfully demonstrated against GMail a while back. The post, JSON is not as safe as people think it is, covers it well, but I thought I’d provide step-by-step coverage to help make it clear how the exploit works. The exploit combines Cross Site Request Forgery (CSRF) with a JSON Array hack allowing an evil site to grab sensitive user data from an unsuspecting user. The hack involves redefining the Array constructor, which is totally legal in Javascript. Let’s walk through the attack step...
UPDATE: I added three new unit tests and one interesting case in which the three browser render something differently. Well I’m back at it, but this time I want to strip all HTML from a string. Specifically: Remove all HTML opening and self-closing tags: Thus <foo> and <foo /> should be stripped. Remove all HTML closing tags such as </p>. Remove all HTML comments. Do not strip any text in between tags that would be rendered by the browser. This may...
A while ago I wrote a blog post about how painful it is to properly parse an email address. This post is kind of like that, except that this time, I take on HTML. I’ve written about parsing HTML with a regular expression in the past and pointed out that it’s extremely tricky and probably not a good idea to use regular expressions in this case. In this post, I want to strip out HTML comments. Why? I had some code that uses a regular expression to strip comments from HTML, but found one of those feared...
Usability and Discoverability (also referred to as Learnability) are often confused with one another, but they really are distinct concepts. In Joel Spolsky’s wonderful User Interface Design for Programmers (go read it!), Joel provides an metaphor to highlight the difference. It takes several weeks to learn how to drive a car. For the first few hours behind the wheel, the average teenager will swerve around like crazy. They will pitch, weave, lurch, and sway. If the car has a stick shift they will stall the engine in the middle of busy intersections in a truly terrifying...
UPDATE: Due to differences in the way that ASP.NET MVC 2 processes request, data within the substitution block can be cached when it shouldn’t be. Substitution caching for ASP.NET MVC is not supported and has been removed from our ASP.NET MVC Futures project.
This technique is NOT RECOMMENDED for ASP.NET MVC 2.
With ASP.NET MVC, you can easily cache the output of an action by using the OutputCacheAttribute like so. [OutputCache(Duration=60, VaryByParam="None")]
public ActionResult CacheDemo() {
return View();
}
One of the problems with this approach is that it is an all or nothing approach....
Whew! I’ve finally found a bit of time to write about my impressions of the PDC 2008 conference. If you’re looking for insightful commentary and a “What does this all mean” post, you’ve come to the wrong place. There are plenty of others providing that sort of commentary. I’ll just string together some random impressions and pics from my perspective. First of all, one thing I’m very impressed with is that all sessions are viewable online almost immediately afterwards, with full video of the slides and the presenter. Now I understand why they asked me not to pace...
In my last post, I joked that the reason that someone gave me all 1s in my talk was a misunderstanding of the evaluation form. In truth, I just assumed that someone out there really didn’t like what I was showing and that’s totally fine. It was something I found funny and I didn’t really care too much. But I received a message from someone that they tried to evaluate the session from the conference hall, but the evaluation form was really screwy on their iPhone. For example, here’s how it’s supposed to look in IE. ...
Download the sample project to play with the code as you read this blog post. Using the DefaultModelBinder in ASP.NET MVC, you can bind submitted form values to arguments of an action method. But what if that argument is a collection? Can you bind a posted form to an ICollection<T>? Sure thing! It’s really easy if you’re posting a bunch of primitive types. For example, suppose you have the following action method. public ActionResult UpdateInts(ICollection<int> ints) {
return View(ints);
}
You can bind to that by simply submitting...
UPDATE: Pretty much disregard this entire post, except as a reminder that it’s easy to make a mistake with DOCTYPEs and markup. As many people have told me, I had an error I didn’t notice in the original HTML. I forgot to close the SELECT tag. I’ll leave the post as-is. Not only that, the DOCTYPE is not specified in the document, which causes IE to render in Quirks mode, not standards mode. So I guess the bug is in IE 7 rendering. So this is a case of PEBKAC, the bug is in the HTML, not the...
Download the MSI and Release notes here. Last night we released ASP.NET CodePlex Preview 5 on CodePlex. Be on the lookout for one of those famous epic blog posts from ScottGu describing the release. In the meanwhile, the release notes contain short write-ups of what has changed. We didn’t originally plan to have another preview. However, we implemented a few significant chunks of functionality and were dying to get feedback so that we could incorporate it into the product before Beta. It helps that with five or so of these interim releases, we’ve become pretty efficient producing...
I admit, up until now I’ve largely ignored the BDD (Behavior Driven Development) Context/Specification style of writing unit tests. It’s been touted as a more approachable way to learn TDD (Test Driven Development) and as a more natural transition from user stories to the actual code design. I guess my hesitation to give it a second thought was that I felt I didn’t need a more approachable form of TDD. Recently, my Subtext partner in crime, Steve Harman, urged me to take another fresh look at BDD Context/Specification style tests. I trust Steve’s opinion, so I took another look...
A commenter to my last post asks the following question, What is the difference between a beta, a CTP, a fully-supported out of band release, an RTM feature, and a service pack? The answer you get will differ based on who you ask, but I’ll give you my two cents on what these terms mean. Beta Let’s start with Beta. A great starting point is this post by Jeff Atwood entitled Alpha, Beta, and Sometimes Gamma. The software is complete enough for external testing -- that is,...
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? 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...
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. 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...
One principle to follow when writing a unit test is that a unit test should ideally not cross boundaries. 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 ...
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. Now that Preview 4 is out, I revisited the prototype and got it working again. I use the term working...
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...
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....
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...
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. 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...
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. 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...
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. 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...
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. No 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...
UPDATE: I just posted the working demo here. I wish I could have been there, but I was celebrating my son’s first birthday (which gives me an opening to gratuitously post a picture of the kid here). I’m talking about Tech-Ed 2008 Orlando of course where John Lam presented a demo of IronRuby running on top of ASP.NET MVC. This demo builds on prototype work I’ve done with defining ASP.NET MVC routes and views using IronRuby. The final missing piece was defining controllers using IronRuby. Working with members of John’s team, Levi (a dev...
My compadre Scott Hunter, another PM on the ASP.NET team, who happens to work on the Dynamic Data feature, recently put together an example of using ASP.NET MVC and Dynamic Data Web Forms together in the same application. Look for the link to MvcDynamicData.zip on this Code Gallery page. I’ve been working on a post detailing a couple different ways to integrate WebForms and MVC, but life has been really busy for me lately. Hopefully I’ll get that to you soon. In the meanwhile, you can probably learn all you need to know by looking at this...
The design is never right the first time. Nor is it usually right the second time. This is one of those key lessons you learn over time building real software, and is the source of one of the chief complaints leveled at the Waterfall methodology for building software, which puts heavy emphasis on getting the design right up front. We have to define “right” in this case. If by “right” you mean perfect, then I don’t think the design is ever right, as I’ve argued in the past that there is no perfect design. Recently, this lesson...
I updated the template to have the correct assembly references so it should work now out of the box. Sorry about that.
A while ago Scott Hanselman linked to my Northwind sample which itself was spawned from an initial sample that Brad Abrams wrote.
As I like to say (to anyone who will listen)
There ain’t no party like a Northwind Party
So I went and updated my sample to work well with the recently released ASP.NET MVC Preview 3Beta.
Download it here.
The news is out, the beta for the Visual Studio 2008 and the .NET Framework 3.5 Service Pack has been released. As it relates to ASP.NET MVC, there are two important points to notice about the SP1 release:
ASP.NET MVC is not included
URL Routing is included
Now you can see why there’s been so much focus on Routing from the MVC team, as Routing is now part of the Framework and is not out-of-band. This meant that we had to put a lot more effort into Routing to make sure it was...
In my last post, I walked through a simple example of an ActionResult that you can use to transmit a file to the user’s browser along with a download prompt. The MVC framework will include several useful action results for common tasks. However, we might not cover all results you might want to return. In this post, I walk through a simple result that will cover all remaining cases. With the DelegatingResult, you simply pass it a delegate. This provides ultimate control. Let’s see it in action. public ActionResult Hello()...
Not long ago, my compadre Scott Hanselman related the following story... In a recent MVC design meeting someone said something like "we’ll need a Repeater control" and a powerful and very technical boss-type said: "We’ve got a repeater control, it’s called a foreach loop." I beg to differ. I think we can do better than a foreach loop. A foreach loop doesn’t help you handle alternating items, for example. My response to this story is, “The foreach loop is not our repeater control. Our repeater control is an iterating extension...
File this one away for the next time your boss comes in and asks,
Yeaaah, I’m going to need you to make that little change to the code. It’ll only take you a couple hours, right?
Software has this deceptive property in which some changes that seem quite big and challenging to the layman end up being quite trivial, while other changes that seem quite trivial, end up requiring a lot of thought, care, and work.
Often, little changes add up to a lot.
I’m going to walk through a change we made that seemed like a no-brainer but ended up having a...
In a recent post I expressed a few thoughts on using a DSL instead of an XML config file. I followed that up with a technical look at monkey patching CLR objects using IronRuby, which explores a tiny bit of interop. These posts were precursors to this post in which I apply these ideas to an implementation that allows me to define ASP.NET MVC Routes using IronRuby. Also included in this download is an incomplete implementation of an IronRuby view engine. I haven't yet implemented layouts. IronRubyMvcDemo.zip Download (4.93 MB) This implementation works with the latest CodePlex...
In my last post I set the stage for this post by discussing some of my personal opinions around integrating a dynamic language into a .NET application. Using a DSL written in a dynamic language, such as IronRuby, to set up configuration for a .NET application is an interesting approach to application configuration. With that in mind, I was playing around with some IronRuby interop with the CLR recently. Ruby has this concept called Monkey Patching. You can read the definition in the Wikipedia link I provided, but in short, it is a way to modify the behavior of...
Disclaimer: My opinions only, not anyone else’s. Nothing official here. I shouldn’t have to say this, but past history suggests I should. P.S. I’m not an expert on DSLs and Dynamic Languages ;) This week I attended a talk by John Lam on IronRuby in which he trotted out the Uncle Ben line, with great power comes great responsibility. He was of course referring to the power in a dynamic language like Ruby. Another quip he made stuck with me. He talked about how his brain sometimes gets twisted in a knot reading Ruby code written using metaprogramming...
UPDATE: Just to prove that this is a preview of a preview, we had a signing problem with the initial pre-built VSI download. If you tried building from source, everything should’ve been ok. We apologize for that. Even though this is meant to be a rough preview, we do want to have a high quality bar in that you should be able to try out the code. So if you run into that problem, please do download the VSI again.
It’s no secret that Microsoft can get better at naming non RTM (Release to Manufacturing) releases. We have terms like CTP,...
Made a few corrections on having default.aspx in the root due to a minor bug we just found. Isn’t preview code so much fun?
We’ve been making some changes to routing to make it more powerful and useful. But as Uncle Ben says, with more power comes more responsibility. I’ll list out the changes first and then discuss some of the implication of the changes.
Routes no longer treat the . character as a separator. Currently, routes treat the . and / characters as special. They are separator characters. The upcoming release of routing will only treat the...
Way down the road, it would be nice to be able to build ASP.NET MVC applications using a DLR language such as IronRuby. However, enabling DLR language support isn’t free.
There are going to be places in our design that are specific to statically typed languages (such as Attribute based filters) that just wouldn’t work (or would be too unnatural) with a dynamic language.
Ideally we can minimize those cases, and for the ones we can’t, we need to make sure the extensibility of the framework allows for extending the system in such a way that we can provide a DLR friendly...
When I build applications, I personally like to have my unit tests in a separate class library project than the application I am testing.
That’s just how I roll.
I just assumed this is how everyone structures their unit tests, but I’ve talked with some people who have a deep history in TDD who put their code in the same project.
So I wanted to create a simple poll to find out how people are actually structuring their unit tests. I’ve been involved in various internal discussions looking at
how Microsoft design, tools, code can better support unit testing across the board.
Note...
There’s a great interview on the How Software is Built blog with Brad Wilson, a developer in Microsoft’s OfficeLabs team, but probably better known for his work on xUnit.net, CodePlex, and ObjectBuilder. What I particularly liked about this post was the insight Brad provides on the diverse views of open source outside and inside of Microsoft as well as his own personal experience contributing to many OSS projects. It’s hard for some to believe, but there are developers internal to Microsoft who like and contribute to various open source projects. Another reason that Brad gets a thumbs...
It’s been all quiet on the Subtext front for a while. While I think many open source projects face the occasional lull, Subtext was hit by a Perfect Storm of inactivity. This was mostly because several of the key developers all ended up having job changes (and moves) around the same time. For me, the move to Microsoft and up to the Seattle area took up a lot of my time and energy. I finally feel settled in so I fired up the old TortoiseSVN client and got latest from the tree excited to see what new goodness...
UPDATE: I should have entitled this “Comparing Rhino Mocks and MoQ for State Based Testing”. I tend to prefer state-based testing over interaction based testing except in the few cases where it is absolutely necessary or makes the test much cleaner. When it is necessary, it is nice to have interaction based testing available. So my comparison is incomplete as I didn’t compare interaction based testing between the two frameworks. For the longest time I’ve been a big fan of Rhino Mocks and have often written about it glowingly. When Moq came on the scene, I remained blissfully ignorant...
Whew! I’ve held off writing about MVC until I could write a non-MVC post in response to some constructive criticism (It’s not just Sean, Jeff mentioned something to me as well). Now that I’ve posted that, perhaps I’ve bought myself a few MVC related posts in a row before the goodwill runs dry and I have to write something decidedly not MVC related again. ;) As ScottGu recently posted, the ASP.NET MVC source code is now available via CodePlex. A move like this isn’t as simple as flipping a switch and *boom* it happens. No, it takes a lot...
UPDATE: I’ve added a NuGet package named "routedebugger" to the NuGet feed, which will make it much easier to install.
In Scott Hanselman’s wonderful talk at Mix, he demonstrated a simple little route tester I quickly put together.
This utility displays the route data pulled from the request of the current request in the address bar. So you can type in various URLs in the address bar to see which route matches. At the bottom, it shows a list of all defined routes in your application. This allows you to see which of your routes would match the current URL.
The reason this...
UPDATE: I updated the sample to work with the final version of ASP.NET Routing included with ASP.NET 3.5 SP1. This sample is now being hosted on CodePlex.
Download the demo here
In my last post I described how Routing no longer has any dependency on MVC. The natural question I’ve been asked upon hearing that is “Can I use it with Web Forms?” to which I answer “You sure can, but very carefully.”
Being on the inside, I’ve had a working example of this for a while now based on early access to the bits. Even so, Chris Cavanagh impressively beats me to...
At this year’s Mix conference, we announced the availability of the second preview for ASP.NET MVC which you can download from here. Videos highlighting MVC are also available. Now that I am back from Mix and have time to breathe, I thought I’d share a few (non-exhaustive) highlights of this release as well as my thoughts on the future. New Assemblies and Routing Much of the effort and focus of this release was put into routing. If you’ve installed the release, you’ll notice that MVC has been factored into three assemblies: ...
This is part 2 in an ongoing series in which I talk about various design and versioning issues as they relate to Abstract Base Classes (ABC), Interfaces, and Framework design. In part 1 I discussed some ways in which ABCs are more resilient to versioning than interfaces. I haven’t covered the full story yet and will address some great points raised in the comments.
In this part, I want to point out some cases in which Abstract Base Classes fail in versioning. In my last post, I mentioned you could simply add new methods to an Abstract Base Class and not...
Eilon Lipton recently wrote a bit about context objects in ASP.NET MVC and in an “Oh by the way” moment, tossed out the fact that we changed the IHttpContext interface to the HttpContextBase abstract base class (ABC for short). Not long after, this spurred debate among the Twitterati. Why did you choose an Abstract Base Class in this case? The full detailed answer would probably break my keyboard in length, so I thought I would try to address it in a series of posts. In the end, I hope to convince the critiques that the real point of...
By the way my blogging frequency has declined, you can guess I’ve been quite busy here at Microsoft preparing for the next release of ASP.NET MVC. It’s not just working on specs, design meetings, etc... that keep me busy. It’s preparing for several talks, various spec reviews, building hands on labs, demo and and app building, etc...that keeps me busy. All the while I am still learning the ropes and dealing with selling a house in L.A. and buying a house up here. There’s a lot that goes into being a PM I naively didn’t expect, on top...
UPDATE: I improved this based on some feedback in my comments.
With ASP.NET MVC it is possible for someone to try and navigate directly to a .aspx view. In general, this only leaves them with an ugly error message as Views typically need ViewData in order to work.
However, one approach that I think will easily work is to create a Web.config file in the root of your Views directory that contains the following.
We need to do more testing on our side to make sure there's no pathological case in doing this, but so far in my personal testing, it seems to...
If you know me, you know I go through great pains to write automated unit tests for my code. Some might even call me anal about it. Those people know me too well. For example, in the active branch of Subtext, we have 882 unit tests, of which I estimate I wrote around 800 of those. Yep, if you’re browsing the Subtext unit test code and something smells bad, chances are I probably dealt it. Unfortunately, by most definitions of Unit Test, most of these tests are really integration tests. Partly because I was testing legacy code that...
At the risk of embarrassing myself and eliciting more groans, I am going to share a joke I made up for my Code Camp talk. I was inspired to come up with some humor based on Jeff’s Sesame Street Presentation Rule post. I fully understand his post was addressing something deeper than simply telling a gratuitous joke in the presentation.
The context is that I just finished explaining the various dependencies between the Model, View, and Controller within the MVC pattern.
UPDATE: Updating this joke as the feedback comes in. The original is at the bottom.
So a Model, a View, and a...
The Seattle Code Camp (which despite the misleading photo, isn’t a camping trip) is now over and I have nothing but good things to say about it. I didn’t get a chance to see a lot of talks but did enjoy the xUnit.net talk by Jim Newkirk and Brad Wilson. I’m a fan of their approach to providing extensibility and this session provided all the impetus I needed to really give xUnit.net a try rather than simply talking about trying it. :)
As for my own talk, I had the great pleasure of showing up late to my talk. To...
In a recent post, Frans Bouma laments the lack of computer science or reference to research papers by agile pundits in various mailing lists (I bet this really applies to nearly all mailing lists, not just the ones he mentions). What surprised me to no end was the total lack of any reference/debate about computer science research, papers etc. ... in the form of CS research. Almost all the debates focused on tools and their direct techniques, not the computer science behind them. In general asking ’Why’ wasn’t answered with: "research has shown that..." but with...
Six months ago and six days after the birth of my son, Subkismet was also born which I introduced as the cure for comment spam. The point of the project was to be a useful class library containing multiple spam fighting classes that could be easily integrated into a blog platform or any website that allows users to comment. One of my goals with the project was to make it safe to enable trackbacks/pingbacks again. I’ve been very happy that others have joined in the Subkismet efforts. Mads Kristensen, well known for BlogEngine.NET, contributed some code. Keyvan...
A common pattern when submitting a form in ASP.NET MVC is to post the form data to an action which performs some operation and then redirects to another action afterwards. The only problem is, the form data is not repopulated automatically after a redirect. Let's look at remedying that, shall we?
When submitting form data, the ASP.NET MVC Toolkit includes a helper extension method that makes it easy to go the other direction, populating an object from the request. Check out the following simplified controller action adapted from an example ScottGu’s post on handling form data.
[ControllerAction]
public void Create()
{
Article article...
Recently, Maxfield Pool from CodeSqueeze sent me an email about a new monthly feature he calls Developer Faceoff in which he pits two developers side-by-side for a showdown.
It’s an obvious attempt to gain readers via an appeal to vanity of the featured bloggers who have no choice to link to it. Brilliant! :)
Seriously, I think it’s a fun and creative idea, but I have no credibility in saying so because I’m obviously biased being featured alongside my longtime nemesis and friend, Scott Hanselman. So check it out for yourself.
Some of my answers were truncated due to the format so...
The ASP.NET Routing engine used by ASP.NET MVC plays a very important role. Routes map incoming requests for URLs to a Controller and Action. They also are used to construct an URL to a Controller/Action. In this way, they provide a two-way mapping between URLs and controller actions. When building routes, it may be useful to write unit tests for the routes to ensure that you’ve set up the proper mappings you intend. ScottGu touched a bit on unit testing routes in part 2 of his series on MVC in which he covers URL Routing. In this post,...
Yesterday, Wally McClure interviewed me for the ASP.NET Podcast Show. We chatted for around half an hour on my background, Microsoft, and ASP.NET MVC.
It was a fun chat, but I have to warn you, I was very sleep deprived (a constant condition lately), so at points I tend to ramble a bit, second-guess myself (I was right the first time, model-view-thing-editor!), and even contradict myself.
I’m not normally that harebrained. I promise. Ok, maybe just a little. With all those caveats in place, give it a listen.
This is why writing a blog is so much easier than being interviewed. All the...
I have a set of little demos apps I’ve been working on that I want to release to the public. I need to clean them up a bit (you’d be surprised how much I swear in comments) and make sure they work with the CTP. Hopefully I will publish them on my blog over the next few weeks.
In the meanwhile, there’s some great stuff being posted by the community I want to call out. All these great posts are making my life easier.
Routing Revisited - Sean Lynch talks about some interesting route scenarios. Currently the Route...
Eilon Lipton, the lead developer on the ASP.NET MVC project shares some of his thoughts on the design philosophy guiding the shaping of the framework.
There have been many post describing what the framework is and how to perform tasks, which are really useful. I think a more reflective post like this is a breath of fresh air and a nice insight into how the team is making decisions.
Eilon also covers some of the lessons we’ve already learned in building the CTP, and some of the changes we have planned for the next CTP.
At the end he lists some interesting...
UPDATE: ASP.NET MVC now works with Visual Web Developer Express SP1
Some developers who downloaded the ASP.NET Extensions CTP specifically for ASP.NET MVC and then opened up Visual Web Developer like it was Christmas morning instead got a lump of coal.
We currently only include Web Application Projects for ASP.NET MVC, which Visual Web Developer does not support. I was planning to write up a post on this, but Scott Koon beat me to it.
And thank goodness! I’m busy enough as it is already. It’s all part of my master plan to have members of the community doing my job for...
UPDATE: Completely ignore the contents of this post. All of this is out-dated. Test specific subclasses are no longer necessary with ASP.NET MVC since our April CodePlex refresh Just a brief note on writing unit tests for controller actions. When your action has a call to RedirectToAction or RenderView (yeah, pretty much every action) be aware that these methods have dependencies on various context objects. If you attempt to mock these objects, you sometimes also have to mock their dependencies and their dependencies' dependencies and so on, depending on what you are trying to test. This is why...
UPDATE: Much of this post is out-of-date with the latest versions of MVC. We long sinced removed the ControllerAction attribute.
Note: If you hate reading and just want the code, it is at the bottom.
Eons ago, I was a youngster living in Spain watching my Saturday morning cartoons when my dad walked in bearing freshly made taquitos and a small cup of green stuff. The taquitos looked delicious, but I was appalled at the green stuff.
Was this some kind of joke? My dad wanted me to simply just taste it but I refused because I absolutely knew it would suck...
One of the guiding principles in the design of the new ASP.NET MVC Framework is enabling TDD (Test Driven Development) when building a web application. If you want to follow along, this post makes use of ASP.NET MVC CodePlex Preview 4 which you’ll need to install from CodePlex. I’ll try and keep this post up to date with the latest releases, but it may take me time to get around to it. This post will provide a somewhat detailed walk-through of building a web application in a Test Driven manner while also demonstrating one way to integrate a Dependency...
Sometimes when writing unit tests, you run into the case where you want to override the behavior of a specific method.
Here’s a totally contrived example I just pulled from my head to demonstrate this idea. Any similarity to specific real world scenarios is coincidental ;). Suppose we have this class we want to test.
public class MyController
{
public void MyAction()
{
RenderView("it matches?");
}
public virtual void RenderView(string s)
{
throw new NotImplementedException("To ensure this method is overridden.");
}
}
What we have here is a class...
Note that in the same vein as Pele, Ronaldinho and Ronaldo, Joel has reach that Brazillian Soccer player level of stardom in the geek community and can pretty much go by just his first name. Admit it, you knew who I was referring to in the title. Admit it! Please indulge me in a brief moment of hubris. I was reading part 1 of Joel Spolsky’s talk at Yale that he gave on November 28 and came upon this quote on code provability... The problem, here, is very fundamental. In order to...
My friend (and former boss and business partner) Micah found this gem of a quote from Donald Knuth addressing code proofs. Beware of bugs in the above code; I have only proved it correct, not tried it. Micah writes more on the topic and reminds me of why I enjoyed working with him so much. He’s always been quite thoughtful in his approach to problems. And I’m not just saying that because he agrees with me. ;) On another note, several commenters pointed out that one thing I didn’t mention before, but should...
I’m currently doing some app building with ASP.NET MVC in which I try to cover a bunch of different scenarios. One scenario in particular I wanted to cover is approaching an application using a Test Driven Development approach. I especially wanted to cover using various Dependency Injection frameworks, to make sure everything plays nice. Since I’ve already seen demos with Castle Windsor and Spring.NET, I wanted to give StructureMap a try. Here is the problem I’ve run into. Say I have a class like so: public class MyController :...
Frans Bouma wrote an interesting response to my last post, Writing Testable Code Is About Managing Complexity entitled Correctness Provability should be the goal, not Testability. He states in his post: When focusing on testability, one can fall into the trap of believing that the tests prove that your code is correct. God I hope not. Perhaps someone in theory could fall into that trap, but a person could also fall into the trap and buy a modestly priced bridge I have to sell to them in the bay area? This seems like...
When discussing the upcoming ASP.NET MVC framework, one of the key benefits I like to tout is how this framework will improve testability of your web applications.
The response I often get is the same question I get when mention patterns such as Dependency Injection, IoC, etc...
Why would I want to do XYZ just to improve testability?
I think to myself in response
Just to improve testability? Isn’t that enough of a reason!
That’s how excited I am about test driven development. Testing seems enough of a reason for me!
Of course, when I’m done un-bunching my knickers, I realize that despite all the benefits...
UPDATE: This content is a bit outdated as these interfaces have changed in ASP.NET MVC since the writing of this post.
One task that I relish as a PM on the ASP.NET MVC project is to build code samples and sample applications to put the platform through its paces and try to suss out any problems with the design or usability of the API.
Since testability is a key goal of this framework, I’ve been trying to apply a Test Driven Development (TDD) approach as I build out the sample applications. This has led to some fun discoveries in terms of using...
One thing I’ve found with various open source projects is that many of them contain very useful code nuggets that could be generally useful to developers writing different kinds of apps. Unfortunately, in many cases, these nuggets are hidden. If you’ve ever found yourself thinking, Man, I wonder how that one open source app does XYZ because I could use that in this app, then you know what I mean. One goal I have with Subtext is to try and expose code that I think would be useful to others. It’s part of the reason I started the Subkismet...
It is a sad fact of life that, in this day and age, arguments are not won with sound logic and reasoning. Instead, applying the principle of framing an argument is much more effective at swaying public opinion. So the next time you try to make headway introducing Test Driven Development (or even simply introducing writing automated unit tests at all) into an organization and are rebuffed with... Don’t bring your fancy schmancy flavor of the week agile manifesto infested “methodology” here kiddo. I’ve been writing software my way for a loooong time... You can reply with... ...
This is a quick follow-up to my last post. That seemed like such a common test situation I figured I’d write a quick generic method for encapsulating those two tests. I’ll start with usage. [Test]
public void FileBrowserSecureCreationTests()
{
AssertSecureCreation<FileBrowserConnector>(new string[] {"Admins"});
}
And here’s the method.
/// <summary>
/// Helper method. Makes sure you can create an instance
/// of a type if you have the correct role.</summary>
/// <typeparam name="T"></typeparam>
/// <param name="allowedRoles"></param>
public static void AssertSecureCreation<T>(string[] allowedRoles
, params object[] constructorArguments)
{
try
{
Activator.CreateInstance(typeof (T),...
This is a simple little demonstration of how to write unit tests to test out a specific role based permission issue using NUnit/MbUnit and Rhino Mocks.
In Subtext, we have a class named FileBrowserConnector that really should only ever be constructed by a member of the Admins role. Because this class can write to the file system, we want to take extra precautions other than simply restricting access to the URL in which this object is created.
Here are two tests I wrote to begin with.
[Test]
[ExpectedException(typeof(SecurityException))]
public void NonAdminCannotCreateFileConnector()
{
new FileBrowserConnector();
}
[Test]
public void AdminCanCreateFileConnector()
{
MockRepository mocks = new MockRepository();
IPrincipal principal;
using (mocks.Record())
...
It was only two and a half months ago when I wrote about receiving my Microsoft MVP award. I was quite honored to receive this award. In a follow-up comment to that post, rich with unintentional foreshadowing, I mentioned the following... However, I would like to hit up that MVP conference in Redmond before doing anything to cause my MVP status to be dropped. Unfortunately, I will not be retaining my MVP status long enough for the MVP conference. I have committed an action that has forced Microsoft’s hand in this matter and they must remove my MVP status....
I was thinking about alternative ways to block comment spam the other day and it occurred to me that there’s potentially a simpler solution than the Invisible Captcha approach I wrote about. The Invisible Captcha control plays upon the fact that most comment spam bots don’t evaluate javascript. However there’s another particular behavioral trait that bots have that can be exploited due to the bots inability to support another browser facility. You see, comment spam bots love form fields. When they encounter a form field, they go into a berserker frenzy (+2 to strength, +2 hp per level, etc...) trying to...
Raise your hand if you know how to validate an email address. For those of you with your hand in the air, put it down quickly before someone sees you. It’s an odd sight to see someone sitting alone at the keyboard raising his or her hand. I was speaking metaphorically. Before yesterday I would have raised my hand (metaphorically) as well. I needed to validate an email address on the server. Something I’ve done a hundred thousand times (seriously, I counted) using a handy dandy regular expression in my personal library. This time, for some reason, I decided to...
Most of the time when I’m testing my code, I only test it using the en-US culture since, ...well..., I speak English and I live in the U.S. Isn’t the U.S. the only country that matters anyway? ;) Fortunately, there are Subtext team members living in other countries ready to smack such nonsensical thoughts from my head and keep me honest about Localization and Internationalization issues. Simone, who is an Italian living in New Zealand, pointed out that a particular unit test that works on my machine always fails on his machine. Here’s the test. [RowTest]
[Row("4/12/2006", "04/12/2006 00:00:00 AM")]
[Row("20070123T120102", "01/23/2007 12:01:02...
I wrote about this on my company’s blog, but thought I’d mention it here since I assume not everyone has jumped at the chance to subscribe to that blog (go on, it won’t bite) ;) Simone Busoli wrote a pretty cool API to query open source code via Koders.com by leveraging the ASP.NET RSS Toolkit. Read more about it at his blog.
If you’ve worked with unit test frameworks like NUnit or MbUnit for a while, you are probably all too familiar with the set of assertion methods that come built into these frameworks. For example: Assert.AreEqual(expected, actual);
Assert.Between(actual, left, right);
Assert.Greater(value1, value2);
Assert.IsAssignableFrom(expectedType, actualType);
// and so on...
While the list of methods on the Assert class is impressive, it leaves much to be desired. For example, I needed to assert that a string value was a member of an array. Here’s the test I wrote.
[Test]
public void CanFindRole()
{
string[] roles = Roles.GetRolesForUser("pikachu");
bool found = false;
foreach (string role in roles)
...
Although I am a big fan of Rhino Mocks, I typically favor State-Based over Interaction-Based unit testing, though I am not totally against Interaction Based testing.
I often use Rhino Mocks to dynamically create Dummy objects and Fake objects rather than true Mocks, based on this definition given by Martin Fowler.
Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database...
Several pople have asked me recently about the nice code syntax highlighting in my blog. For example: public string Test()
{
//Look at the pretty colors
return "Yay!";
}
A long time ago, I wrote about using http://www.manoli.net/csharpformat/ for converting code to HTML.
But these days, I use Omar Shahine’s Insert Code for Windows Live Writer plugin for, you guessed it, Windows Live Writer. This plugin just happens to use the Manoli code to perform syntax highlighting.
I recommend downloading and referencing the CSS stylesheet from the Manoli site and making sure to uncheck the Embed StyleSheet option in the plugin.
The...
Just something I noticed today. A lot of people (I may even be guilty of this) publish their emails on the web using the following format: name at gmail dot com Substitute gmail dot com with your favorite email domain. The problem with this approach is that it is trivially easy to harvest email addresses in this format with Google. First, do a search for the following text (include the quotes): "* at * dot com" Now, all you need to do is run a regular expression over the results. For example, using your favorite regular...
Ayende just announced the release of Rhino Mocks 3.0. The downloads are located here. If you aren’t subscribed to Ayende’s blog, I highly recommend it. This guy never sleeps and churns out code like a tornado.
Ever since I discovered mocking frameworks in general, and especially Rhino Mocks, mocking has become an essential part of my unit testing toolkit.
A while ago I wrote a short intro demonstrating how to write unit tests for events defined by an interface. This small example shows the usefulness of something like Rhino Mocks.
If you’re wondering what the difference between a mocks, stubs, and fakes, be...
Some people think the ViewState is the spawn of the devil. Not one to be afraid of being in bed with the devil, I feel a tad bit less negative towards it, as it can be very useful.
Still, it has its share of disadvantages. It sure can get bloated. Not only that, but disabling ViewState can wreack havock with the functionality of many controls.
This is why ASP.NET 2.0 introduces the control state. The basic idea is that there is some state that should be considered the data for the control, while other state is necessary for the control to function. For example,...
Leon Bambrick (aka SecretGeek) has started a series on Agile methodologies and Test Driven Development (TDD) in which he brings up his own various hidden objections to TDD in order to see if his prejudices can be overcome. One of the questions he asks is an age old argument against TDD. Who Tests the Tests? Leon sees potential for a stack overflow since, given that the tests are code, and that according to TDD, code should be tested, shouldn’t there be tests for the tests? The short answer is that the code tests the tests, and the tests test the...
Forget flame wars. They’re so USENET. The new way of geek fighting is much more subtle. Recently Scott Hanselman wrote a post on the SEO implications of URL standardization which Jeff Atwood followed up with his post on URL Rewriting to prevent Duplicate URLs. Jeff makes it known that he prefers that his blog be referenced with the “www.” in the front. I think that’s an unnecessary three characters that is quite dated. Yes, we know your blog is on the World Wide Web. The World Wide Web is no longer a nice new shiny bauble. You can...
Yesterday I mentioned that Jeff Atwood and Jon Galloway wrote an Identicon implementation for .NET. It works beautifully, but they distributed the code as a Web Site Project, which I cannot deploy to my blog as is.
For those of us who prefer Web Application projects, I repackaged their code as compiled DLL and a handler file. This distribution will work for both Web Application Projects as well as Website Projects.
Just download the binaries, copy the DLL to your bin directory, copy the IdenticonHandler.ashx file to your website directory, and you are good to go. You can simply add an image...
How do you uniquely identify a person, without divulging the identity of that person? For example, given a set of personal artifacts, how would I arrange the set of artifacts grouped by the person to which they belonged?
The answer is quite easy, isn’t it (especially given the title of this blog post and the image to the right)? You can look at the fingerprints on the items.
Unless you happened to have a file that mapped the fingerprints to individuals, you won’t know who the comb and mirror belong to, for example, only that they do belong to the same person and...
Jeremy Miller believes that among the various beneficial and important qualities a codebase can have, the single most important quality of code is maintainability. I totally agree, having spent many hours maintaining legacy code written years ago as well as code I wrote a week ago. As soon as a line of code is typed on the screen, it becomes legacy. You are now maintaining that code. Enterprise software systems change. Business rules change, technology platforms change, third party dependencies are upgraded. ... Enterprise systems typically aren’t replaced because they stop working. The end of life cycle for an...
Here we are already looking ahead to learn about the language features of C# 3.0 and I am still finding new ways to make my code better with good “old fashioned” C# 2.0.
Like many people, I tend to fall into certain habits of writing code. For example, today I was writing a unit test to test the source of a particular event. I wanted to make sure that the event is raised and that the event arguments were set properly. Here’s the test I started off with (some details changed for brevity) which reflects how I would do this in the old days.
private bool eventRaised...
Last night a unit test saved my life (with apologies). Ok, maybe not my life, but the act of writing some unit tests did save me the embarrasment of an obscure bug which was sure to hit when I least expected it. It is cases like this that made me into such a big fan of writing automated unit tests.
Not too long ago I wrote a C# Akismet API for Subtext. In writing the code, I followed design principles focused on making the API as testable as possible. For example, I applied Inversion of Control (IOC) by having the AkismetClient constructor take...
One of the benefits of writing an ASP.NET book is that it forces me to spend a lot of time spelunking deep in the bowels of ASP.NET uncovering all sorts of little gems I never noticed the first time around. Many of these little morsels should end up in the book, but I thought I would blog about a few of them as I go along. This is all part of the weird situation I find myself in while writing this book. I thought I would just sit down and all the words would flow. Instead, no matter how motivated I...
I have a few great openings available that I have to share with you. These are really great positions working with really interesting and smart people all over the world. Some of the outstanding benefits include: Work from home. Work for a great project lead (me!). Work with an international team of really great developers. Work on a product used by thousands of people and seen by many more. Work tasks are pretty much self-directed. Nobody is looking over your shoulder. Set your own schedule and work at your own pace. Interesting cutting-edge ASP.NET...
Jeff Atwood writes a great post about The Last Responsible Moment. Take a second to read it and come back here. I’ll wait. In the comments, someone named Steve makes this comment: This is madness. Today’s minds have been overly affected by short attention span music videos, video games, film edits that skip around every .4 seconds, etc. People are no longer able to focus and hold a thought, hence their "requirements" never settle down, hence "agile development", extreme coding, etc. I wonder what methodology the space shuttle folks use. You shouldn’t humor this stuff, it’s a serious...
UPDATE: I’ve since supplemented this with another approach.
Jeremy Miller asks the question, “How do you organize your NUnit test code?”. My answer? I don’t, I organize my MbUnit test code. Bad jokes aside, I do understand that his question is more focused on the structure of unit testing code and not the structure of any particular unit testing framework. I pretty much follow the same structure that Jeremy does in that I have a test fixture per class (sometimes more than one per class for special cases). I experimented with having a test fixture per method, but gave up on that as it became a maintenance headache. Too...
Keyvan Nayyeri has a great tip for how to control the display of a type in the various debugger windows using a DebuggerTypeProxy attribute. His post includes screenshots with this in use.
This is an attribute you can apply to a class, assembly, or struct to specify another class to examine within a debugger window.
You still get access to the raw view of the original type, just in case some other developer plays a practical joke on you by specifying a DebuggerTypeProxy that displays the value of every field as being 42.
Tags: .NET, C#, Debugging, Visual Studio.NET,
Tips
UPDATE: For a more full featured implementation of this pattern for ASP.NET Web Forms, check out the WebForms MVP project! It’s available as a NuGet package! Install-Package WebFormsMVP
Martin Fowler recently split the Model-View-Presenter pattern into two new patterns, Supervising Controller and Passive View. They are pretty much two different flavors of the MVP pattern differentiated by how much application logic is placed within the view.
The goal of this post is to demonstrate an end-to-end walk-through of the process of implementing the Supervising Controller pattern starting with a rough schematic. My goal is not explain the Supervising Controller pattern in...
Jeff “The CodingHorror” Atwood takes issue with the idea that software developers have any moral obligation to contribute to Open Source projects.
And you know what? I agree. However I do take issue with his conclusion as well as some of the points that he makes in an attempt to bolster his argument.
The whole point of open source-- the reason any open source project exists-- is to save us time. To keep us from rewriting the same software over and over.
snip...
It's exactly what open source is about: maximum benefit, minimum effort.
Well no. Not really. Back in...
Dave Burke makes the interesting claim that Community Server is an open source application. Whether this is true or not of course depends on your definition of the term Open Source. Here is Dave’s definition.
To talk about Community Server and Open Source we should start with a baseline definition of an Open Source application: All of the source code is available. For free.
But is that all there is to Open Source, access to the code? Is mere access to the code the fairy dust that has inspired such a passionate movement in the software community?
Certainly the term...
I am working on some code using the Model View Presenter pattern for an article I am writing. I am using an event based approach based on the work that Fowler did. For the sake of this discussion, here is an example of a simplified view interface.
public interface IView
{
event EventHandler Load;
}
In the spirit of TDD I follow this up with the shell of my Presenter class
public class Presenter
{
public Presenter(IView view)
{
throw new NotImplementedException("Not implemented.");
}
}
And...
Lightbox JS brought a new level of hotness when it came to displaying pictures on your website or blog. Reference the javascript file in your html page, add a rel="lightbox" to a link, and voila! You have a sweet way to display pics. I even implemented it on my blog as evidenced by the image below. Go ahead, click on it (assuming you are not reading this in an aggregator).
Pretty cool eh? Well just as I go and get this implemented, the people that brought you Lightbox JS just released Lightbox JS 2.0. New...
Good news! SourceForge now supports using Subversion for source control!
One complaint I received from developers who read my Quickstart Guide To Open Source Development With CVS and SourceForge is the sheer amount of complexity just to get started (not that it was my fault, I was just the messenger). With Subversion, contributing to a project on SourceForge is now much simpler.
Benefits of Subversion over CVS
Subversion has several key benefits over CVS, a few of which are listed here...
Subversion supports WEBDAV+DeltaV which works over HTTPS so that whole...
I just finished reading the book "Producing Open Source Software - How to Run a Successful Free Software Project" by Karl Fogel (pdf available). CollabNet has employed Karl Fogel for the past five years to work on Subversion. Prior to that he has been involved with GNU Emacs and CVS development.
If you fall in one of the following categories, I highly recommend taking the time to read this book. Especially if you fall in one of the first two.
Planning to start an open source project
Currently running an open source project
Involved with an open source project
Managing a team of...
On a recent project, my team pursued a CSS based design as we had two sites to build that were similar in layout, but different in look and feel. We were brought in after the schematics and design had pretty much been worked out, but we felt we could work with the agreed upon design.
The site had a typical corporate layout: a header, a body, and a footer. The body might have two or three columns.
We started off writing markup that had a structure like so (not including the body columns).
<div id="main">
<div id="header">
</div>
<div id="body">Body</div>
<div...
Wired News has a very interesting article on History’s worst software flaws.
It makes me think of my worst software bug when I first started off as an ASP developer right out of college. I was working on a large music community website and was told to implement a “Forgot Password” feature. Sounds easy enough. I coded it, ran a quick test, and then deployed it (that alone should rankle your feathers).
We didn’t quite have a formal deployment process at the time. A few days later, we find out that the code never sent out any emails, and never...
Perhaps there is a better term I could be using when I referred to “dynamic SQL” in my last post. To my defense, I did mention using Prepared Statements.
The key point to keep in mind while reading the last post is that Dynamic SQL does not necessarily imply Inline SQL. By inline SQL, I mean concatenated sql statements flung all over the code like a first year classic ASP developer.
Like any good security minded developer, I detest inline SQL (as I define it here). A much better and safer approach is to use prepared parameterized SQL as Jeff...
Found this post in RossCode which mentions a blog post that discusses how to bind enumerations to drop downs, something I’ve done quite often. RossCode has an issue with using this approach personally because typically, the display text of a drop down should have spaces between words, which is not allowed in an enum value. For example... public enum UglinessFactor {
ButtUgly,
Fugly,
NotSoBad,
}
In the preceding enumeration, you’d probably want the dropdown to display “Butt Ugly” and not...
Many developers, especially those fresh out of college (though older developers are just as prone), fall into the trap of believing in an absolute concept of “the perfect design”. I hate to break such youthful idealism, but there’s just no such thing.
Design is always a series of trade-offs in an arduous struggle to implement the best solution given a set of competing constraints. And there are always constraints.
Not too long ago, I had an interesting discussion with a young developer who was unhappy with the design of a project he was working on. This project had a very...
I'm posting this in the hopes that it helps someone out there with the same problem because I just KNOW how often you're adding files using CVS. It's the little spark that gets your juices flowing while sitting at work daydreaming about how much you can't wait to use CVS again.
Anyways, I was creating a new CVS module and adding the contents of some source code to the repository when I heard the sound of breaking glass that TortoiseCVS uses to indicate a problem (it's a rather lovely sound).
It seems I had some sort of network issue while adding...
I put up an HTML version of my resume on my blog. It has a slight bit more information than my Word resume which I think lends well to the online experience. For a moment I thought about using the Marquee and Blink tags all over and have animated dancing babies, but I don't have the design skills to do that tastefully. I even forgoed adding Google and Amazon ads all over.
Since I'm now an independent consultant, I think it's a good idea to have that sucker online, though I think my blog posts will give the potential...
As part of my site's redesign, I wanted to keep the drop shadow effect on the left and right borders of my main content area. No problem I naively thought, I'll simply add two background elements to the main div. I named the div "background" like so:
<div id="background">
</div>
And in my style sheet, I tried the following:
#background
{
background: url(leftBorder.gif) repeat-y left;
background: url(rightBorder.gif) repeat-y right;
}
Unfortunately this did not work as only one of the background images showed up. What I ended up resorting to was using two nested divs. The inner...
Saw this post on Consult Utah's Weblog...
Is anyone else getting tired of writting:...
private bool _autoAccept;
...
public bool AutoAccept
{
get {return _autoAccept;}
set {_autoAccept = value;}
}
I've pretty much decided that it is just preferable in these cases to just make the member variable public. I'm am being bad? ;-)
My answer? I think he should be publicly flogged, smeared with tar and feather, and paraded around town in a pink tutu.
Ok, that might be a bit extreme. I don't really believe that.
I think using a public field is fine in some cases. If the interface...
There's a debate going on about how effective the rel="nofollow" solution really is. Some believe that Google is flattering itself by thinking that the primary motivation for comment spam is Google juice.
I do not believe that rel="nofollow" will stop comment spam as I've stated before (though I've applied it myself). Getting their links out there may be motivation enough. However I think it will have a bigger impact than some people think.
In terms of sheer economies of scale, I don't think comment spam is like regular email spam. Sending an email to millions of users is very easy...
Although I agree in spirit with most of Joel’s discussion of methodologies and rock star programmers, I’m in a bit of disagreement over the quote from Tamir he posts.
For instance, in software development, we like to have people unit-test their code. However, a good, experienced developer is about 100 times less likely to write bugs that will be uncovered during unit tests than a beginner. It is therefore practically useless for the former to write these...
I disagree with this, but in part because I think this is based on a flawed assumption over the purpose of unit testing....
This is a fabulous post (did I just say "fabulous"?) on how to create self contained NUnit tests when you need a web server.
As you may know (assuming you've read this blog for a while, which is a BIG assumption), I'm a big fan of self contained Unit Tests. It's a key component to having a self contained location independent build process.
I have an approach similar to Scott's in unit testing some of the functionality of RSS Bandit. For example, I have tests that will create a web directory, start a Cassini web server, and then use the...
One of the holy grails for unit testing is to get 100% code coverage from your tests. However, you can’t sit back and smoke a cigar when you reach that point and assume your code is invulnerable. Code coverage just is not enough.
One obvious reason is that Code Coverage cannot help you find errors of omission. That is, even if you had 100% code coverage from your tests, if you forget to implement a feature (and a test for that feature), then you’re shit out of luck.
However, apart from errors of omission, there’s the case presented here. Imagine...
There’s a lot of focus these days on SOAP vs REST and the proliferation of WS-* specifications. Sometimes you wonder if WS-* solves problems that aren't all that common or have already been solved.
For example, some in the REST camp will say, HTTP has security built in. It#8217;s called SSL. Why not use it instead of building WS-Security.
Another example is WS-Addressing. This places addressing information within the SOAP envelope so that the message can be delivered via transports other than HTTP. At first glance, I wonder how often this will be useful for web services when HTTP is the...
Jonathan de Halleux, aka Peli, never ceases to impress me with his innovations within MbUnit. In case you're not familiar with MbUnit, it's a unit testing framework similar to NUnit.
The difference is that while NUnit seems to have stagnated, Jonathan is constantly innovating new features, test fixtures, etc... for a complete unit testing solution. In fact, he's even made it so that you can run your NUnit tests within MbUnit without a recompile.
His latest feature is not necessarily a mind blower, but it's definitely will save me a lot of time writing the same type of code over...
By now you probably think I have an unhealthy obsession over the TimedLock struct. Well, you're right. I think it's emblematic of the right way to do things and shows that the right way isn't always the easiest way.
In Ian's last post on the TimedLock, he talked a bit about the performance considerations with my solution to keeping track of stack traces in a multi-threaded situation. To sum, my solution is pokey in certain situations. As always, measure measure measure.
However, Ian mentioned a solution outlined by Marek Malowidzki that avoids creating a stack trace on every lock acquisition....
When conducting phone interviews, I like to ask a few technical questions just to make sure that a candidate isn’t trying to blow smoke up my... well we don’t need to be overly illustrative do we?
I absolutely do not intend the questions to be nitpicky. Nor do I feel they are totally representative of an interviewee’s depth of knowledge. I save the probing questions for an in-person interview.
However, if a candidate claims to have one or two years experience working with ASP.NET, there are some basic facts and principles that a mid-level developer should know.
For example, please compare...
I’m not proud of it (well maybe just a little), but I once created an insane build process once. If Pat (who maintained the build after me) posts in my comments, he’ll tell you about it. Take a stew of a proprietary microcomputer flavor of Fortran written in the 70s by a programmer most assuredly clad in polyester, churn it through a Visual Basic 6.0 preprocessor that spits out Fortran 90 code, all the while correcting memory bound issues, mix it together by compiling it with a custom NAnt fortran compiler task, and voila!, 20 or so compiled Win32 fortran...
Now I've never been a consultant myself, but I have friends who have been consultants. Namely Kyle. What do you think of these rules?
[Via DonXML Demsak's Grok This]
You work for the client, not the consulting firm. No matter who cuts the payroll check, the client is the one paying for your services. Do the right thing for the client, not the consulting firm (or anyone else).
Your network of consultants is your most important asset.
Consultants should keep a blacklist of firms and other consultants that should be avoided, and why. Share this list with your network of...
Ian Griffiths finds a niggle about my post on sockets.
This may surprise a few friends of mine who regard me as a "human dictionary", but I had to look up the word "niggle". Apparently only the "human" part of the appellation applies. I've apparently fooled them by reading a lot of sci-fi fantasy and choosing to learn and use "impressive" words such as Bacchanalian in everyday conversation ("I wrote this code in a drunken stupor from a bacchanalian display of excessive beer drinking."). It's really all smoke and mirrors. But I digress...
His comment is quite insightful and well worth repeating...
In this post, Tim Ewald talks about using Doc/Literal/Bare for your web service. There are several benefits he ticks off, but one seems to be the aesthetic effect of cleaning up the format of the XML within your SOAP message. In SOAP, the XML sent back and forth is just the wire format. As a typical developer, why should you care what the wire format is? In general, you shouldn't. If you have the tools to generate WSDL and generate a proxy off of a WSDL to call a web service, you're all set.
Unfortunately...
Google apparently is behind this mysterious billboard that presents a nice number theory problem. I love number theory!
Of course, I could have written a program to sift through the digits of e to find the answer to this question, but I’m a pragmatic soul and figure why not just use Google since it’s 3 AM and I’m tired (I know, it’s cheating, but how good Google fault you for using Google?) The answer to this problem is also a website (7427466391) which presents a more challenging problem.
Congratulations. You've made it to level 2. Go to www.Linux.org and enter Bobsyouruncle...
You've probably heard the term Impedance Mismatch thrown around when discussing object relational mapping. I'm sure it comes up every morning at the water cooler. Maybe you've even thrown it around yoursef a few times. Do you know what the term means?
Object relational mapping refers to the process of mapping your relational data model to your object model. Object Spaces is a highly publicized framework for doing just that. The mismatch I refer to is a result of the differences in structure between a normalized relational database and a typical object oriented class hierarchy. One might say Databases are from...
UPDATE: I finally followed up with part 2, only 8 years later.
When you ask the average programmer what problems plague the practice of building software, you’ll probably hear responses such as: The impedance mismatch between relational databases and object oriented code. The difficulty of writing secure code. Managing complexity and requirement changes.. Certainly, these are all worthy problems to tackle, but the problem that comes to my mind is how much pain I’m in when I write code and how few people really understand this. I hope to write a series of articles about typing pain...
Test First Development, the process of writing unit tests to test the code you are about to write, is one of my favorite software practices that has an impact on producing better written code. However, it's no a panacea. It is true that I use the debugger much less often because of TDD, but there are still occasions where it's important to manually step through code line by line.
Personally, I use NCover as my first line of defense. It highlights the lines of code that haven't been executed by my unit tests. A lot of...
Apparently I’m not the only one to run into this annoying problem. When using the HttpWebRequest to POST form data using HTTP 1.1, it ALWAYS adds the following HTTP header "Expect: 100-Continue". Fixing the problem has proved to be quite elusive.
According to the HTTP 1.1 protocol, when this header is sent, the form data is not sent with the initial request. Instead, this header is sent to the web server which responds with 100 (Continue) if implemented correctly. However, not all web servers handle this correctly, including the server to which I am attempting to post data. I sniffed the...
Wow! After posting my update to the TimedLock class entitled TimedLock Yet Again Revisited..., Ian Griffiths posts this gem which outlines a solution to one of the problem's with my approach to keeping a stack trace.
The problem is that my code acquires a stack trace every time it acquires a lock just in case another thread fails to acquire a lock. The purpose of this action is so that we can examine the stack trace of the blocking thread to find out why we couldn't acquire a lock. This can be a big performance cost in some situations.
Ian received...
In an earlier post, I updated the TimedLock class (first introduced in this post) to allow the user to examine the stack trace of the thread that is holding the lock to an object when the TimedLock fails to obtain a lock on that object. This assumes that the blocking lock was obtained using the TimedLock. Ian Griffiths pointed out a few flaws in my implementation and I promised I would incorporate his feedback and revise the code.
Since that time, Ian revisited the TimedLock based on comments he recevied and changed it to be a struct in both...
In an earlier blog entry, I asked the question if it made sense to add code in a debug version of the TimedLock class (written by Ian Griffiths in this post and commented on by Eric Gunnerson in this post) to store the stack trace when acquiring a lock on an object so that if another thread blocks an attempt to acquire a TimedLock, we can discover the StackTrace of the blocking thread.
Well I stopped asking questions and started writing answers. I update the TimedLock class with stack trace tracking and also wrote an NUnit test that demonstrates the...
Found this on Eric Gunnerson's (PM for the C# compliler team) blog. It's an interesting approach to get a lock statement with a time out. It would be nice to perhaps add a timeout syntax to the lock statement in C#. Maybe it would look like this:
object obj = new object();
int milliseconds = 10000;
try
{
lock(obj, milliseconds)
{
//Do something with obj
}
}
catch(LockTimeOutException exception)
{
//Handle exception
}
One thought I had, and let me know if I'm off base, but it seems we could add debug code to Ian...
In general, cursors suck ass! Ok, that’s a bit extreme, but I have a long and ugly history with cursors. Let me diverge here and tell you a true story.
A while ago, a friend of mine recommended me to a company in serious need of senior developers for full-time or contract work. After talking to the dev manager over the phone, he felt my rate was too high, but wanted me to come in anyways. He set his top three developers in the room with me and left as they began to drill me with technical questions.
Now, I don’t...
I needed to create a temp table in SQL with a column that contained an incrementing integer, without making that column an identity.
For example, suppose I want to select record from a table of users, but add a column that contains an incrementing counter. The data in the table should look like so:
counter
UserID
...
I'm working with a third party component (I will not name the guilty party) that has a method with the following signature and implementation (with no overrides):
public void doSomething(DataTable table){ for(int i = 0; i < table.Rows.Count; i++) { DataRow row = table.Rows[i]; //Do Something with row... } }
What is the problem with this method?
In my opinion, it is an example of poor class design. Suppose the user of this class wanted to have the component process the rows of the DataTable in a particular order. How would one accomplish that?
If you take a look at the...