How To Hit Back When Your Boss Uses Salary Statistics To Negotiate

You sit in a meeting with your boss, negotiating your salary.

Of course, you’re the awesome developer and feel like you should be paid 10x as much as the guy sitting next to you. You know that smart developers who gets things done are scarce, very scarce!

And yet, your boss is arguing that your salary should be X because that’s the average salary for a developer in your area, based on some crappy statistics he pulled off of a website just before the meeting.

How To Hit Back

With all the confidence you can get, you must counter argue by saying that you are not an average developer. That you think this company needs more than average people to carry out their goals and deliver products that aren’t average either. And  that he must up his game dramatically, if the negotiations should continue.

By the way…

I have a bunch of invites for Stack Overflow Careers, so if you’re interested ping me on Twitter and I’ll invite you.

Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library

Recurly is a full suite recurring payment service that lets you easily create subscription plans, billing cycles, handle customers, revenue etc.

They made payment integration dead easy with their awesome JavaScript library called Recurly.js that you can use to inject a payment form onto any page with a simple piece of JavaScript, a long with a server generated signature.

But .Net as a platform, and C# as a language is not very well supported by Recurly. They don’t event provide a client library for creating those signatures.

I needed a client library and wrote this simple class that I’ve now uploaded to Nu Get. The package is called RecurlyJS, and the source code is on GitHub.

Enjoy!

Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes

ActionFilters in ASP.NET MVC are great.

You can now easily share logic between controllers without having to inherit from a base controller, that does the common work.

I have a content heavy application that supports a set of layouts. Each layout is rendered by setting the Layout view dynamically, which I do from an ActionFilter. My ActionFilter is fully tested, but when you delegate work to an ActionFilter, you should write a test that ensures the filter is defined on the action.

Not surprisingly, this is very simple and relies on reflection (Download from Gist: https://gist.github.com/2605628):

/// <summary>
/// Verifies the controller action, contains an attribute of the specified attributeType.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="action">The action method.</param>
/// <param name="attributeType">Type of the attribute to look for.</param>
/// <returns>Returns true if the attribute was present on the action. Otherwise false.</returns>
public static bool VerifyControllerActionAttribute(this Controller controller, Func<ActionResult> action, Type attributeType)
{
    MethodInfo methodInfo = action.Method;
    object[] attributes = methodInfo.GetCustomAttributes(attributeType, true);
    return attributes.Any(a => a.GetType() == attributeType);
}

And the usage looks like this:

[TestMethod]
public void Index_ContainsTemplateLayoutAttribute()
{
    HomeController controller = new HomeController();
    bool containsAttribute = controller.VerifyControllerActionAttribute(controller.Index, typeof(TemplateLayoutAttribute));
    Assert.IsTrue(containsAttribute);
}

Need an introduction? Watch a video about unit testing ASP.NET and MVC based web apps on Vimeo, published by Typemock.

Make features obvious — forcing usage is even better

When creating software, make your features obvious.

A long time ago, Facebook introduced friendlists – a feature where you can group friends by any name you want.
Along comes Google+, and have a feature called circles that, unlike Facebook’s lists, are very obvious and an integral part of the design and workflow for when adding friends. All over the press, this is the feature they focus on claiming it has an advantage over Facebook. It seems as if they don’t know about the lists feature of Facebook, which makes it very important to focus on the features you need and make them obvious.
People use what they can see, and what they’re forced to use.
It also makes you think about the countless times, when someone says “I hate the bla bla bla” – and most technical minded people just says, “you can turn it off”. This is a typical response, but the problem might be that the defaults are incorrect.

ASP.NET MVC Localize Numeric (data-val-number) Validation

Another buggy experience in ASP.NET MVC. This has to do with validation, more specifically numeric validation. Whenever you have a numeric property on your view models, ASP.NET MVC automatically adds some implicit validation to ensure that whatever entered in fact is a numeric value.

Might be good in most cases, but here’s the problem. The validation mechanism writes the error messages in english. So for any app that targets a non-english audience, this needs to be changes.

But that’s easier said than done. The code in ASP.NET MVC that generates the error message for the implicit numeric validator, looks like this:

private static string MakeErrorString(string displayName) {
  // use CurrentCulture since this message is intended for the site visitor
  return String.Format(CultureInfo.CurrentCulture, MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric, displayName);
}

To make matter worse, this is a method from an internal, sealed class. They didn’t want you to change this.

The only option is to remove the validator, and get rid of the implicit validation. To be honest, I prefer to take care of validation myself, through data annotations on my view models. I don’t like when too much gets done implicitly. I want to be in control, and I want to know what is going on.

You can remove the validator in Global.asax:

foreach (ModelValidatorProvider prov in ModelValidatorProviders.Providers) {
  if (prov.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider))) {
    ModelValidatorProviders.Providers.Remove(prov);
    break;
  }
}

If you’d like to keep the numeric validation, but be able to override the error message, there’s a great way to roll your own ClientDataTypeModelValidatorProvider that does this the right way.

Things will get better

I was browsing through the source code of ASP.NET MVC 4, and found a changeset that looks like will fix this issue. In short, it will be possible to define your own ResourceClassKey, and the MVC framework will use that before using default error messages. Nice!

 

10 Ways to (re) Structure JavaScript

Structuring JavaScript can be a job in itself if you don’t look out. I was attending the virtual jQuery Summit 2011, and one of the talks were called ‘Structuring Your DOM-based Application‘ by Garann Means. Her talk really took me back to the days of fighting un-structured JavaScript.

I was working on a code base that had been maintained by a handful of different developers, each with different skills, ideas and disciplin. Web development, and especially JavaScript requires a lot of disciplin in order to keep the code clean and structured, and that just wasn’t the case at that time.

While I was watching Garann’s talk, I constantly thought of all the problems we had and what we eventually did to solve our issues and take control of our JavaScript.

This is is my 10 ideas on ways to (re) structure JavaScript, get it under control, get rid of legacy code and improve the quality of a code base.

1. Move all JavaScript code into js files

While this should be obvious for all of us, it’s just something I constantly see people don’t do. Instead of having these nice js files, JavaScript is thrown into view files.

First of all, this means that the same code is delivered to the client everytime a page is requested. Depending on the amount of JavaScript tucked into the view, this can easily add up to hundreds of kilobytes which slows down your sites load time. With JS files, you can easily cache those files on the client, save bandwidth and increase the speed of your site.

Secondly, it makes the JavaScript much more difficult to maintain. You basically can’t find what you’re looking for, it’s hard to have shared and general purpose functions that you can use from several views and you declare everything in the global scope.

2. Use closures, to avoid working in the global scope

JavaScript’s biggest problem is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the var statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.

Douglas Crockford, http://www.jslint.com/lint.html – (Global Variables paragraph)

To solve this problem, we need to wrap all of our code in closures.

A closure changes the context your code is executed within, to be inside the closure and not in the global scope. This means that all your functions and variables inside your closure is not available for others, outside the closure unless you explicitly expose them.

A closure is often referred to as an Immediately Invoked Function Expression (IFFE), and it is pretty much a function that acts as a wrapper around your code:

(function () {
  // your code here
})();

Read more about closures and IIFE’s here.

3. Improve jQuery selectors

jQuery selectors are very powerful. It’s dead easy to write selectors that gets a bunch of elements in the DOM, and they can easily get pretty advanced.

This can have an impact on the performance of your code. Running in the browser, the efficiency of your code has a direct impact on the user’s experience.

Since getElementsByClassName is not implemented by all browsers, the ones that don’t have it will suffer when you query the DOM by class class name.

That means you can speed up your jQuery selectors by specifying the tag name before the class name:

BAD: $(".price-label")

GOOD: $("span.price-label")

You can also improve performance by limiting the context in which you select. You do that by specifying a second parameter to the selector which could be a container element that you’re working inside:

var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);

4. Cache elements, instead of selecting from the DOM

Using jQuery to select elements from the DOM is expensive. Some selectors are more expensive than others, but if you’re going to use the same element multiple times in a functions, you’re better off storing it in a local variable instead of selecting it every time.

When you select an element like this: $(".price-label") it’s like having a huge swimming pool (the DOM), and telling your little brother (jQuery) to jump in and find all USD coins in there. And if you do the same on the next line of code, he has to jump in again, swim around the pool looking for USD coins.

And if the pool is junked up with loads of coins in other currencies, he has to look at each end everyone of them to determine whether or not it is a USD coin.

Some browser has a native function called getElementsByClassName, as opposed to getElementsByTagName. That does speed up the above example a little, but it is still much more effective to cache the element in a local variable.

It’s just a matter of saving an element to a local variable, and the use that in the rest of you code:

var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);

5. Get rid of HTML in JavaScript

Just like JavaScript should not be added to your HTML pages, HTML should not be generated inside JavaScript by concatenating strings.

Client side template libraries are getting more and more popular, so utilize the <script type=”text/template”></script> and embed your client side view templates there.

Or even better. Pre-compile your client side views into JavaScript using something like HoganJS, place the code in a separate file and embed that. Not only will the footprint be smaller, but you also get caching and you speed things up since they’re already compiled!

6. Upgrade jQuery

This should be a no-brainer. But code-bases get stuck on old versions for a variety of reasons. Maybe you rely on a plugin that doesn’t work with the latest version, or you use lots of deprecated stuff that would take ages to rewrite.

Plugins that are stuck on older version, and are not compatible with future versions must die! You should not hold yourself hostage due to a plugin – get rid of it, fix the error, rewrite the plugin yourself and host it on Github. Never get stuck!

Same for deprecated code. It’s a huge warning signal and you need to react!

In general, stay up to date on the project. New concepts, bug fixes and performance improvements are added all the times. Subscribe to their blog, read the release notes everytime they release a new version to get familiar with the new stuff.

7. Teach your colleagues

It is widely misunderstood, but a lot of developers tend to think of JavaScript as a language you don’t have to learn, in order to write and maintain it. I don’t know of any other language where this is the case, but loads of developers just think of JavaScript as “not real code” that “just lives in the browser”, and more or less “doesn’t matter”.

This is one of the many reasons why JavaScript gets out of control. Too many incompetent developers are writing it, and it’s a tough job to get it under control if you’re the only true JavaScript developer where you work.

First of all, tell your colleagues to watch JavaScript – The Good Parts by Douglas Crockford. This touches on what’s great and what’s bad in JavaScript, and any developer that don’t really know the language will realize that they’re doing a lot of stuff wrong.

If you have to write JavaScript – man up and learn the language.

8. Combine, compress and cache your JavaScript.

In order to increase the performance of any website, minimizing the amount of files the browser needs to download, and minimizing the size of each file is vital.

First of all, install YSlow in your browser and start examining what you have to improve.

If you haven’t optimized for fewer HTTP request, you’ll notice that’s the top thing YSlow tells you to do. Find inspiration and guidance on how to minify and optimize JavaScript and CSS files. It’s easy.

Next up is caching. First thing on this list, suggests that you should move JavaScript into js files. And this is why: Having js files, that is embedded on a page makes it really easy to cache on the client. Most webservers already sends out proper HTTP headers to allow static files, such as JavaScript to be cached on the client.

What you have to make sure, is that you’re able to bust the cache. Either use expiration headers, or add a version indicator to the URL of the file. Next time you deploy, increase that number to make it a new URL.

9. Use a Content Delivery Network – CDN

If you have lots of traffic, from all over the world. You can benefit from hosting your JavaScript files on a Content Delivery Network. With all the new cloud hosting companies out there, this has become exceptionally cheap.

For jQuery and other common libraries, you can also use the CDN hosted files provided by jQuery, Google or Microsoft.

10. Write JavaScript Unit Tests

Some people would probably say this should not be the last thing to do. But I think you need all the low-hanging fruits, that you can accomplish before you start dramatically changing the way you go about writing JavaScript. And unit testing JavaScript is going to do that.

There are several good unit testing libraries for JavaScript. The more popular are QUnit and Jasmine.

Conclusion

There’s a lot of things you can do to re-structure and get control of JavaScript. One thing is for sure. If you do nothing, things will get messy.

This was my take on what can be done, things I’ve done in the past with great success.

What do you think is missing, what have you done that greatly improved the quality of your JavaScript code-base?

JavaScript Bundling Issues When Using Unfinished Closures

We all know it’s a good idea to bundle JavaScript files into as few script includes as possible to minimize HTTP request.

And – we all know you should write your code inside closures, to avoid the biggest problem of JavaScript: its dependence on global variables!

But what happens when those two things don’t work together?

For me, they didn’t play nice with each other today. Whenever I bundled my JavaScript files i got an Uncaught TypeError: undefined is not a function.

Consider this code:

/****** a-file.js ******/
!function($) {
  // Code here
}(window.jQuery)

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");
})(window.jQuery);​

The error occurred on the first line, inside the closure in another-file.js. Take a look at this jsFiddle.

Since the result of the first closure is true, the above code will evaluate as this:

/****** a-file.js ******/
true

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");
})(window.jQuery);​

The only thing missing, is a semicolon to finish off the first closure (updated, and working jsFiddle):

/****** a-file.js ******/
!function($) {
  // Code here
}(window.jQuery);

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");   
})(window.jQuery);​

Now, this is a trivial thing to get right, if you were only dealing with your own code base. But with loads of plugins, external libraries and such – you can only pray for the best!

In my case, the script that were causing the error was Twitter Bootstrap scripts. They were all missing the semi-colon in version 2.0, the issue was submitted a month ago, and later fixed

 

ASP.NET MVC 3 Windows Authentication problem – redirects to Account/Login

ASP.NET MVC 3 has its quirkiness here and there. Sometimes it’s a lack of support for something, and other times it’s downright buggy.

An issue I came across recently, is something to do with Windows Authentication. There’s a lot of resource on the web on how to run ASP.NET MVC with Windows Authentication. There’s even a project template, the Intranet site, which ships with MVC 3. It should be a no-brainer!

The issue I came across, prevented ASP.NET from using Windows Authentication. Even though I had set authentication mode to Windows in Web.config:

<authentication mode="Windows" />
<authorization>
  <deny users="?" />
</authorization>

And disabled anonymous authentication on the website in IIS - it always redirected all requests to /Account/Login, as if it was using some sort of default Forms Authentication.

This coursed a server error – the dreaded Yellow Screen of Death, since I didn’t have a login form on my site, I had no controller/action for Account/Login.

Known issue

After searching the web for a while, I came across the release notes on the ASP.NET MVC website. At the bottom, there’s a section called ‘Known issues‘, and one of the last issues reads:

There’s a known issue that causes Forms Authentication to always redirect unauthenticated users to ~/Account/Login, ignoring the forms authentication setting used in Web.config. The workaround is to add the following app setting.

      <add key="autoFormsAuthentication" value="false" />

And much to my disappointment, this didn’t do the trick! Long story short, it turned out that I needed another setting as well, as pointed out in the comment of this Stackoverflow question:

<add key="enableSimpleMembership" value="false"/>

After adding the magic settings to my Web.config, everything worked as it should – and Windows Authentication on ASP.NET MVC is now a no-brainer!

Make CSS inline in C# and ASP.NET using PreMailer.Net

Being able to make CSS inline is something you need all the time when sending HTML e-mails. HTML E-mails simply don’t render perfectly in all e-mail clients if you don’t make all your styles inline.

Campaign Monitor introduced the ability to make CSS inline years ago, and it just works. They use the premailer Ruby project to do this, and it seems to work perfectly. You can edit your HTML e-mails using styles embedded inside the HTML document’s <head> tag, and they automatically make the CSS inline on all elements that match your selectors.

At the end of my latest blog post on How to Send HTML E-mail from an ASP.NET MVC Controller, I wrote that I’d like to combine the ActionMailer.Net library with the premailer Ruby project, to be able to send great HTML e-mails from an application, that renders well in all e-mail clients.

I honestly didn’t want to combine ASP.NET MVC with a Ruby project. I can’t image all the hacks necessary to make it work. Eventually, I’d probably start a process from ASP.NET that runs the Ruby script – but it’s still a hack in my opinion.

That made me search the .Net community to see if I could find anything similar for .Net, but I didn’t succeed. But instead I found two interesting things:

And that is exactly what it takes to make CSS inline. I added code to the CSS parser, so that it would merge the style block, if an element already had inline styles specified, and packed the two project into my own solution, called PreMailer.NET.

It works like this:

string htmlSource = File.ReadAllText(@"C:\Workspace\testmail.html");
PreMailer pm = new PreMailer();
string premailedOutput = pm.MoveCssInline(htmlSource, false);

The premailedOutput variable contains e-mail mark-up ready to send.

For more information on how to create HTML E-mails, check out the HTML E-mail Boilerplate, and Campaign Monitor’s blog, and resources section.

How to Send HTML E-mail from an ASP.NET MVC Controller

As I argued about a year ago, any modern piece of software needs to send e-mail. It needs to connect, and reach its users. Back then I showed how to send templated HTML e-mail, using the little known MailDefinition class in C#.

Today, there’s an even better approach. The main problem with the old solution, was that the templates were plain, old, flat and boring HTML templates. Any sort of dynamic content, were limited to what a simple replace could do.

The better approach that I’m using now, is the awesome ActionMailer.NET package. It’s right there within Visual Studio, if you have Nuget – which I’m sure you do.

Why is it better?

ActionMailer.NET is better, first of all because the templates for your e-mails are just regular ASP.NET MVC views. That means you can strongly type those view and supply it with a model. All the stuff you can do in an ASP.NET MVC View (Razor or WebForms – your choice) – you can now send via E-mail.

It’s very easy to use

You simply start by creating a new Controller in your ASP.NET MVC web application that will take care of sending all the e-mails. Along with the controller, you add a folder for the views.

public class MailController : MailerBase
{
    public EmailResult VerificationEmail(User model)
    {
        To.Add(model.EmailAddress);
        From = "Martin Normark <mysite@email.com>";
        Subject = "Welcome to My Blog!";


return Email("VerificationEmail", model); } }

Notice how you can set the from name, as well as the e-mail address. Neat stuff. If you want to do something just before or after an e-mail is sent, you can play around with the OnMailSending and OnMailSent by overriding the default implementation.

protected override void OnMailSending(MailSendingContext context)
{
    base.OnMailSending(context);
}

protected override void OnMailSent(System.Net.Mail.MailMessage mail)
{
    base.OnMailSent(mail);
}

Maybe you want to save the e-mail in your database for future reference, logging etc.

One thing I’ll do one day, is combine this with the premailer Ruby project, that optimizes your HTML e-mails for rendering in e-mail clients, by moving your CSS inline.