Archive for Development category

8 things you probably didn’t know about C#

Here’s a few unusual things about C# that few C# developers seem to know about.

1. Indexers can use params

We all know the regular indexer pattern x = something[“a”] and to implement it you write:

public string this[string key] {
  get { return internalDictionary[key]; }
}

But did you know that you can use params to allow x = something[“a”, “b”, “c”, “d”] ?

Simply write your indexer like this:

public IEnumerable<string> this[params string[] keys] {
  get { return keys.Select(key => internalDictionary[key]).AsEnumerable(); }
}

The cool thing is you can have both indexers in the same class side-by-side. If somebody passes an array or multiple args they get an IEnumerable back but call with a single arg and they get a single value.

2. Strings defined multiple times in your code are folded into one instance

Many developers believe that:

if (x == "" || x == "y")

will create a couple of strings every time. It won’t.

C#, like many languages, has string interning and every string your app compiles with gets put into an in-memory list that is referenced at runtime.

You can use String.Intern to see if it’s currently in this list but bear in mind that doing String.Intern(“what”) == “what” will always return true as you just defined another string in your source. String.IsInterned(“wh” + “at”) == “what” will also return true thanks to compiler optimizations. String.IsInterned(new string(new char[] { ‘w’,’h’,’a’,’t’ }) == new string(new char[] { ‘w’,’h’,’a’,’t’ }) will only return true if you have “what” elsewhere in your program or something else at runtime has added it to the intern pool.

If you have classes that build up or retrieve regularly used strings at runtime consider using String.Intern to add them to the pool. Bear in mind once in they’re there until your app quits so use String.Intern carefully. The syntax is simply String.Intern(someClass.ToString())

Another caveat is that doing (object)”Hi” == (object)”Hi” will return true in your app thanks to interning. Try it in your debug intermediate window and it will be false as the debugger will not be interning your strings.

3. Exposing types as a less capable type doesn’t prevent use as their real type

A great example of this is when internal lists are exposed as IEnumerable properties, e.g.

private readonly List<string> internalStrings = new List<string>();
public IEnumerable<string> AllStrings { get { return internalStrings; }

You’d likely think nobody can modify internal strings. Alas, it’s all too easy:

((List<string>)x.AllStrings).Add("Hello");

Even AsEnumerable won’t help as that’s a LINQ method that does nothing :( You can use AsReadOnly which creates a wrapper over the list that throws when you try and set anything however and provides a good pattern for doing similar things with your own classes should you need to expose a subset of internal structures if unavoidable.

4. Variables in methods can be scoped with just braces

In Pascal you had to declare all the variables your function would use at the start of the function. Thankfully today the declarations can live next to their assignment and use which prevents acidentally using the variable before you intended to.

What it doesn’t do is stop you using it after you intended. Given that for/if/while/using etc. all allow a nested scope it should come as only mild surprise that you can declare variables within braces without a keyword to achieve the same result:

private void MultipleScopes() {
  { var a = 1; Console.WriteLine(a); }
  { var b = 2; Console.WriteLine(a); }
}

It’s almost useful as now the second copy-and-pasted code block doesn’t compile but a much better solution is to split your method into smaller ones using the extract method refactoring.

5. Enums can have extension methods

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions {
  public static DateTime From(this Duration duration, DateTime dateTime) {
    switch duration {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration")
    }
  }
}

I think enums are evil but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

6. Order of static variable declaration in your source code matters

Some people insist that variables are ordered alphabetically and there are tools around that can reorder for you… however there is one scenario where re-ording can break your app.

static class Program {
  private static int a = 5;
  private static int b = a;

  static void Main(string[] args) {
   Console.WriteLine(b);
  }
}

This will print the value 5. Reorder the a and b declarations and it will output 0.

7. Private instance variables of a class can be accessed by other instances

You might think the following code wouldn’t work:

class KeepSecret {
  private int someSecret;
  public bool Equals(KeepSecret other) {
    return other.someSecret == someSecret;
  }
}

It’s easy to think of private as meaning only this instance of a class can access them but the reality is it means only this class can access it… including other instances of this class. It’s actually quite useful for some comparison methods.

8. The C# Language specification is already on your computer

Providing you have Visual Studio installed you can find it in your Visual Studio folder in your Program Files folder (x86 if on a 64-bit machine) within the VC#\Specifications folder. VS 2010 comes with the C# 5.0 document in Word format.

It’s full of many more interesting facts such as:

  • i = 1 is atomic (thread-safe) for an int but not long
  • You can & and | nullable booleans with SQL compatibility
  • [Conditional(“DEBUG”)] is more useful than #if DEBUG

And to those of you that say “I knew all/most of these!” I say “Where are you when I’m recruiting!” Seriously, it’s hard enough trying to find C# devs with a solid understanding of the well-know parts of the language.

[)amien

Designing a great API

Several years ago I worked on a payroll package developing a core engine that required an API to let third parties write calculations, validations and security gates that would execute as part of it’s regular operation.

We were a small team and I had many conversations with another developer tasked with building a payroll using the API I would provide. Some methods here, classes there, the odd helper function and I had an API and then we had a mini payroll running.

Then he showed me the code he had written and that smug grin dropped off my face. It was awful.

Perhaps this other developer wasn’t as great as I’d thought? Looking at the code though made me realise he had done the best anyone could with a terrible API. I’d exposed parts of this core payroll engine with hooks when it needed a decision. Its job was to run the payroll – a very complex task that involved storage, translation, time periods, users and companies. That complexity and context had leaked out.

Unfortunately it’s not a unique story – many API’s are terrible to use. They’re concerned with their own terminology, limitations and quirks because they are exposed sections of an underlying system developed by those responsible for the underlying system.

If you want others to have a good experience with your product you have to put yourself in their shoes. Whether it’s a UI or an API makes no difference.

You are not the user

That’s the real difference between writing the classes that form your regular implementation and those that make up your public API.

We had time to fix our payroll API. Instead of refining and polishing here and there we took the 20 or so snippets developed for the mini payroll and pruned, cleaned and polished until they looked beautiful. They scanned well and made sense to payroll developers unfamiliar with our package. When a third developer familiar with payrolls but unfamiliar with out package developed the necessary code for a fully-functional jurisdiction in record time with minimal assistance we knew we had hit our goal.

Sure implementing that new API was hard work. Instead of simple methods sticking out of the engine we had a facade over our engine but it was justified. They were two different systems for two different types of user with distinct ideas about what the system was and how it was going to be used.

Code First

Many years later I found myself on a small team of 3 people tasked with putting a brand new API on top of Entity Framework for configuring models with code the .NET world would come to know as Code First. I was determined to use my experience and avoid another complex API surface littered with terminology and leaky abstractions. Parts of EF already suffered from that problem.

So for the first few weeks of that project we didn’t write any of the code that would in fact become Code First.

Instead we decided who our user was – in this case a C# developer who likes writing code, knows LINQ and some database concepts but doesn’t know Entity Framework as people who did were already using Model First or Database First.

Then we wrote tiny sample apps and tried to find simpler and simpler ways to describe them in code. We’d often start on a whiteboard with a scenario and write the complete mapping. We’d then try and find conventions that would remove the need for most of it and then try to write succinct code to configure the rest. As the newest guy to the team I’d fight to keep EF terms away from the main API surface in order to reduce that barrier to entry and help drive adoption.

Finally we’d hit the computer and develop stub classes and methods to make samples compile and let us try the IntelliSense. This isn’t always necessary but if you want to develop a fluent API or provide lots of type-safety such as Code First’s relationship mapping it’s highly recommended.

We’d then revisit the samples later and see if they could be read as easily as they were written and figure out what problems people were likely to run into and whether we could solve them without too much noise. Sometimes this meant having more than one way to do things such as chaining the fluent methods or allowing a bunch of properties to be set (solved with an extension method class providing the fluent API) and how users could manage larger models (solved by subclassing EntityConfiguration<T> – now EntityTypeConfiguration<T> sigh – and allowing redundant specification for things like relationships that span more than one class).

We finally ended up with succinct code like this with IntelliSense guiding you along the way and preventing you from even being able to specify invalid combinations. The HasMany prompts the properties on Customer and it won’t show you WithRequired unless it is valid. In the case of Required to Required it will ensure that the WithRequired specified which end is principle and dependent. In short it guides you through the process and results in highly readable code.

Entity<Customer>().HasMany(c => c.Orders).WithRequired(o => o.Customer).WillCascadeOnDelete();

This process took a little longer but given the amount of use the API will get that time will be saved by users countless times over.

Code First went down incredibly well with both the target audience and existing EF users and inspired the simpler DbContext interface that became the recommended way of accessing EF.

I think it’s one of the nicest API’s to come out of Microsoft and .NET.

[)amien

PS. Martin Fowler has some great guidance in his book Domain Specific Languages.

Behind the scenes at xbox.com &#8211; RSS enabling web marketplace

A number of people were requesting additional RSS feeds for the xbox.com web marketplace. (We had just one that included all new arrivals)

Looking across our site as the various lists of products we display today the significant views are:

  • Browse games by department
  • Search results
  • Promotions (e.g. Deal of the week)
  • Game detail (shows downloads available beneath it)
  • Avatar item browse

These views also have sorting options and a set of filters available for things like product type, game genre, content rating etc.

So we had a couple of options:

  1. Write controller actions that expose the results of specific queries as RSS
  2. Introduce a mechanism whereby any of our product result pages can render as RSS including any user-defined filtering

Our web marketplace is written in ASP.NET MVC (like most of xbox.com) so while option 1 sounds simpler MVC really helps us make option 2 more attractive by way of a useful feature called ActionFilters that let us jump in and reshape the way existing actions behave.

ActionFilters

ActionFilters can be applied to either to an individual action method on a controller or to the controller class itself which applies it to all the actions on that controller. They provide hooks into the processing pipeline where you can jump in and perform additional processing.

The most interesting events are:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted
We’re going to hook in to the OnActionExecuted step – this is because we always want to run after the code in the controller action has executed but before the ActionResult has done it’s work – i.e. before page or RSS rendering.

Writing our ActionFilter

The first thing we want to do is identify that a request wants the RSS version. One way is to read the accepts header and switch when it requests mime/type but this can be a little trickier to test,  another is to append a query parameter on the url which is very easy to test.

Once we’ve identified the incoming request should be for RSS we need to identify the data we want to turn into RSS and repurpose it.

All the views we identified at the start of this post share a common rendering mechanism and each view model subclasses from one of our base models. For simplicity though we’ll imagine an interface that just exposes an IEnumerable<Product> property.

public class RssEnabledAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        var viewModel = filterContext.Controller.ViewData.Model as IProductResultViewModel;
        if (viewModel == null)
            return;

        var rssFeedTitle = FeedHelper.MakeTitle(viewModel.Results);
        filterContext.Controller.ViewData.Add("RssFeedTitle", rssFeedTitle);

        var format = filterContext.RequestContext.HttpContext.Request.QueryString["format"];
        if (format == "rss" && rssFeedTitle != null) {
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            var url = QueryStringUtility.RemoveQueryStringParameter(filterContext.RequestContext.HttpContext.Request.Url.ToString(), "format");
            var feedItems = FeedHelper.GetSyndicationItems(viewModel.Results, urlHelper);
            filterContext.Result = FeedHelper.CreateProductFeed(rssFeedTitle, viewModel.Description, new Uri(url), feedItems);
        }

        base.OnActionExecuted(filterContext);
    }
}

This class relies on our FeedHelper class to achieve three things it needs:

  1. MakeTitle takes the request details – i.e. which page, type of products, filtering and sorting is selected and makes a title by re-using our breadcrumbs
  2. GetSyndicationItems takes the IEnumerable<Product> and turns it into IEnumerable<SyndicationItem> by way of a foreach projecting Product into SyndicationItem with some basic HTML formatting, combining the product image and setting the correct category (with a yield thrown in for good measure)
  3. CreateProductFeed then creates a Syndication feed with the appropriate Copyright and Language set and chooses the formatter – in our case RSS 2.0 but could easily be Atom 1.0, e.g.
public static SyndicationFeedResult CreateProductFeed(string title, string description, Uri link, IEnumerable<SyndicationItem> syndicationItems)
{
    var feed = new SyndicationFeed(title, description, link, syndicationItems) {
        Copyright = new TextSyndicationContent(String.Format(Resources.FeedCopyrightFormat, DateTime.Now.Year)),
        Language = CultureInfo.CurrentUICulture.Name
    };

    return new FeedResult(new Rss20FeedFormatter(feed, false));
}

The FeedResult class is a simple one that takes the built-in .NET SyndicationFeed class and wires it up to MVC by implementing an ActionResult that writes the XML of the SyndicationFeedFormatter into the response as well as setting the application/rss+xml content type and encoding.

Advertising the feed in the head

Now that we have the ability to serve up RSS we need to let browsers know it exists.

The ActionFilter we wrote above needs to know the title of the RSS feed regardless of whether it is rendering the RSS (which needs a title) or rendering the page (which will need to advertise the RSS title) so it always calculates it and then puts it into the ViewData dictionary with the key RssFeedTitle.

Now finally our site’s master page can check for the existence of that key/value pair and advertise it out with a simple link tag:

var rssFeedTitle = ViewData["RssFeedTitle"] as string;
if (!String.IsNullOrEmpty(rssFeedTitle)) { %>
<link rel="alternate" type="application/rss+xml" title="<%:rssFeedTitle%>" href="<%:Url.ForThisAsRssFeed%>" />
<% }

This code requires just one more thing – a very small UrlHelper which will append “format=rss” to the query string (taking into account whether there existing query parameters or not).

The result of this is we can now just add [RssEnabled] in front of any controller or action to turn on RSS feeds for that portion of our marketplace! :)

[)amien

Enums &#8211; Better syntax, improved performance and TryParse in NET 3.5

Recently I needed to map external data into in-memory objects. In such scenarios the TryParse methods of Int and String are useful but where is Enum.TryParse? TryParse exists in .NET 4.0 but like a lot of people I’m on .NET 3.5.

A quick look at Enum left me scratching my head.

  • Why didn’t enums receive the generic love that collections received in .NET 2.0?
  • Why do I have to pass in typeof(MyEnum) everywhere?
  • Why do I have to the cast results back to MyEnum all the time?
  • Can I write TryParse and still make quick – i.e. without try/catch?

I found myself with a small class, Enum<T> that solved all these. I was surprised when I put it through some benchmarks that also showed the various methods were significantly faster when processing a lot of documents. Even my TryParse was quicker than that in .NET 4.0.

While there is some small memory overhead with the initial class (about 5KB for the first, a few KB per enum after) the performance benefits came as an additional bonus on top of the nicer syntax.

Before (System.Enum)

var getValues = Enum.GetValues(typeof(MyEnumbers)).OfType();
var parse = (MyEnumbers)Enum.Parse(typeof(MyEnumbers), "Seven");
var isDefined = Enum.IsDefined(typeof(MyEnumbers), 3);
var getName = Enum.GetName(typeof(MyEnumbers), MyEnumbers.Eight);
MyEnumbers tryParse;
Enum.TryParse<MyEnumbers>("Zero", out tryParse);

After (Enum<T>)

var getValues = Enum<MyEnumbers>.GetValues();
var parse = Enum<MyEnumbers>.Parse("Seven");
var isDefined = Enum<MyEnumbers>.IsDefined(MyEnumbers.Eight);
var getName = Enum<MyEnumbers>.GetName(MyEnumbers.Eight);
MyEnumbers tryParse;
Enum<MyEnumbers>.TryParse("Zero", out tryParse);

I also added a useful ParseOrNull method that lets you either return null or default using the coalesce so you don’t have to mess around with out parameters, e.g.

MyEnumbers myValue = Enum<MyEnumbers>.ParseOrNull("Nine-teen") ?? MyEnumbers.Zero;

The class

GitHub has the latest version of EnumT.cs

Usage notes

  • This class as-is only works for Enum’s backed by an int (the default) although you could modify the class to use longs etc.
  • I doubt very much this class is of much use for flag enums
  • Casting from long can be done using the CastOrNull function instead of just putting (T)
  • GetName is actually much quicker than ToString on the Enum… (e.g. Enum<MyEnumbers>.GetName(a) over a.ToString())
  • IsDefined doesn’t take an object like Enum and instead has three overloads which map to the actual types Enum.IsDefined can deal with and saves runtime lookup
  • Some of the method may not behave exactly like their Enum counterparts in terms of exception messages, nulls etc.

[)amien