Tatham Oddie

Talk Resources – Internet Explorer 9 for Developers

leave a comment »

At REMIX10, TechEd AU 2010 and TechEd NZ 2010 I’ve been showing some of what’s new in Internet Explorer 9 for developers.

Here are the slides and code: http://db.tt/JvEUu3o

The recording from TechEd New Zealand (the third and best version!) will end up here by 6th Sep or so: http://www.msteched.com/Speakers/Tatham-Oddie

IE9NZ

The recording from TechEd Australia (version 2 of the talk) is available here: http://www.msteched.com/2010/Australia/WEB204

IE9AU

And finally, here’s a recording from REMIX10 Australia (version 1 of the talk): http://www.microsoft.com/australia/remix/videos/default.aspx

IERemix

If you’ve attended any of these talks, thank you for your feedback! The session evals at conferences are like crack for speakers. We read every single one, and then we read them again.

– Tats

Written by Tatham Oddie

September 1, 2010 at 09:05

Scoop! C#’s new #until directive

with 4 comments

(Disclaimer: This post is about a C# language feature I’d like to see, not one that actually exists. Once the feature gets added, the title will be accurate and I’ll be able the world’s most pro-active blogger. :) )

Update 1: Added another approach

I’m trying to evolve a framework here at my current client. There are some 30+ solutions and an unknown (to me) number of developers dependent upon this framework. As such, I can’t go and make breaking changes without everybody’s CI build dieing and me getting escorted from the building.

Even when I do have access to all the code in one solution, I prefer a three pass approach of:

  1. implementing new functionality and bridging old functionality but marking it obsolete
  2. cleaning up all the build warnings triggered by the [Obsolete] attributes
  3. going back and deleting the obsolete code now that nothing depends on it anymore

Starting with that approach, I have some code like this:

[Obsolete("Use SomeOtherProperty instead.")]
public SomeType SomeProperty { get; set; }

public SomeOtherType SomeOtherProperty { get; set; }

In theory, each team will then drive down their build warnings over time.

In practice, I’ve never seen people do this very excitedly and I have no hope of driving all these down myself.

What I want to do is offer a fixed grace period something like this:

[Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
public SomeType SomeProperty { get; set; }

public SomeOtherType SomeOtherProperty { get; set; }

This gives each team a known grace period to update their usages, and then forces them after that. (It’s basically two release cycles.)

The problem is that I want to have these members die automatically once this date arrives. (I may or may not be here, etc.)

Approach #1

I came up with this:

#until 2010-08-01
    [Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
    public SomeType SomeProperty { get; set; }
#enduntil

public SomeOtherType SomeOtherProperty { get; set; }

Basically, that code block is only compiled up until 1st August. As soon as that date ticks around, the member is magically nuked from the build and the lazy downstream users start getting compile errors. The simple syntax of this also makes it easy for me to run some PowerShell + regular expressions over the framework codebase on a regular basis and remove the actual source code.

Unfortunately, C# doesn’t include the #until directive yet and I doubt Anders is going to give me a custom compiler build any time soon. :)

Approach #2

My next idea was to create a numeric version of the date and then using a basic conditional compilation directive:

#if DATESERIAL < 20100801
    [Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
    public SomeType SomeProperty { get; set; }
#endif

public SomeOtherType SomeOtherProperty { get; set; }

I’d then include something in the build script that adds the current date as a symbol (eg. csc.exe /define:DATESERIAL=20100801).

Unfortunately, symbols are just symbols (duh) and thus don’t have values. Also, the pre-processor ‘expressions’ used in #if only support basic boolean expressions.

Approach #3

My next idea was to make the dates less granular and define a series of symbols for the last 3 months or so. For example, a build run today 17th June 2010 would be executed like so – with a symbol for April, May and June:

csc.exe /define:OBSOLETE_201004;OBSOLETE_201005;OBSOLETE_201006

The code could then look like this:

#if OBSOLETE_201005
    [Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
    public SomeType SomeProperty { get; set; }
#endif

public SomeOtherType SomeOtherProperty { get; set; }

As soon as September ticks around, the OBSOLETE_201005 symbol will fall off the list and voila, the member dies.

This approach is basically flagging the date that we marked something obsolete (in this example, May 2010) and then allowing the build process to determine which ones are in and which ones are one.

I don’t like the approach for a few reasons:

  • it means that the directive isn’t as clear (it’s the date we indicated the change, not the date it’s going to take effect)
  • the message in the attribute can potentially become wrong (say we decided to include four months’ worth of obsolete changes instead of three, all the messages will now be out by one month)
  • all of the members are now forced on to the same attrition cycle – I can’t spread the ‘easier’ ones on to one cycle and the ‘harder’ ones on to a longer cycle

Approach #4

Let’s go back and evolve the syntax from approach #1:

//#until 2010-08-01
    [Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
    public SomeType SomeProperty { get; set; }
//#enduntil

public SomeOtherType SomeOtherProperty { get; set; }

All I’ve done is add the comment indicator to the start of each of the directives so that they still look like directives but the compiler doesn’t try and process them.

I was already planning to have a PowerShell script that I could use to find the stale code after it had passed its used by date. Keeping the syntax simple makes it easy to find the blocks via regular expressions, so this would be quite easy to do.

I could run this same script at the start of the build:

  1. Create a workspace for the build
  2. Run the PS script across it to remove any expired code
  3. Run the compiler

The problem with this approach is that it clobbers your code. This works fine on a build server where you’re creating a new workspace for every build. It doesn’t work so well in your local environment, and that’s just yucky. This doesn’t affect the downstream consumers (they only get binaries) however it kind of sucks for the framework team.

Approach #5

(This is inspired from Simon’s response.)

Bringing this all back into C#, we can move the onus on to the framework team. First up, lets add a custom attribute to the member:

[ValidUntil(2010, 08, 01)]
[Obsolete("Use SomeOtherProperty instead. This member will be removed on 1st Aug 2010.")]
public SomeType SomeProperty { get; set; }

public SomeOtherType SomeOtherProperty { get; set; }

Now, the framework build could include a unit test that uses reflection to find all the instances of this attribute and evaluate the dates. If the date is in the past, the unit test fails and the framework build fails. The framework team would then identify the build break and delete the now expired code.

Approach #6

Feel free to suggest. :)

Written by Tatham Oddie

June 17, 2010 at 14:51

Posted in Technical

Tagged with

Talk Resources – Riding the Geolocation Wave

with one comment

At both the REMIX10 conference in Melbourne, Australia and more recently TechEd New Zealand I presented on geolocation for developers.

This was the abstract:

It’s pretty obvious by now that geolocation is a heavy player in the next wave of applications and APIs. Now is the time to learn how to take advantage of this information and add context to your own applications. In this session we’ll look at geolocation at every layer of the stack – from open protocols to operating system APIs, from the browser to Windows Phone 7. Building a compelling geo-enabled experience takes more than simple coordinates. In this session Tatham will introduce the basics of determining a user’s location and then delve into some of the opportunities and restrictions that are specific to mobile devices and their interfaces.

The talk was filmed at REMIX10, and is available for download here: http://www.microsoft.com/australia/remix/videos/default.aspx

GeolocationScreenshot

The recording from TechEd New Zealand will end up here by 6th Sep or so: http://www.msteched.com/Speakers/Tatham-Oddie

In the mean time, here are some links to the code and resources:

(Post updated 3rd Sep 2010 with new links and videos)

Written by Tatham Oddie

June 3, 2010 at 11:00

Why Windows Azure Is Not Worth Investing In (For Developers)

with 31 comments

It’s pretty obvious that I’m a Microsoft fanboy. This is the story of how they let me down today.

Why I Wanted To Learn Windows Azure

This afternoon I sat down to write a simple web service that would expose my cloud based Exchange calendar as public free/busy feed (webcal://tath.am/freebusy).

The hosting requirements:

  • around 1 request every 5 minutes (0.003 requests/second)
  • around 10kb of transfer per request (100 MB/month)
  • no writeable storage or databases (it’s totally stateless)

Cloud hosting sounded like the perfect solution for this. I don’t care where it runs. I don’t care who or what else is running on the box. I don’t have any funky dependencies.

Whenever I go to write something for myself I use it as an opportunity to learn something new.

Today, it seemed like I was going to learn Windows Azure.

Why Azure Needs To Be Free For This Scenario

Being able to scale down a cloud hosting solution is just important as being able to scale it up. In fact, I’d go as far as suggesting that I think it’s even more important.

Right now, I can’t market myself as an Azure professional. I can’t get up at a community event and evangelise the product. I can’t answer questions about the product on mailing lists or forums. Giving me 25 hours of compute time to try the service isn’t going to let me learn the service.

The free availability of competing services is what lets somebody spin up a political statement in an hour. As well as getting a quick, free and suitably tiny hosting solution, Lachlan and Andy were sharpening their skills and building their own confidence with Heroku.

It’s not all about bringing users to Azure though – it also works in reverse. In the interests of being up to date with how ‘the other half’ live, I like to have a bit of a handle on what the Ruby world is up to. Recently I built http://tath.am/where so that I could publish a visualization of places that I’ve recently been and commonly go. This is a simple enough app that I figured it would be a good place to start some Ruby with however I initially dismissed this idea because I didn’t want to have to work out how to host it. In the end, the availability of Heroku actually brought me to the Ruby platform. Windows Azure is our opportunity to bring new devs to the .NET platform.

Attempt #1: Free via the Windows Azure Platform Introductory Special

My first point of call was http://www.microsoft.com/windowsazure/ where I spotted the introductory offer:

Windows Azure Platform Introductory Special isn't so special

Sounds perfect! It’s free, and it has a teeny tiny bit of everything to let me play with it all.

Alas, this wasn’t the case:

Only 25 hours of computer time per month

That means I can only run my service for 48 minutes and 38 seconds per day.

Attempt #2: Free via MSDN benefits

As an MSDN subscriber, I have access to yet another “Introductory” offer. This offer includes 750 hours per month (basically the whole month, as 31 days = 744 hours) as well as way more storage and bandwidth than I would possibly use with this service.

The problem with this approach is that it only lasts for 8 months (assuming I disable auto-renew otherwise they just start charging me). After this time, my MSDN Ultimate subscription will only entitle me to 250 compute hours per month.

That means I can only run my service for 8 hours and 3 minutes per day.

Attempt #3: Just paying for it

Apparently my part of the internet is completely different to your part of the internet:

Microsoft still don't understand that other countries exist

Once again, Microsoft have completely stuffed up their product globalization strategy.

Attempt #4: Pretending I’m American

Luckily, the country checks are easily bypassed thanks to no address verification service being implemented:

My completely valid US address

Before I hand over my credit card for “usage based billing”, let’s just estimate what this is going to cost me.

US$84.82 per month … for a web service.

The Solution

Once again, I’m back at Heroku. My web service will run with a single dyno (their compute unit) and happily tick away 24/7 for free. I already have one app on their infrastructure (http://tath.am/where) and now it sounds like I’ll be building my second.

Being realistic, I don’t expect many .NET devs to spend a weekend learning Ruby + Sinatra + Git + Heroku just to deploy a simple web service. Instead, I think they just won’t bother with Azure and will opt for traditional shared hosting or just not building the web service at all. The former is disappointing, the latter is terrifying.

Why Does This Make It Not Worth Investing In?

With the current pricing model, Windows Azure is destined for the same way that MapPoint went – a quiet solution in the corner that’s only used by larger corporates and lacks a viable ecosystem.

If you’re in the audience for this blog – Microsoft have made it clear that Windows Azure is not for you.

Unless you’re a Best Buy or Netflix contender and are looking to build out a prototype for the next PDC keynote, spend your time focussing on other solutions for now.

I’m Not The Only One

I agree completely. The MS view would be that hobbyists can play around on their local dev fabric/storage. Not much fun.
Brad Curtis

Yeah I had high hopes for Azure initially, but now I’m not so sure. As you’ve pointed out, it doesn’t really scale down.
Thomas Johansen

Azure could have been great with a trimmed down entry level package that was free. Sucks :-/
Thomas Johansen

Agree, seems to be missing one of the big benefits of cloud virtualization – scale down as well as up.
Jon Galloway

Yeah, it’s not very interesting at that price point. At least not to me.
Dave Ward

dude, that totally sucks! Heroku is pretty sweet, though. If they’ve only made Azure as simple as that.
Javier Lozano

well put, sad that azure’s out of reach for mere mortals
Brendan Forster

Really seems they’re missing the point of hobby guys developing the Azure skills then taking it back to work with them.
Andrew Tobin

Great post, keep it up I say. I have turned to GAE for similar projects for the same reasons. Good for everyone to speak up.
Tarn Barford

Written by Tatham Oddie

April 5, 2010 at 12:32

Posted in Uncategorized

Web Forms Model-View-Presenter on Hanselminutes

with 2 comments

Over the last few months Damian Edwards and myself have been spending quite a bit of time building out a Model-View-Presenter framework for ASP.NET Web Forms.

Until now we’ve been pretty quiet about it all on our blogs because we were busy polishing off v1 and trying to get all the documentation in order. Nevertheless, the word has definitely started to spread as Scott Hanselman interviewed me about the library on this week’s Hanselminutes episode.

Listen to the podcast

Learn more about the library

Written by Tatham Oddie

February 21, 2010 at 20:43

Custom Code Analysis Rules in VS2010 (and how to make them run in FxCop and VS2008 too)

with 9 comments

Back in 2002 Microsoft released FxCop, a static code analysis tool. At the time it was shipped as a separate product and received a bit of buzz. It used .NET reflection and a series of pre-defined rules to detect and report coding issues that wouldn’t normally be picked up by the compiler. Since this initial release, FxCop has undergone an amazing amount of work and become more mainstream with its integration into Visual Studio under the title of ‘Code Analysis’.

Recently I’ve been developing some custom extensions to FxCop – my own code analysis rules. While extremely powerful, this isn’t yet a fully documented or supported scenario. Until it is, this post shows you how to do it all.

Why should we care?

Lately I’ve been working on the ASP.NET Web Forms Model-View-Presenter framework. It’s not quite ready for launch yet, which is why I haven’t been blogging about it, but it is already in use by a number of high traffic websites. As more and more people have started to adopt the project in its relative infancy, documentation hasn’t been up to standard. To try and keep everybody in line I contemplated writing up some ‘best practices’ documentation but then figured that this probably wouldn’t get as much attention as it should and had a high chance of rapidly becoming stale.

Code analysis rules were the perfect solution. They would allow me to define a series of best practices for use of the library in a way that could be applied across multiple projects by the developers themselves. Code analysis rules are also great because they produce a simple task list of things to fix – something that appeals to developers and managers alike.

Over the course of developing these rules I’ve increasingly come to realise that custom rules are something that should be considered in any major project – even if it’s not a framework that will be redistributed. All projects (should) have some level of consistency in their architecture. The details of this are often enforced through good practice and code reviews, but from time to time things slip through. In the same way that we write unit tests to validate our work, I think we should be writing code analysis rules. Think of them like an “architectural validity test” or something.

The Basics

A quick note about versioning: First we’ll create some rules in VS2010, to be executed in VS2010. Later in the post we’ll look at how to compile these same rules in a way that makes them compatible with FxCop 1.36 (and thus VS2008). If you’re only targeting VS2008 then all the same concepts will apply but you’ll be able to skip a few steps.

  1. Start with a new class library project. Make sure you choose to target “.NET Framework 4”, even if the rest of your solution is targeting an earlier framework. Because we’re going to be loading these rules inside VS2010, and it uses .NET 4.0, we need to use it too.

    New Class Library using .NET Framework 4 

  2. Add references to FxCopSdk.dll, Microsoft.Cci.dll and Microsoft.VisualStudio.CodeAnalysis.dll. You’ll usually find these in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop, or an equivalent location. Don’t worry about copying these libraries to a better location or anything – we’ll look at a smarter way of referencing them shortly. (If you’re doing this in VS2008, you’ll need to download and install FxCop 1.36 first and then find these references in that folder. Also, you’ll only need the first two.)
  3. Add a new XML file to your project called Rules.xml. This will be a manifest file that describes each of our individual rules. To get us started, paste in the following content:

    <?xml version="1.0" encoding="utf-8" ?>
    <Rules FriendlyName="My Custom Rules">
      <Rule TypeName="AllTypeNamesShouldEndInFoo" Category="CustomRules.Naming" CheckId="CR1000">
        <Name>All type names should end in 'Foo'</Name>
        <Description>I like all of my types to end in 'Foo' so that I know they're a type.</Description>
        <Url>http://foobar.com</Url>
        <Resolution>The name of type {0} does not end with the suffix 'Foo'. Add the suffix to the type name.</Resolution>
        <MessageLevel Certainty="95">Warning</MessageLevel>
        <FixCategories>Breaking</FixCategories>
        <Email />
        <Owner />
      </Rule>
    </Rules>
    

    This XML file is pretty self-explanatory, but there are a few things I should point out:

    The type name needs to match the name of the class that we define the actual rule in, so make it appropriate (don’t use special characters, use Pascal casing, etc).

    The check id must be unique within the namespace of your rules, but really should be unique across the board. Microsoft uses the letters “CA” followed by a four digit number, and we use a similar scheme for Web Forms MVP.

    The resolution message is stored in the XML here, and not in your own code, but you want it to be as specific as possible so that the developer on the receiving end of it knows exactly what they need to do. Use it like a formatting string – you’ll soon see that it works really nicely.

  4. Go to the properties for the XML file and change the Build Action to EmbeddedResource so that it gets compiled into our DLL.

    Build Action: Embedded Resource

  5. Create a class called BaseRule and paste in the following code:

    using Microsoft.FxCop.Sdk;
    
    public abstract class BaseRule : BaseIntrospectionRule
    {
        protected BaseRule(string name)
            : base(
    
                // The name of the rule (must match exactly to an entry
                // in the manifest XML)
                name,
    
                // The name of the manifest XML file, qualified with the
                // namespace and missing the extension
                typeof(BaseRule).Assembly.GetName().Name + ".Rules",
    
                // The assembly to find the manifest XML in
                typeof(BaseRule).Assembly)
        {
        }
    }
    

    There are three pieces of information we’re passing into the base constructor here. The first is the type name of the rule which the framework will use to find the corresponding entry in the manifest, the second is the namespace qualified resource name of the manifest file itself and the last is the assembly that the manifest is stored in. I like to create this base class because the last two arguments will be the same for all of your rules and it gets ugly repeating them at the top of each rule.

  6. Create a class called AllTypeNamesShouldEndInFoo and paste in the following stub code:

    using Microsoft.FxCop.Sdk;
    using Microsoft.VisualStudio.CodeAnalysis.Extensibility;
    
    public class AllTypeNamesShouldEndInFoo : BaseRule
    {
        public AllTypeNamesShouldEndInFoo()
            : base("AllTypeNamesShouldEndInFoo")
        {
        }
    }
    

That’s all of the boilerplate code in place. Before we start writing the actual rule, let’s take a brief detour to the world of introspection.

Um … ‘introspection’?

The first version of FxCop used basic .NET reflection to weave its magic. This approach is relatively simple, familiar to most developers and was a quick-to-market solution for them. As FxCop grew, this approach couldn’t scale though. Reflection has two main problems: First and foremost, it only lets you inspect the signatures of types and members – there’s no way to look inside a method and see what other methods it’s calling or to identify bad control flows. Reflection also inherits a major restriction from the underlying framework – once loaded into an app domain, and assembly can’t be unloaded. This restriction wreaks havoc in scenarios where developers want to be able to rapidly rerun the tests; having to restart FxCop every time isn’t the most glamorous of development experiences.

At this point we could fall back to inspecting the original source code, but that comes with a whole bunch of parsing nightmares and ultimately ties us back to a particular language. CIL is where we want to be.

Later versions of FxCop started using an introspection engine. This provided a fundamentally different experience, light-years ahead of what reflection could provide. The introspection engine performs all of its own CIL parsing which means that it can be pointed at any .NET assembly without having to load that assembly into the runtime. Code can be inspected without ever having the chance of being executed. The same assembly can be reloaded as many times as we want. Better yet, we can explore from the assembly level right down to individual opcodes and control structures through a unified API.

Jason Kresowaty has published a nice write up of the introspection engine. Even cooler yet, he has released a tool called Introspector which allows us to visualise the object graph that the introspection engine gives us. I highly recommend that you download it before you get into any serious rules development.

Introspector

Back to our rule…

Now that we know some of the basics of introspection, we’re ready to start coding our own rule. As a reminder, this is what we have so far:

using Microsoft.FxCop.Sdk;
using Microsoft.VisualStudio.CodeAnalysis.Extensibility;

public class AllTypeNamesShouldEndInFoo : BaseRule
{
    public AllTypeNamesShouldEndInFoo()
        : base("AllTypeNamesShouldEndInFoo")
    {
    }
}

The FxCop runtime manages the process of ‘walking’ the assembly for us. It will visit every node that it needs to, but no more, and it’ll do it across multiple threads. All we need to do is tell the runtime which nodes we’re interested in. To do this, we override one of the many Check methods.

As much as possible, use the most specific override that you can as this will give FxCop a better idea of what you’re actually looking at and thus provide better feedback to the end user. For example, if you want to look at method names don’t override Check(TypeNode) and enumerate the methods yourself because any violations you raise will be raised against the overall type. Instead, override Check(Member member).

In our scenario, because we want to check type names, we’ll override Check(TypeNode type).

The actual code for this rule is quite simple:

public override ProblemCollection Check(TypeNode type)
{
    if (!type.Name.Name.EndsWith("Foo", StringComparison.Ordinal))
    {
        var resolution = GetResolution(type.Name.Name);
        var problem = new Problem(resolution, type)
                          {
                              Certainty = 100,
                              FixCategory = FixCategories.Breaking,
                              MessageLevel = MessageLevel.Warning
                          };
        Problems.Add(problem);
    }

    return Problems;
}

All we’re doing here is checking the name of the type, and then adding a problem to a collection on the base type. The GetResolution method acts like string.Format and takes an array of parameters then formats them into the resolution text we defined in the XML file.

The second argument that we pass to the Problem constructor is the introspection node that the problem relates to. In this case it’s just the type itself, but if we were doing our own enumeration then we would pass the most specific node possible here so that FxCop could return the most accurate source reference possible to the end user.

Let’s start ‘er up.

At the time of writing, the latest standalone version of FxCop is 1.36 which still targets .NET 2.0 – 3.5. Because we’ve written our rule in .NET 4.0, our only option is to test it within Visual Studio. Luckily, that’s not as hard as it sounds. (If you’re writing your rules in VS2008, jump over this section.)

  1. Create another class library in your solution called TestLibrary. We won’t put any real code in here – we’re just going to use it as the library to execute our rules against.
  2. Add a new Code Analysis Rule Set file to the project:

    New Code Analysis Rule Set

  3. When the file opens in the designer you’ll see a list of all the built-in rules. Because custom rules aren’t really supported yet, there’s no nice way of adding our own rules into this list.

    Default Rules

  4. In Solution Explorer, right click on the .ruleset file, choose Open With and select XML Editor from the options. This will show you the raw contents of the file, which is currently pretty boring. To point Visual Studio in the direction of your custom rules, you then add a series of hint paths.

    This is what my rule set XML looks like:

    <?xml version="1.0" encoding="utf-8"?>
    <RuleSet Name="New Rule Set" Description="" ToolsVersion="10.0">
      <RuleHintPaths>
        <Path>C:\Temp\CARules\BlogDemo\BlogDemo.CodeAnalysisRules\bin\Debug</Path>
      </RuleHintPaths>
    </RuleSet>
    

    Hint paths can be absolute, or relative to the location of the rule set file. They should point at the exact folder that your compiled rules sit in. Because Visual Studio fails silently if it can’t load a rule, I prefer to start with an absolute folder path first, then change it to a relative path once everything is working.

  5. Make sure you have compiled your rules project, then go back to Solution Explorer, right click on the .ruleset file, choose Open With and select Code Analysis Rule Set Editor.

    (If you have file locking issues, close Visual Studio, delete all of your bin folders, reopen the solution, build the rules project, then attempt to open the Code Analysis Rule Set Editor again.)

Now, you should see your custom rule loaded into the list:

6CustomRules

Running the rule is now easy. Open the project properties for your test library project, go to the Code Analysis tab, enable Code Analysis and select our new rule set:

7EnableCodeAnalysis

Now when we build the project, the output from our new rule will appear in the Errors List just like any of the default rules:

8ErrorList

A Bit of Clean-up

Back when we first created the project file for our rules we referenced a couple of DLLs from a system location. This isn’t very maintainable, particularly in a team environment, so let’s clean that up quickly.

  1. Right click on the rules project and select “Unload Project”
  2. Right click on the rules project again and select “Edit .csproj” – this will show you the raw XML definition for the project
  3. Find these three references:

    <Reference Include="FxCopSdk">
      <HintPath>..\..\..\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\FxCopSdk.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Cci">
      <HintPath>..\..\..\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\Microsoft.Cci.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.CodeAnalysis, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\Microsoft.VisualStudio.CodeAnalysis.dll</HintPath>
      <Private>True</Private>
    </Reference>
    

    And replace them with this:

    <Reference Include="FxCopSdk">
      <HintPath>$(CodeAnalysisPath)\FxCopSdk.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Cci">
      <HintPath>$(CodeAnalysisPath)\Microsoft.Cci.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.CodeAnalysis">
      <HintPath>$(CodeAnalysisPath)\Microsoft.VisualStudio.CodeAnalysis.dll</HintPath>
      <Private>False</Private>
    </Reference>
    

    The build system populates the $(CodeAnalysisPath) variable for us automatically. This way, our references will be valid on every developer’s machine.

  4. Save and close the file, then right click the project and select “Reload Project”

Do the shuffle. The two-step, multi-framework shuffle…

For Web Forms MVP we want to support users on both VS2008 and VS2010. The work we’ve done so far in this post is all exclusively targeted towards VS2010 and not compatible with VS2008 or FxCop 1.36.

To make the compiled rules compatible with both IDEs we’ll need to compile two different versions of it. The VS2008 version will use .NET 3.5 and only two references while the VS2010 version will use .NET 4 and a third reference, Microsoft.VisualStudio.CodeAnalysis.

  1. Right click on the rules project and select “Unload Project”
  2. Right click on the rules project again and select “Edit .csproj” – this will show you the raw XML definition for the project
  3. Find both your Debug and Release property groups and add a DEV10 constant to each:

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
      ...
      <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS;DEV10</DefineConstants>
      ...
    </PropertyGroup>
    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
      ...
      <DefineConstants>TRACE;DEV10</DefineConstants>
      ...
    </PropertyGroup>
    
  4. Find the Microsoft.VisualStudio.CodeAnalysis reference and make it conditional based on the framework version being compiled against:

    <Reference Include="Microsoft.VisualStudio.CodeAnalysis" Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">
      <HintPath>$(CodeAnalysisPath)\Microsoft.VisualStudio.CodeAnalysis.dll</HintPath>
      <Private>False</Private>
    </Reference>
    
  5. Save and close the file, then right click the project and select “Reload Project”
  6. Go to AllTypeNamesShouldEndInFoo.cs and wrap the using statement for Microsoft.VisualStudio.CodeAnalysis.Extensibility in an #if construct like so:

    using System;
    using Microsoft.FxCop.Sdk;
    #if DEV10
        using Microsoft.VisualStudio.CodeAnalysis.Extensibility;
    #endif
    
  7. Make sure that your project still compiles with VS2010

At this point our project is still only building for VS2010 but it now contains all of the hook points we need to perform a second build for VS2008. The reference to Microsoft.VisualStudio.CodeAnalysis.dll will only be included if we’re building against .NET 4 and the using statements will only be compiled if the DEV10 compilation constant is present.

Normally, we would build the project using a simple call to MSBuild (which is exactly what VS2010 does under the covers):

MSBuild "BlogDemo.CodeAnalysisRules.csproj" /p:Configuration=Release /maxcpucount

To compile the FxCop 1.36 version, we just pass some extra arguments:

MSBuild  BlogDemo.CodeAnalysisRules.csproj " /p:Configuration=Release /maxcpucount /p:CodeAnalysisPath="..\Dependencies\FxCop136\" /p:DefineConstants="" /p:TargetFrameworkVersion="v3.5"

The CodeAnalysisPath parameter is normally supplied by MSBuild, but we are now overriding it with the location of the FxCop 1.36 SDK. We’re also overriding TargetFrameworkVersion.

Of course, there are nicer ways to script the build process using technologies like PowerShell. The ZIP file below contains a nice little Build-CARules.ps1 which you can use as a template.

The Resources

Download all of the sample code from this blog post and a PowerShell build script here:

Download CodeAnalysisRulesBlogDemo.zip

Written by Tatham Oddie

January 6, 2010 at 14:57

I work on the web.

with 2 comments

Readify’s CTO Mitch Denny just announced Damian and myself as the first two Readify staff to receive the new title of “Technical Specialist”. This is an additional title to represent technical focus beyond our standard consulting commitments. Over the coming weeks, this will be awarded in a number of key technology areas. Obviously, for Damian and myself, it’s the web. :)

As part of the position we needed to do a bit of a refresh on our consulting profiles, a component of which is a blurb about why we work in the industry. Having just written mine, I felt like sharing it:

The web was never a platform I explicitly sought out; it was more so somewhere I ended up, but I ended up here for a reason. The shear breadth and power of the web, from both technical and business perspectives, made it a natural fit as I developed my career and skill sets.

I’ve always been fascinated by how a relatively simple set of building blocks designed through the 70s and 80s now underpin so much of what we do today. Video calling might look all fancy and futuristic, but it’s still sitting on much of that same technology. It’s this ability to foster evolution and innovation in an open, neutral and (mostly) democratic way that makes the web both possible and exciting.

Mass organic adoption of the web has today given us a heterogeneous environment of networks, devices and software clients that can be quite accurately described as somewhat hostile. Navigating these challenges to deliver a robust and compelling solution, while also seeking to drive the web forward, is what I do as a web specialist.

Microsoft’s early forays into web development were designed to make it an easy transition for their existing community of developers. This approach has resulted in a generation of developers who work on the web without necessarily being fully aware of its scope or potential. Microsoft’s current push is to now bring these developers across to the next iteration of the web. Engaging these audiences and encouraging them to that take that next step is a key component of what I do as an active community member.

In an ever increasingly connected world, now is the time to work on the web.

Why do you work on the web?

(While you’re thinking about it, check out iworkontheweb.com)

Written by Tatham Oddie

September 25, 2009 at 14:08

Posted in Uncategorized

Missed TechEd Australia? Get the content anyway.

with 2 comments

Close on the heels of TechEd Australia, Readify have announced their latest Dev Day event. This time, we’ve also tweaked the structure a little bit so that instead of having two tracks at the same time we’ll be running a morning track and an afternoon track. This way you get to see it all, or just pop in for the half day if you want.

Richard Banks will be presenting in the morning on Software Quality and Application Lifecycle Management, split into:

  • Gathering Quality Requirements for Agile Development Teams, and an
  • Introduction to Visual Studio Team System 2010.

In the afternoon, I’ll be covering Building for the Web with .NET through three different presentations:

  • Building Fast, Standards Compliant ASP.NET Websites,
  • ASP.NET MVC: Building for the web, and an
  • Introduction to the ASP.NET Web Forms Model-View-Presenter framework.

For my talks, you can find some teasers between my last two blog posts and CodePlex.

To see it all, you’ll just have to come along though. :)

More info at: http://readify.net/training-and-events/rdn-dev-days/

See you there!

Written by Tatham Oddie

September 22, 2009 at 09:52

Posted in Uncategorized

Video: Building Fast, Public Websites

with one comment

Following up from my last post about the ASP.NET MVC vs ASP.NET WebForms debate, we’ve had a second TechTalk posted, also from TechEd Australia. In this video, Michael Kordahi, Damian Edwards and I sat down to discuss building fast, public websites. It was a bit of a teaser for our breakout session at the conference, which will be available online as a screencast in the next week or two.

If you’re interested in learning more about building large public websites on ASP.NET, remember that the full video from our recent REMIX session is still available online too.

Building Fast, Public Websites

Watch Online or Download

Written by Tatham Oddie

September 14, 2009 at 21:04

Video: ASP.NET MVC vs ASP.NET WebForms – Will WebForms be replaced by MVC?

with 5 comments

At the recent TechEd Australia conference, Paul Glavich, Damian Edwards and myself sat down to discuss what we thought about the current MVC vs WebForms debate. Our TechTalk has now been posted on the TechEd Online site, and available for anyone to watch.

Check it out, and feel free to continue the debate with any of us. :)

ASP.NET MVC vs ASP.NET WebForms – Will WebForms be replaced by MVC? 

Watch Online or Download

Written by Tatham Oddie

September 14, 2009 at 20:52