Archive for March, 2011

Convention Based Localization With ASP.NET MVC

6 commentsWritten on March 19th, 2011 by
Categories: ASP.NET MVC

A feature of ASP.NET MVC that i really like is that when you use the LabelFor extension method in a strongly-typed view, the LabelFor implementation will try to retrieve and use metadata for the property you're creating a label for. For instance:

@Html.LabelFor(m => m.SomeProperty)

This will generate an HTML label for the SomeProperty property of your model. If you need localized views, you can annotate the property in your model like this:

        [Display(ResourceType = typeof(Resources), Name = "ResourceKeyForSomeProperty")]
        public string SomeProperty { get; set; }

And the label will be generated with a localized value from your application's resources depending on the culture of the current user. Which is great, but putting those Display attributes on each property gets quite tedious. It would be better if the localized value was automatically retrieved based on a convention. Something like NameOfModelClass_NameOfProperty.

It turns out that ASP.NET MVC uses a DataAnnotationsModelMetaDataProvider by default to retrieve this metadata, and that you can provide a different implementation to be used by the framework. We still want to take advantage of those DataAnnotations, but we just want to add some convention-based default behavior to it as well. So we inherited from the DataAnnotationsModelMetaDataProvider and came up with something pretty simple like this:

    public class AnnotationsAndConventionsBasedModelMetaDataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
                                                        Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            if (string.IsNullOrEmpty(result.DisplayName) && containerType != null && propertyName != null)
            {
                var keyForDisplayValue = string.Format("{0}_{1}", containerType.Name, propertyName);
                var translatedValue = Resources.ResourceManager.GetObject(keyForDisplayValue) as string;

                if (!string.IsNullOrEmpty(translatedValue))
                {
                    result.DisplayName = translatedValue;
                }
            }

            return result;
        }
    }

We first call the base implementation which will get the values from annotations if they're present. If no DisplayName value was created based on annotations, we're going to check to see if the value is present in our resources based on the convention and if so, add it to the metadata before we return it. Then we instruct ASP.NET MVC to use this provider instead of the default:

            ModelMetadataProviders.Current = new AnnotationsAndConventionsBasedModelMetaDataProvider();

And now, every label will be localized automatically if a translation is present in the resources with the expected key. Not sure if this is the best way to do this (better suggestions are welcome!), but it's certainly a big step up from having to annotate each property.

Reminder: My NHibernate Course Is Coming Up

7 commentsWritten on March 8th, 2011 by
Categories: NHibernate

Just a reminder: my NHibernate course will be held from April 4th to the 6th in Belgium, and you can still register. You'll not only learn a lot about what NHibernate can do, you'll learn how to use it wisely. The format of the course will be pretty hands-on, meaning that there are plenty of exercises for you to complete. Theory and exercises will be mixed constantly throughout the day, at a rather rapid pace so you won't get a chance to get bored. In fact, i challenge you to get bored during the course! :P

This is the agenda for the course:

Day 1:

  • Quick ORM Introduction
  • Configuration
  • Classes & Mapping (hbm & fluent-nhibernate)
    • Entities
    • One-to-many associations
    • Many-to-one associations
    • Inheritance
  • Session/Transaction Management
    • In web applications
    • In service layers
  • Transitive Persistence
    • Transient & Persistent Entities
    • Cascades
    • Detached Entities

Day 2:

  • Querying
    • HQL
    • Criteria
    • QueryOver
    • LINQ
    • Polymorphic Queries
    • Named Queries
  • Performance Optimizations
    • Paging
    • Projections
    • Future Queries
    • Batching DML statements
    • Executable HQL (deletes/updates)
    • Stored Procedures/Views
    • Using native SQL
  • Optimistic Concurrency strategies
  • Pessimistic Locking

Day 3:

  • Identifier strategies
  • Inheritance strategies
  • Advanced mappings
    • Value type collections
    • Components
    • Component collections
    • (composite) User Types
    • Many-to-Many associations
    • Polymorphic associations
  • 2nd Level cache
    • Caching entities
    • Caching collections
    • Caching queries
  • Stateless Sessions

(Sorry for this shameless plug, but you'd do it too if you were me :) )

Why We’re Going With HTML(5) Instead Of Silverlight

142 commentsWritten on March 6th, 2011 by
Categories: ASP.NET MVC, Silverlight

I recently had to research which UI technology would be the best choice for the applications that my client is going to build in the next couple of years. This is a .NET shop, so there are 2 major directions you could move into: standards-based web development, or Silverlight. When you have to recommend one over the other, you ideally want to be able to back up your choice with more than just some opinions. So we made a list of candidates and did a POC for each one. Then we came up with a list of criteria, grouped in a bunch of categories. The criteria were all assigned a weight, and we scored each of them for all candidates.

In this post, i want to go over the categories of criteria, and discuss our findings. I'm also going to share the spreadsheet so you can go through the numbers yourself. Depending on your needs or your opinions, you can change the weights and the scores and see how that affects the outcome. I removed some of the criteria that were specific to my client, but it didn't have a significant impact on the outcome. For this post, I also limited the candidates to ASP.NET MVC 3 in combination with the jQuery family (jQuery Core, jQuery UI and jQuery Mobile) and Silverlight.

Here's a quick listing of the categories and some of their criteria (for the actual list, check the spreadsheet... the link is at the end of the post):

  • User experience (compelling UI, accessibility, intuitive/ease-of-use, accessible from multiple devices, accessable from multiple platforms)
  • Infrastructure (easy/flexible deployment, monitorability)
  • Security (safe from XSS, CSRF)
  • Performance (server footprint, client-side resource usage, asynchronicity, UI responsiveness, initial load times)
  • Code/Architecture (maturity, reusability of validation logic, simplicity, maintainability, flexibility, power, testability, i18n, feedback cycle, learning curve, potential efficiency, rapid application prototyping, readable URLs, extensibility)
  • People (limits the number of required skills, mindshare, documentation, community support, commercial support)
  • Strategic (future-proof, standards-compliant, differentiator, backing, vision)
  • License (do we have access to the code?)
  • Cost
  • Tools (IDE support, availability of extra tools, free 3rd party component availability, commercial 3rd party component availability

Depending on what you or your organization requires, some of these might not apply to you. Perhaps there are other criteria that you find important and that we missed. Nevertheless, i think this is a pretty comprehensive list which covers most of the factors that you need to think about when making this kind of decision.

This graph visualizes how both technologies scored, grouped by category:

I'm sure there are quite a few things about that image that surprise you. The first thing you might be thinking is "how can Silverlight score so badly when it comes to User Experience?". The answer to that is quite simple: if your users aren't using a desktop/laptop with Windows or OS X on it, there is no experience to be had at all. Users that require assistive technology are out of luck as well since accessibility support in Silverlight is still very poor. If you hold those factors into account, it really doesn't matter much that you can easily make Silverlight applications incredibly flashy (pardon the pun). Besides, most people get bored and annoyed with excessive animations rather quickly, so you're often better off not to overdo it. With that in mind, jQuery UI and HTML5 will easily meet your needs for that kind of stuff.

Another area where Silverlight scores very poorly is the strategic department. The fact that it's not standards-compliant obviously hurts a lot here, but there's more to it than that. First of all, the mobile story (again) pretty much kills it. Android and iOS don't support it. We already know it's never going to work on iOS and as long as it doesn't work on iOS, Android has no reason whatsoever to provide support because Silverlight simply isn't important in the grand scheme of things to any of the important players. Microsoft hasn't even announced a Silverlight browser plugin for WP7 yet and who knows if it will? That means that Silverlight web applications aren't usable on any mobile device right now, except for slates running a full Windows OS which looks like its only a tiny portion of the market. Secondly, despite its original tagline of "Lighting up the web", it appears that Microsoft only has about 3 scenario's in mind where it still actively pushes Silverlight: internal business applications, video streaming and native WP7 development. While internal business applications are certainly a large part of what we're going to do in the next couple of years, we're also going to build things that are available publicly and to a large variety of people. Going with Silverlight for the internal applications and HTML(5) for the public-facing applications wouldn't be very cost-efficient either since that means we have to train our developers for both cases. And it wouldn't make much sense anyway since HTML(5) is a great fit for internal business apps as well.

But, as you can see, there are areas where Silverlight scores better than ASP.NET MVC 3 with jQuery. For instance, when it comes to Tools, you can't deny the fact that Visual Studio and Blend cover a lot of ground when it comes to the whole Silverlight developer experience. At the very least, you can mostly stick to your familiar integrated environment, whereas with standards-based web development, you're likely to spend some time in Firebug or Google Chrome's developer tools instead of sticking almost entirely with Visual Studio. I personally don't mind (at all actually) to use other tools than Visual Studio, but there are quite a few .NET developers who do prefer to stick with Visual Studio. Which brings me to the People category. The biggest benefit that Silverlight has over standards-based web development is that you only need to know C# and XAML. With standards-based web development, you have to know HTML, CSS, JavaScript and the language of your server-side technology, in this case also C#. This might impact your ability to find new developers so Silverlight does have sort of an advantage there. Though i'd argue that you're better off in the long term with people who are willing to step out of their comfort zone instead of clinging to what they know. From a security point of view, Silverlight also scores better because you don't really have to worry about common issues such as XSS, CSRF and other vulnerabilities that are common in web-development.

So we have 3 categories where Silverlight scores better than ASP.NET MVC3/jQuery but that's far from sufficient to close the gap. Based on the weights we assigned to the criteria, the maximum possible score is 732. ASP.NET MVC3 with jQuery scored 568. Silverlight scored 304. Obviously, the results will vary depending on what you find important. Which is why we asked an analyst from one of those large IT research & advisory companies to give us some feedback on this. The analyst agreed entirely with our findings and our data, and confirmed that his company is recommending moving towards HTML5 to all of their customers. He even went as far as to say that Silverlight is hard to recommend, unless you're not targeting any mobile users and the applications are internal-only and you've already invested in the technology. I can't provide a link for any of this yet, but a paper about this will be published soon so i'll either link to it when it's out (if it's publicly available) or at least reference it.

I encourage anyone who is faced with the same decision to use the spreadsheet and modify it to your needs (adding more criteria, changing weights and/or scores, whatever) to see which one is the best fit for your situation. You can download the spreadsheet here.

Highly Recommended Book: REST In Practice

5 commentsWritten on March 5th, 2011 by
Categories: Architecture, Books

A couple of months ago, i knew very little about REST and Restful services. Since it was increasingly getting more attention in the developer community, i wanted to find out what it was about. Luckily for me, O'Reilly had recently released REST In Practice and when it was listed as an O'Reilly Deal Of The Day, i bought it without thinking twice. Unfortunately, i temporarily stopped reading it about halfway through because i needed to finish some other books first, but i recently picked up where i left off.

Coming from the Microsoft world were SOAP services have for a long time been the norm in most projects, it's very interesting to see what REST is all about and how these Restful services are built. If you don't know anything about REST, you might want to check out this article by Martin Fowler first. Obviously, you don't need to read that before you can read the book but it might pique your interest. The first chapter does a great job of introducing to the architecture of the Web and how the REST architectural style fits within it. After that, you're introduced to the Restbucks example, which is used throughout the book to show you how Restful services can work.

The book then gradually starts diving deeper and deeper into the implementation of the Restful services for the Restbucks example. Everything is explained very clearly, and the authors continuously show both the requests and the responses that are going over the wire to illustrate what is going on at the HTTP level, which makes it even easier to understand everything that's being discussed. After the explanations and request/response examples, there's typically a code-based example in either Java or .NET to show how you can implement these systems. After a while i just started skipping these examples entirely because i thought they didn't really bring any added benefit. Though i'm sure some people will appreciate those examples being included as well.

Another great thing about this book is that it remains very clear and easy to follow, even though it covers a lot of ground. Here's a brief overview of the things you'll see implemented in the next couple of chapters:

  • CRUD
  • Hypermedia (the engine of application state transformations)
  • Everything you need to know about caching
  • Event-driven services with Atom
  • Atom publishing
  • Security: authentication as well as authorization

After that, there's a chapter on the semantic web and microformats, which i didn't find very interesting but others likely will. The final 2 chapters make for a great conclusion of the book. First, there's a pretty extensive comparison between the benefits and drawbacks of SOAP versus REST. And finally, the last chapter covers when it makes sense to use REST and when it doesn't and ends with a recap of the major selling points of using the Web as a central building block of your architecture.

I grok the REST architectural style now, and definitely like it. If you read this book with an open mind, i'd bet you'll like it a lot as well.

Thoughts On Developer Longevity

158 commentsWritten on March 4th, 2011 by
Categories: Opinions, work/career

How many developers over 40 do you know? For quite a few of you, the answer will be 0. For those of you who do know of one or more developers over 40: how many of them are good? If you know any good developers over 40, then do yourself a favor: start picking their brain and figure out how they keep their skills sharp. Once you've done that, do us all a favor and publish it somewhere because there really aren't that many older developers that are any good in this industry.

There are 2 big reasons for this. The first is that too many developers move into management after a few years, either because that was their goal from the outset (and like it or not, many people still think that's what developers ought to strive for) or because they sorta got into management by accident. In the latter case, we're talking about good developers that kept performing well whenever they were given extra responsibilities. Before they know it, they're locked in meeting rooms the majority of their time and hardly have any time left for coding, even though some of them would probably prefer to be able to focus on coding more often. In both cases, these people cease to be active developers sooner, rather than later.

The second big reason is that a lot of long-term developers kinda start thinking they pretty much know all there is to know and stop learning new ways of solving problems, or keeping up with what the rest of the developer community is learning. They carry themselves as if they've seen it all and solved pretty much every kind of development challenge already. They keep using the same techniques and approaches for years and years, thinking "why change a winning team?". And while their solutions might work and might even work great, the implementations might be outdated and/or wasteful. At this point, the developer's value starts decreasing and will keep on decreasing for as long as the developer remains unable (for whatever reason) to keep his skills up to date.

I don't know about you, but i'm not exactly interested in either of those paths for the rest of my career. I want to keep coding for as long as i find it interesting and fun, and more importantly, i want to make sure that my skills don't become outdated. I believe i bring a lot of value to the table as a developer, and as i get older i'd like to make sure that i keep increasing the value that i bring to my customers. Not only through experience, but also by staying up to date with how the rest of the industry is developing software. The question is: how do you do that? How do you prevent becoming one of those "trust me kiddo, i've been writing code this way for 20 years and dag nabbit, it works"-veterans?

Obviously, i don't have a definitive answer because i've only been working as a developer for 8 years. But i do have a simple plan that i hope will enable me to continuously increase my value as a developer:

  1. Keep feeling stupid

    Once you think you know it all, you're pretty much done and are only harming yourself, your customers and the poor people who have the misfortune to work with you. Instead, keep reading blogs and books by people who are smarter than you, who are talking about things you don't understand. When you're reading their material and their code, you'll probably feel stupid. Which is great because those are the times when you are most open to learning new things. Keep reading until you get it, and then, start experimenting with what you've just learned. Keep doing this over and over again. In short: Keep feeling stupid, it's the only way to keep learning.

  2. Question what you know and think, all the time

    When it comes to software development, pretty much all knowledge has a limited shelf life. Everything you know right now about building software might be completely irrelevant 10 years from now. You probably don't even need half the things you know now 5 years from now. Allow me to go even further: half the things you know now might actually hurt your ability to build good software 5 years from now. Who the hell knows, right? Make sure you frequently question what you know. Every approach, pattern, practice or whatever that you like right now, needs to be revisited from time to time. Does it still make sense now? Are there any new factors in play that change the situation or the context that led me to think or feel this way? It's OK to change your mind, you know. Be especially wary if you feel the same about something for more than a year or two... you might have stopped feeling stupid, which isn't exactly a smart thing to do.

Again, i can't definitively say that this is the best approach to achieving longevity as a valuable developer, but i think i'm gonna take my chances on this.