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

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 new language features of C# to improve my tests.

For example, the MVC framework will include interfaces for the ASP.NET intrinsics. So to mock up the HTTP context using Rhino Mocks, you might do the following.

MockRepository mocks = new MockRepository();
      
IHttpContext context = mocks.DynamicMock<IHttpContext>();
IHttpRequest request = mocks.DynamicMock<IHttpRequest>();
IHttpResponse response = mocks.DynamicMock<IHttpResponse>();
IHttpServerUtility server = mocks.DynamicMock<IHttpServerUtility>();
IHttpSessionState session = mocks.DynamicMock<IHttpSessionState>();

SetupResult.For(context.Request).Return(request);
SetupResult.For(context.Response).Return(response);
SetupResult.For(context.Server).Return(server);
SetupResult.For(context.Session).Return(session);

mocks.ReplayAll();
//Ready to use the mock now

Kind of a mouthful, no?

Then it occurred to me. I should use C# 3.0 Extension Methods to create a mini DSL (to abuse the term) for building HTTP mock objects. First, I wrote a simple proof of concept class with extension methods.

public static class MvcMockHelpers
{
  public static IHttpContext 
    DynamicIHttpContext(this MockRepository mocks)
  {
    IHttpContext context = mocks.DynamicMock<IHttpContext>();
    IHttpRequest request = mocks.DynamicMock<IHttpRequest>();
    IHttpResponse response = mocks.DynamicMock<IHttpResponse>();
    IHttpSessionState session = mocks.DynamicMock<IHttpSessionState>();
    IHttpServerUtility server = mocks.DynamicMock<IHttpServerUtility>();

    SetupResult.For(context.Request).Return(request);
    SetupResult.For(context.Response).Return(response);
    SetupResult.For(context.Session).Return(session);
    SetupResult.For(context.Server).Return(server);

    mocks.Replay(context);
    return context;
  }

  public static void SetFakeHttpMethod(
    this IHttpRequest request, string httpMethod)
  { 
    SetupResult.For(request.HttpMethod).Return(httpMethod);
  }
}

And then I rewrote the setup part for the test (the rest of the test is omitted for brevity).

MockRepository mocks = new MockRepository();
IHttpContext context = mocks.DynamicIHttpContext();
context.Request.SetFakeHttpMethod("GET");
mocks.ReplayAll();

That’s much cleaner, isn’t it?

Please note that I call the Replay method on the IHttpContext mock. That means you won’t be able to setup any more expectations on the context. But in most cases, you won’t need to.

This is just a proof-of-concept, but I could potentially add a bunch of SetFakeXYZ extension methods on the various intrinsics to make setting up expectations and results much easier. I chose the pattern of using the SetFake prefix to help differentiate these test helper methods.

Note that this technique isn’t specific to ASP.NET MVC. As you start to build apps with #C 3.0, you can build extensions for commonly used mocks to make it easier to write unit tests with mocked objects. That takes a lot of the drudgery out of setting up a mocked object.

Oh, and if you’re lamenting the fact that you’re writing ASP.NET 2.0 apps that don’t have interfaces for the HTTP intrinsics, you should read my post on IHttpContext and Duck Typing in which I provide such interfaces.

Happy testing to you!

I have a follow-up post on testing routes. The project includes a slightly more full featured version of the MvcMockHelpers class.

Tags: ASP.NET MVC , TDD, Rhino Mocks

comments suggest edit

Recently I gave out a few free copies of a book I co-wrote, but ran out quickly. This is the same book that Jeff Atwood (a co-author) told everyone, Do Not Buy This Book.

Well, if you didn’t get a copy, there is another opportunity to get a free copy. DotNetSlackers is running a contest and will reward the top 3 contributors to their forums (ooh, that could get…interesting. First Post!orI Agree!Count it up.) with great prizes.

ASP.NET 2.0
Anthology Unfortunately, our book is part of a second prize package which includes ANTS Profiler Pro. Our book is also the third-prize.

Why is that unfortunate?

XBox 360
Elite Because if you want a free copy of our book, you have to try real hard not to do too well that you win first prize, which is an XBox 360 Elite along with Telerik RadControls. Once you got your hands on Halo 3 or Gears of War, you’d have no time to read our book! And you wouldn’t want that, would you?

In any case, for more contest details, check out the contest page.

Tags: Contest , Book

code comments suggest edit

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 project.

Another useful library you might find useful in Subtext is our SQL Script execution library encapsulated in the Subtext.Scripting.dll assembly.

A loooong time ago, Jon Galloway wrote a post entitled Handling GO Separators in SQL Scripts - the easy way that tackled the subject of executing SQL Scripts that contain GO separators using SQL Server Management Objects (SMO). SMO handles GO separators, but it doesn’t (AFAIK) handle SQL template parameters.

So rather than go the easy way, we went the hard way and wrote our own library for parsing and executing SQL scripts that contain GO separators (much harder than it sounds) and template parameters. Here’s a code sample that demonstrates the usage.

string script = @"SELECT * FROM <table1, nvarchar(256), Products>
GO
SELECT * FROM <table2, nvarchar(256), Users>";

SqlScriptRunner runner = new SqlScriptRunner(script);
runner.TemplateParameters["table1"] = "Post";
runner.TemplateParameters["table2"] = "Comment";

using(SqlConnection conn = new SqlConnection(connectionString))
{
  conn.Open();
  using(SqlTransaction transaction = conn.BeginTransaction())
  {
    runner.Execute(transaction);
    transaction.Commit();
  }
}            

The above code uses the SqlScriptRunner class to parse the script into its constituent scripts (you can access them via a ScriptCollection property) and then sets the value of two template parameters before executing all of the constituent scripts within a transaction.

Currently, the class only has one Execute method which takes in a SqlTransaction instance. This is slightly cumbersome and it would be nice to have a version that didn’t need all this setup, but this was all we needed for Subtext.

When I started writing this post, I thought about making some overrides that would make this class even easier to use, but instead, I will provide a copy of the assembly and point people to our Subversion repository and hope that someone out there will find this useful and have enough incentive to submit improvements!

Also, be sure to check out our unit tests for this class to understand what I mean when I said it was harder than it look. As a hint, think about dealing with GO statements in comments and quotes. Also, GO doesn’t have to be the only thing on the line. Certain specific elements can come before or after a GO statement on a line.

In case you missed the link, DOWNLOAD IT HERE.

Tags: Subtext , SQL , Sql Script Runner

comments suggest edit

A while back, Jon Galloway asked the question, Can Operating Systems tell if they’re running in a Virtual Machine? What a silly question! When was the last time an Operating System questioned its own existence? Is that going to be in the next version of Windows - Windows Vista Into Its Own Soul? Or perhaps Apple will come out with Mac OS Existentialist?

Perhaps a more interesting question is whether or not you can tell that a web server is running in a virtual machine? Last weekend I migrated my blog into a virtual server running on a pretty sweet host machine and so far, my site seems to have gained an extra spring in its step.

Given that it’s hosted on the same server as that bandwidth hog, CodingHorror.com, I’m very pleased with the performance thus far. At least until he gets Dugged again.

In Jeff’s post, he mentioned that CrystalTech hooked us up with a beefy 64-bit dedicated server. Several commenters noted that there was no 64-bit offering on their site. The reason is that they hadn’t received much demand for 64-bit servers until we came along with our bullying tactics.

Dedicated Dual & Quad
Core Through a contact over there, I wanted to see if we could work out a hosting deal. Jeff was adamant that we get a 64-bit server, which they didn’t have at the time, but could certainly order. I pretty much didn’t want them to go through all that trouble and was ready to move on, but they insisted it was not a big deal.

They lied…er…understated their case. Rather than simply build a single 64-bit server, they took this as an opportunity to build out a whole new product offering of 64 bit dedicated servers.

So what started off as me trying to scam some discounted or free hosting ended up spurring these guys to start a new product offering. Nice!

I’m now hosting this site and SubtextProject.com on this box, but our CCNET server is still in a virtual machine hosted generously by Eric Kemp of Subsonic fame.

I used to be skeptical of hosting my site in a virtual machine, as I felt like if I hosted closer to the metal, I could wring out extra performance. But let’s get real here, I’m not taxing this machine in any way.

I’m sold on the benefits and convenience of virtualization.

Tags: CrystalTech , Hosting , Virtual Machine

comments suggest edit

From Monday night to Thursday afternoon next week I will be in Las Vegas attending both DevConnections/ASPConnections as well as the DotNetNuke OpenForce conference. After that, I will be up in Redmond for the next week.

I wrote before that I would be speaking on a couple panels at OpenForce conference talking about open source and .NET.

If you’re interested, the panels will be:

Wednesday, Nov 7 - 8:00 AM - 9:15 AM Lagoon L

DOS101: Panel Discussion: Open Source on the Microsoft \ Technology Stack\ Scott Guthrie, Phil Haack, Rob Conery and Shaun Walker

Thursday, Nov 8 - 9:30 AM - 10:45 AM Lagoon F

DOS102: Panel Discussion: .NET Open Source Architectural Models \ Joe Brinkman, Phil Haack, Jay Flowers, Jon Galloway and Rob Conery

It’s unfortunate that the first panel is at 8:00 AM because I never really sleep much at all when I’m in Vegas. I pretty much have too much fun (unless I’m losing bad). So if you run into me, I apologize in advance for the fool I make of myself. ;)

Another talk you’ll not want to miss is the MVC talk given by Scott Hanselman and Eilon Lipton.

Tuesday, Nov 6 - 2:30 PM - 3:30 PM Room 2

AMS304: Introduction to the new ASP.NET Model View Controller (MVC) Framework

Scott Hanselman, Eilon Lipton

I’ll definitely be at this talk. These two are giving a couple of talks together you can read about on Scott’s post. Come by and say hi.

Tags: Microsoft , DevConnections , AspConnections , OpenForce , Conference

comments suggest edit

Pop quiz for you C# developers out there. Will the following code compile?

//In Foo.dll
public class Kitty
{
  protected internal virtual void MakeSomeNoise()
  {
    Console.WriteLine("I'm in ur serverz fixing things...");
  }
}

//In Bar.dll
public class Lion : Kitty
{
  protected override void MakeSomeNoise()
  {
    Console.WriteLine("LOL!");
  }
}

If you had asked me that yesterday, I would have said hell no. You can’t override an internal method in another assembly.

Of course, I would have been WRONG!

Well the truth of the matter is, I was wrong. This came up in an internal discussion in which I was unfairly complaining that certain methods I needed to override were internal. In fact, they were protected internal. Doesn’t that mean that the method is both protected and internal?

Had I simply tried to override them, I would have learned that my assumption was wrong. For the record…

protected internal means protected OR internal

It’s very clear when you think of the keywords as the union of accessibility rather than the intersection. Thus protected internal means the method is accessible by anything that can access the protected method UNION with anything that can access the internal method.

A Donkey Named Lester - Creative Commons By Attribution -
ninjapoodlesAs the old saying goes, when you assume, you make an ass out of u and me. I never understood this saying because when I assume, I only make an ass of me. I really think the word should simply be assme. As in… 

Never assme something won’t work without at least trying it.

UPDATE: Eilon, sent me an email to point out that…

BTW the CLR does have the notion of ProtectedANDInternal, but C# has no syntax to specify it. If you look at the CLR’s System.Reflection.MethodAttributes enum you’ll see both FamANDAssem as well as FamORAssem (“Family” is the CLR’s term for C#’s protected and “Assem” is C#’s internal).

If you don’t know Eilon, he’s a freaking sharp developer I get to work with on the MVC project and was the one who kindly disabused me of my ignorance on this subject. He keeps a blog at http://weblogs.asp.net/leftslipper/.

Apparently he’s the one with the clever idea of using a C# 3.0 anonymous type as a dictionary, that many of you saw in ScottGu’s ALT.NET Conference talk. Very cool.

subtext comments suggest edit

MySpace China
LogoAn undisclosed source informed me that MySpace China is using a modified version of Subtext for its blogging engine.

I had to check it out for myself to confirm it and it is true! Check out my first MySpace China blog post. How do I know for a fact that this is running on Subtext? I just viewed source and saw this little bit of javascript…

var subtextBlogInfo = new blogInfo('/', '/1304049400/');

So if anyone is wondering if Subtext can scale, it sure can. MySpace China gets around 100 million page views, approximately a million of which go to the blog.

My source tells me the MySpace China developers found some bugs with Subtext they had to fix that were only exposed when they put a huge load on it. Although they are under no requirements to do so under our license, I hope that they would contribute those fixes as patches back to Subtext.

So to all you Chinese users of Subtext (via MySpace China), 你好 to you.

Technorati Tags: Subtext , MySpace China

comments suggest edit

Like a lovesick puppy, my good friend Rob Conery is following me to Microsoft.

I’m excited (not yet super excited) that Rob is going to be joining us working on Subsonic as the sugar on top of the work we’re doing with the MVC framework. Good times! We’re definitely going to have to celebrate in Vegas at the DotNetNuke conference and DevConnections (you all will be there, won’t you?)

This is perhaps another item to add to the list I made of signs of progress in regards to how Microsoft is approaching Open Source.

Rob, be sure to read Dan Fernandez’s post on the stages of new employees at Microsoft employee.

I really think our first order of business is to build a sample MVC application using LOLCode.NET. Until your framework supports LOLCode, nobody takes you seriously.

Technorati Tags: Microsoft , Rob Conery

comments suggest edit

For those starting out at Microsoft, an analogy that you’re likely to hear a lot is “Drinking from the firehose”. The first time I’ve ever heard this phrase was when Dare used it in a post about the flood of information due to subscribing to multiple RSS feeds.

Bronx Summer. Photographer,
unknown.

It’s entirely apropos (just love that word ever since The Matrix) as a description of starting as a new employee at Microsoft. My buddy Walter said his brother had the same feeling when starting at CalTech. That resonates with me, because unlike my college, with its emphasis on the liberal arts, Microsoft very much feels like an engineering college.

For example, everyone around me is technically adept and incredibly smart. It’s funny to hear myself say that. Over the past few years, I’ve read many blog posts from people I highly respect, real brainiacs in the industry, talk about their transition to Microsoft and they would often say something similar. Something along the lines of…

“I’m surrounded by really really smart people.”

“Everyone here is super smart” Note, they like to use “super” as a prefacing adjective a lot around here. Especially the phrases “Super Smart” or “Super Excited” 

“I feel humbled by the smart people around me.”

I used to read these statements and think to myself, Bullshit! You’re freakin’Don Box! OrChris Sells! OrScott Hanselman! OrJohn Lam! (I could go on…) I know you’re just saying that to be nice. I mean, how could you really say otherwise since you have to work with them?

Sure I bet these people are smart, and many of them might even be scary smart, but you know you’re a big dog over there. Admit it. Go ahead, admit it.

Ahhhh yes, the ignorant arrogance of an outsider. Now here I find myself saying the same things these guys have said, though admittedly, the bar is lower in my case than the aforementioned highly respected gentlemen.

I’m sure there must be some stupid people around here somewhere. They’re just not in my group as far as I can tell.

Investing for the long run

I had a great meeting with my manager on my third day of work. Rather than focusing on technology, tasks, and features, we spent a couple hours talking about passion, personal mission, goals, long term outlook, etc… And not the typical bullcrap I can regurgitate in an interview (whoops!). I was forced to really think deeply about these issues, about what I really want out of a career, which is quite frankly something I haven’t done in a long time. I’ve been too busy doing and not spending any time pondering. It is really important to have a balance of both.

In part, I think this is a reflection of a company that can afford to invest in the long run and be strategic, rather than always investing in the short term and feeling like a chicken with its head cut off. It is a refreshing change of pace.

But don’t confuse that with a slow pace, it was crazy busy over here last week. Right off the bat I was put to work on preparing materials for a private Software Design Review (SDR) we had with select customers and partners, which kept me busy over the weekend. The great part of course is that I’m pretty much in control over my own schedule for the most part, as long as I’m producing results.

You Sound Like You Totally Drank The Kool-Aid?

It may seem like I have completely drunk the kool-aid, but I like to think that I held it in my cheek waiting for a moment when nobody was looking to spit it out. Besides, the kool-aid would be extremely diluted from the fire hose.

The phrase drinking the kool-aid”** implies a cult or herd mentality, which is something I hope to avoid. In fact, it makes me a more valuable employee if I can keep some of my naive outsider thinking intact, though perhaps over time, I will be super assimilated (doh!).

I think my enthusiasm for my work has a lot to do with the particular group I am in and the particular project I am on. I know there are some people very dissatisfied at Microsoft, so it’s not all roses and ice cream.

I have also heard second-hand comments that show that some people here still have misconceptions about Open Source. Not a willful antagonism, just a misunderstanding, which is easily remedied via education.

This post has gone on long enough. If people are interested, I’d be happy to write more about my experiences and impressions of Microsoft as things progress.

The main thing I want to say is that I still plan to work on Subtext, though my involvement will be scant in the near term. I also still plan to continue blogging and not drop off the face of the blogodome as some have feared.

Technorati Tags: Microsoft

comments suggest edit

If you live in the Seattle area and like code, talking about code, or listening to people talk about code, you owe it to yourself to check out the Seattle Code Camp.

  • WHO: You and a bunch of other code junkies
  • WHAT: Code Camp Seattle!
  • WHEN: November 17, 18 (Sat and Sun) 2007
  • WHERE: DigiPen Institute of Technology, Redmond, WA
  • WHY: Did you not see the first paragraph of this post?
  • HOW: I leave that up to you, but consider car pooling.

Sadly, I won’t be able to make this one since I still live in Los Angeles, but Jason Haley and others will be there. So at the very least, make nice with Jason, get on his Interesting Finds list, and get your blog some exposure.

Check out the website for more information and a brief FAQ on the code camp ethos.

comments suggest edit

Many of you noticed that my blog was down. Thanks for the heads up. For some reason, it was pegging the CPU at 100% all of a sudden. Not sure why this was happening since nobody made any changes to the server. At least no changes they would fess up to ;).

I migrated the blog to a dedicated server courtesy of Rob Conery and still had the problem. Migrating allowed me to narrow down the problem without affecting anyone else’s site.

After much trial and error, I narrowed it down to the Recent Comments and Recent Posts controls in the footer of my skin. If you scroll down, you’ll see I’ve removed them.

So again, thanks for those who pointed it out and sorry to anyone who was inconvenienced (like me!) looking for information etc….

comments suggest edit

UPDATE: We decided on the Three Lions Pub in Redmond at 7:30 PM

beer-and-dinner I’m going to be in Redmond next week and would love to get a geek dinner together around 7:30 PM. My flight gets in at 5:18 PM so I hope that’s doable. Anybody interested in joining us?

I think Scott Hanselman, Brad Wilson, Scott Koon, and Scott Densmore will grace us with their presence. If you’re interested in showing up, post a comment so we get a rough idea of numbers.

Topic for discussion, Forget Separation of Concerns, what does MS Dev Div have against Spaghetti Code? I like spaghetti!

Another potential topic of discussion, Render on POST - A fool’s http response or a pragmatic approach? Choose a side and let the all-out bare knuckle bloody brawl begin.

Final topic, if you believe GET is the one true way to render and prefer redirect on POST, which one do you choose? 302 or 303?

comments suggest edit

Here’s the dirty little secret about being a software developer. No matter how good the code you write is, it’s crap to another developer.

It doesn’t matter if the code is so clean you could eat sushi off of it. Doesn’t matter if both John Carmack and Linus Torvalds bow down in respect every time the code is shown on the screen. Some developer out there will call it crap, and it’s usually the developer who inherits the code when you leave.

The reasons are many and petty:

  • Your code uses string concatenation in that one method rather than using a StringBuilder. So what if in this one situation, that was a conscious decision because on average that method only concatenates three or four strings together. The next guy doesn’t care.
  • You put your curly braces on the same line rather than its own line as God intended (or vice versa).
  • You used a switch statement when everyone (including the next developer) knows you’re supposed to replace that with the State or Strategy pattern, always! Didn’t you read Design Patterns? Never mind the fact that there’s only one switch statement and thus no code duplication.
  • You’re using Spring.NET for dependency injection, but the next guy loves Windsor. Only idiots choose Spring.NET (or vice versa, again).
  • Or perhaps you used dependency injection at all. What the hell is dependency injection? I don’t understand the code now! :(

While we strive for perfect code, it is unattainable on real projects because real code is weighed down by the pressure of constraints such as time pressure. Unfortunately, these constraints aren’t reflected in the code, just the effect of the constraints. The next developer reading your code didn’t know that code was written with one hour left to deliver the project.

Although I admit, having been burned by misguided criticism before, it’s hard not to be tempted to take a pre-emptive strike at criticism by trying to embed the constraints in the code via comments.

For example,

public void SomeMethod()
{
  /*
  At most, there will only be 4 to 5 foos, so string concatenation 
  is just fine in this situation. Here are links to five blog posts that 
  talk about the perf implications. Give me a break, it’s 
  3 AM, I’m hopped up on Jolt, this project is 3 months
  late, and I have no social life anymore. Cut me some slack!
  ...
  */
  string result = string.Empty;
  foreach(Foo foo in Foos)
  {
    result += foo;
  }
  return result;
}

Seems awful defensive, no? There’s nothing wrong with leaving a comment to highlight why a particular non-obvious design decision is made. In fact, that’s exactly what comments are for, rather than simply reiterating what the code does.

The problem though, is that developers sometimes cut each other so little slack, you start writing a treatise in green (or whichever color you have comments set to in your IDE) to justify every line of code because you have no idea what is going to be obvious to the next developer.

That’s why I was particularly pleased to receive an email the other day from a developer who inherited some code I wrote and said that the solutions were, and I quote, “really well written”.

Seriously? Am I being Punk’d? Ashton, where the hell are you hiding?

This is quite possibly the highest compliment you can receive from another developer. And I don’t think it’s because I’m such a great developer. I really think the person who deserves credit here is the one giving the compliment.

I mean, my reaction when I’ve inherited code was typically, why the hell did they write this this way!? Did they learn to code from the back of a Cracker Jack Box!? Who better to serve as the scapegoat than the developer who just left?

Fortunately I had enough tact to keep those thoughts to myself. In the future, I’ll work harder on the empathy side of things. When I inherit code, I’ll assume the developer wrote it in a 72 hour straight coding binge, his World of Warcraft character held hostage, bees all over his body, with only an hour to finish the code on a 386 before everything really starts to go south.

Given those circumstances, it’s no wonder the idiot didn’t use a using block around that IDisposable instance.

comments suggest edit

In his post Goodby CodeBetter and ALT.NET, Sam Gentile writes about his dissatisfaction with CodeBetter and the ALT.NET movement. I don’t know Sam personally, but I’ve read his blog for a long time and know him to be a well reasoned thoughtful person.

Sam, please don’t throw out the baby with the bathwater, to use an old cliche. I don’t think it’s necessary to equate CodeBetter with ALT.NET. Perhaps CodeBetter bloggers are very influential in the ALT.NET circles, but it’s important for ALT.NET to stand separately and on its own.

Sam mentions that ALT.NET is divisive.

ALT.NET is a divisive thing. No matter what they tell you, they are full of negative energy, they sneer at others that don’t buy into their view and sneer at the “enterprisey” folks. I know, I was there.

I think the divisive label can also be applied to the Agile Movement, which Sam was a part of. It divides people into two camps, those who agree and those who don’t. It’s divisive because it makes a stand, but hopefully without all the sneering and negative energy.

ALT.NET should be about considering alternatives, not being contrarian.

A lot of fuss has been made about the ALT.NET label on this particular movement. Personally, I think it’s darn near impossible to change the name of a movement once it sticks. The real work is in putting the meaning into the label so it reflects something positive.

For example, I don’t see ALT.NET as saying, “you must use alternatives to Microsoft technologies in all cases”. Otherwise the ALT.NET movement would really be the Ruby, Erlang, Python, Haskell, Java movement. ALT.NET is not about simply being contrarian.

I think the movement is really about opening people’s eyes to always be learning and considering better ALTernatives to the tools, methods, and practices they use now. As Dave Laribee wrote in his ALT.NET post

What does it mean to be to be ALT.NET? In short it signifies:

  • You’re the type of developer who uses what works while keeping an eye out for a better way.\
  • You reach outside the mainstream to adopt the best of any community: Open Source, Agile, Java, Ruby, etc.\
  • You’re not content with the status quo. Things can always be better expressed, more elegant and simple, more mutable, higher quality, etc.\
  • You know tools are great, but they only take you so far. It’s the principles and knowledge that really matter. The best tools are those that embed the knowledge and encourage the principles (e.g. Resharper.)

These are all noble goals.

In his Goodbye post, Same relents about his ALT.NET involvement.

Now, onto this whole ALT.NET thing. When I was in the weeds at Algo, coding away, I too got caught up in the low-level issues and put out a stupid ALT.NET Moniker and List. I took a ton of crap on this from my friends all over the world, both inside and outside Microsoft. It wasn’t about disagreement, it was just blindly putting a list that was stupid, cross out everything Microsoft in one column and replace it with something else.

In reading his post, I don’t think it’s anything to necessarily be ashamed of in that his post first lists the principles above, but then it goes on to make two lists, one for ALT.NET and one for Not ALT.NET. Sam’s mistake is not in joining in the ALT.NET fun, it’s in making the hot-or-not list appear to be a significant part of ALT.NET (whether he intended this or not).

As the last ALT.NET principle states, tools only take you so far. Not only that, they change rapidly. Tools that are “HOT” today will end up being “NOT” tomorrow. While picking the best tools for the job is important to developers, suggesting specific tools is an addendum to ALT.NET, not core to it.

I certainly have my list of tools I think are the best tools for the job, but I won’t go so far to say you must use these tools or you’re a Mort. Drawing lines among which tools you use is just plain silliness, reminiscent of elementary school lines drawn along who could afford designer jeans.

So Sam, if you’re reading, keep in mind that the Agile Manifesto wasn’t written in one shot. It took time to evolve and refine the message till it was something the signers could agree upon.

I think ALT.NET is in that stage. The message is still being defined and refined and we need voices of reason involved. So while you might leave CodeBetter, consider staying involved in ALT.NET. After all, the goal is to sift out the really gold nuggets and move them to the mainstream.

comments suggest edit

I think Miguel de Icaza nails it regarding some of the FUD being written about Microsoft’s latest move to make the source code to the .NET Framework available under the Microsoft Reference License (Ms-RL).

In fact, his post inspired me to try my hand at creating a comic. I have no comic art skills (nor comic writing skills), so please forgive me for my lack of talent (click for full size)…

Microsoft opens the
code

I know some of the people involved who made this happen and I find it hard to believe that there were nefarious intentions involved. You have to understand that while Bill Gates and Steve Ballmer are known for playing hardball, they aren’t necessarily personally involved in every initiative at Microsoft (as far as I know).

Some things start from the grassroots with motives as simple as trying to give developers a better experience than they’ve had before.

Before: the original code, complete with helpful comments, original variable names, etc… was closed. You could use Reflector (and possibly violate EULAs in the process), but it wasn’t as nice as having the actual code.

After: The source is available to be seen. This is certainly not more closed than before. It is clearly better because you now have more choice. You can choose to view the code, or chose not to. Before, you only had one choice - no lookie lookie here!

But It’s Not Open Source!

Many pundits have pointed out that this is not Open Source. That is correct and as far as I can tell, nobody at Microsoft (at least in an official position) is claiming that.

The Ms-RL is not an open source license, so there is reason to be cautious should you be contributing to the Mono project, or plan to write a component that is similar to something within the framework. As Miguel wrote in his post, these precautions have been in place within the Open Source community for a very long time.

So yes, it’s not open source. But it’s a step in the right direction. As I’ve written before, we’re seeing steady progression within Microsoft regarding Open Source, albeit with the occasional setback.

My hope, when I start at Microsoft, is to be involved with that progress in one form or another as I see it as essential and beneficial to Microsoft. But I will be patient.

Should You Look At The Code?

So should you look at the source code? Frans Bouma says no!

Take for example the new ReaderWriterLockSlim class introduced in .NET 3.5. It’s in the System.Threading namespace which will be released in the pack of sourcecode-you-can-look-at. This class is a replacement for the flawed ReaderWriterLock in the current versions of .NET. This new lock is based on a patent, which (I’m told) is developed by Jeffrey Richter and sold to MS. This new class has its weaknesses as well (nothing is perfect). If you want to bend this class to meet your particular locking needs by writing a new one based on the ideas in that class’ sourcecode, you’re liable for a lawsuit as your code is a derivative work based on a patented class which is available in sourcecode form.

However I think the advice in Miguel’s post addresses this to some degree.

If you have a vague recollection of the internals of a Unix program, this does not absolutely mean you can’t write an imitation of it, but do try to organize the imitation internally along different lines, because this is likely to make the details of the Unix version irrelevant and dissimilar to your results.

My advice would be to use your head and not veer towards one extreme or another. If you’re planning to ship a ReaderWriterLockSlim class, then I probably wouldn’t look at their implementation.

But that shouldn’t stop you from looking at code that you have no plans to rewrite or copy.

And what do you do if you happen to look at the ReaderWriterLockSlim class on accident and were planning to write one for your internal data entry app? Either have another member of your team write it, or follow the above advice and implement it along different lines.

For example, Unix utilities were generally optimized to minimize memory use; if you go for speed instead, your program will be very different …

Or, on the contrary, emphasize simplicity instead of speed. For some applications, the speed of today’s computers makes simpler algorithms adequate.

Or go for generality. For example, Unix programs often have static tables or fixed-size strings, which make for arbitrary limits; use dynamic allocation instead.

Just don’t copy the existing implementation.

For many developers, their code is never distributed because it is completely internal, or runs on a web server. In that case, I think the risk is very low that anyone is going to prove you infringed on a patent because you happened to look at a piece of code, unless the code is a very visible UI element.

Please don’t misunderstand me on this point. I’m not recommending you violate any software patents (even though I think most if not all software patents are dubious), I’m just saying the risk of patent taint for many developers who look at the .NET source code is not as grave as many are making it out to be. When in doubt, you’d do well to follow the advice in Miguel’s post.

UPDATE: Upon further reflection, I realized there is one particular risk with what I’ve just said.

In the case of the ReaderWriteLockSlim, I believe the particular algorithm for high performance is patented. But what if the idea of a reader write lock in general (one that allows simultaneous reads unless blocking for a write) was patented.

Then you could get in trouble for implementing a reader write lock even if you never look at the source code. Patent infringement is a whole different beast than copyright infringement. This scenario is not so far fetched and is something Bill Gates has warned against in the past and has come to pass many times in the present.

Of course, this risk is present whether or not Microsoft makes the source available. By using Reflector, for example, you’d have the same risk of being exposed to patented techniques.

I should point out I’m not a lawyer so follow any of this advice at your own risk.

Having said that, I think a follow-up post on Frans’s blog proposes a solution I think Microsoft should jump on to clear things up. It comes from the JRL (Java Research License).

The JRL is not a tainting license and includes an express ‘residual knowledge’ clause which says you’re not contaminated by things you happen to remember after examining the licensed technology. The JRL allows you to use the source code for the purpose of JRL-related activities but does not prohibit you from working on an independent implementation of the technology afterwards.

It’d be nice if Microsoft added a similar clause to the Ms-RL so much of this FUD can just go away. Or even better, take the next step and look at putting this code (at least some of it) under the Ms-PL.

Disclaimer: Starting on October 15, I will be a Microsoft Employee, but the opinions expressed in this post are mine and mine only. I do not speak for Microsoft on these matters.

I’m also the leader of a couple OSS projects, so I will be very careful about separating what I learn on the job vs what I contribute to Subtext et all. But I’ll be a PM so I hear I won’t be looking at much code anyways. ;)

comments suggest edit

ASP.NET 2.0
AnthologyI just received a few advanced copies of our new book and am giving away three of them to the first three people who leave a comment on this post.

But there’s a catch!

You have to have a blog and promise to write a review on your blog. This is on the honor system so I’ll send you the book and you can then review it.

In your comment, leave your email address in the email field (it’s not visible to anyone else) and I’ll follow up to get your mailing address. Also let me know if you want it signed or not. Not sure why you’d want that, but you never know.

comments suggest edit

One weakness with many blog engines, Subtext included, is that it is difficult to change the tags and categories for multiple entries at a time. In general, most blog engines streamline the workflow for tagging and categorizing a single blog post.

Fortunately, Marco De Sanctis, a friend of Simo (a core Subtext Developer) wrote a nice application that you can use to bulk categorize and tag multiple posts. He developed it using Subtext as a test-bed so it handles the fact that we use the rel-tag microformat within the content as our tagging mechanism. Sweeeeet!

blogmanager_image

Many thanks to Simo for blogging about this and to Marco for writing this.

code, tdd comments suggest edit

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.

1364145387_b8cf994488 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…

I’m sorry, but I’m not a fan of Bug Driven Development. I think Test Driven Development is not without its challenges, but it’s a better alternative. Either you’re with us, or against us. Are you a bug lover? Bug Driven Development gives comfort to the bugs.

UPDATE: this is an example of my dry humor. I don’t believe that “Framing” is a good way to win an argument and I would never actually say or recommend saying anything similar to to this. It’s meant as a bit of a joke, but with a point.

A team that is not focused on automated testing of some sort throughout the lifecycle of the project is effectively embracing Bug Driven Development. Bugs are going to drive the development cycle at the end of the project.

Don’t believe me though, look at the research done by others. In Facts and Fallacies of Software Engineering, Robert Glass points out…

Fact 31. Error removal is the most time-consuming phase of the life cycle.

In Rapid Development, Steve McConnell relates…

Shortcutting 1 day of QA activity early in the project is likely to cost you from 3 to 10 days of activity downstream.

In other words, if you don’t control the bugs, the bugs control your schedule.

code, tdd comments suggest edit

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())
  {
    IIdentity identity = mocks.CreateMock<IIdentity>();
    SetupResult.For(identity.IsAuthenticated).Return(true);
    principal = mocks.CreateMock<IPrincipal>();
    SetupResult.For(principal.Identity).Return(identity);
    SetupResult.For(principal.IsInRole("Admins")).Return(true);
  }

  using (mocks.Playback())
  {
    IPrincipal oldPrincipal = Thread.CurrentPrincipal;
    try
    {
      Thread.CurrentPrincipal = principal;
      FileBrowserConnector connector = new FileBrowserConnector();
      Assert.IsNotNull(connector, "Could not create the connector.");
    }
    finally
    {
      Thread.CurrentPrincipal = oldPrincipal;
    }
  }
}

The first test is really straightforward. It simply tries to instantiate the FileBrowserConnector class.

The second test is a bit more involved, but the concept is simple. I’m using the Rhino Mocks mocking framework to dynamically construct instance that implement the IIdentity and IPrincipal interfaces.

The following line…

SetupResult.For(principal.IsInRole("Admins")).Return(true);

Tells the dynamic principal mock to return true when the IsInRole method is called with the parameter “Admins”. We then set the Thread.CurrentPrincipal to this constructed principal and try and create the instance of FileBrowserConnector.

Here’s the results of my first test run, trimmed down a bit.

Found 2 tests
[failure] FileBrowserConnectorTests.NonAdminCannotCreateFileConnector
Exception of type 'MbUnit.Core.Exceptions.ExceptionNotThrownException' 
was thrown. 

[success] FileBrowserConnectorTests.AdminCanCreateFileConnector
[reports] generating HTML report
TestResults: file:///D:/AppData/MbUnit/Reports/UnitTests.Subtext.Tests.html

1 passed, 1 failed, 0 skipped, took 4.37 seconds.

As expected, one test passed and one failed. Now I can go ahead and enforce security on the FileBrowserConnector class.

[PrincipalPermission(SecurityAction.Demand, Role = "Admins")]
public class FileBrowserConnector: Page
{
  //... implementation ...
}

That’s all there is to it. You might be wondering if this test is even needed because all I’m really testing is that the PrincipalPermission attribute does indeed work.

This test is still important to prevent regressions. You don’t want someone coming along and removing that attribute by accident or out of ignorance and you don’t notice it.

In codebases that I’ve worked with, I’ve seen a tendency to ignore or forget to write test cases for security requirements. This demo hopefully provides a starting point for myself and others to making sure that security requirements get good test coverage.

I should probably write yet another test to make sure a principal in a different role cannot create an instance of this class.

code, tdd comments suggest edit

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), constructorArguments);
    Assert.Fail("Was able to create the instance with no security.");
  }
  catch(TargetInvocationException e)
  {
    Assert.IsInstanceOfType(typeof(SecurityException)
      , e.InnerException
      , "Expected a security exception, got something else.");
  }

  MockRepository mocks = new MockRepository();

  IPrincipal principal;
  using (mocks.Record())
  {
    IIdentity identity = mocks.CreateMock<IIdentity>();
    SetupResult.For(identity.IsAuthenticated).Return(true);
    principal = mocks.CreateMock<IPrincipal>();
    SetupResult.For(principal.Identity).Return(identity);
    Array.ForEach(allowedRoles, delegate(string role) 
    {
      SetupResult.For(principal.IsInRole(role)).Return(true);
    });
  }

  using (mocks.Playback())
  {
    IPrincipal oldPrincipal = Thread.CurrentPrincipal;
    try
    {       
      Thread.CurrentPrincipal = principal;       
      Activator.CreateInstance(typeof(T), constructorArguments);
      //Test passes if no exception is thrown.
    }     
    finally
    {       
      Thread.CurrentPrincipal = oldPrincipal;     
    }   
  } 
}

There are definite improvements we can make, but this is a nice quick way to test the basic permission level for a class.