Archive for

HTML5 and Javascript is not a HTML5 Javascript application

Javascript and HTML5 is in everybody’s mouth nowadays, looks like everything is around them: Node.js is wonderful and made what others tried to achieve long time ago, frameworks like knockout.js or backbone.js taught us how to develop MVVM and MVC oriented applications using javascript, jQuery is your everyday tool, and even an major operating system (Windows 8 ) announced their support for native HTML5 and Javascript to develop desktop touch friendly applications.

Javascript has emerged from a mere hacking language as a now mainstream language, now it’s common to see job offers for “javascript frontend (or UI) developers” and almost every website I’ve been involved into requires a lot of interaction using your browser… So, what’s the problem?

The problem is simple, even when we have new frameworks, new IDE’s, new paradigms for HTML and javascript applications I see that most developers still treating javascript as a hacking language, I mean, throwing lines and lines of code into the problem, without any separation or patterns or anything else, they still writing rich interactive application as HTML plus javascript, not as a HTML and javascript application.

A good application is more than code and UI, a good application should follow DRY, KISS, SOLID or whatever other acronym do you want to throw at them. HTML and Javascript applications are more than just HTML with Javascript.

Want to do something better? don’t tread Javascript as a hacking language. Period.

Provide unit test is not a guarantee of unit testing

In the last years we’ve been hearing a lot about unit testing, so much that now is in the mouth of almost every big or small software company. It’s even so common that many are so brave to say: “If you don’t provide unit tests for your code, then it’s worthless”.

Well, I would be even more brave and say: “If you provide unit tests with your code, even your templates, those test should be worth a penny”.

I found this wonderful piece of code today from a project template:

[TestClass]
public class PackageTest {
    [TestMethod]
    public void CreateInstance() {
        var package = new Walkthrough_01Package();
    }

    [TestMethod]
    public void IsIVsPackage() {
        var package = new Walkthrough_01Package();
        Assert.IsNotNull(package, "The object does not implement IVsPackage");
    }

    [TestMethod]
    public void SetSite() {
        // Create the package
        IVsPackage package = new Walkthrough_01Package();
        Assert.IsNotNull(package, "The object does not implement IVsPackage");

        // Create a basic service provider
        OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();

        // Site the package
        Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");

        // Unsite the package
        Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK");
    }
}

Ok, let’s just rewrite this test for the sake of just see how would it look like:

public class SamplePackageFacts {
    private readonly IVsPackage _package = new Walkthrough_01Package();

    [Fact]
    public void PackageCanCorrectlySetSiteFromProvider() {
        var site = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
        var answer = _package.SetSite(site);
        Assert.Equal(VSConstants.S_OK, answer);
    }

    [Fact]
    public void PackageCanCorrectlySetNullProvider() {
        var answer = _package.SetSite(null);
        Assert.Equal(VSConstants.S_OK, answer);
    }
}

Can you spot the problem? do you see any value at all in the original three tests methods?

NOTE: I used xUnit just because I like it. It’s not a problem inherited from using the test framework but from the way of look at what is a unit test, you could do exactly the same using MSTest.

Internet Explorer style limit

Today I discovered something amazing and nasty at the same time, the page looked good in any other browser but it didn’t rendered in any version of IE (9, 8, 7). After taking a look at the network traffic I discovered one of the style pages was not loaded (IE never did the proper request to the server asking for the css file). That sounds weird… I looked at the source code and the correct <link> sentence was there, then looked at the HTML structure in the IE developer tools, bam! the link was not processed.

After some research in the internet I found something amazingly nasty: Internet Explorer cannot handle more than 31 <style> sentences in a page. This applies to every version of IE (Internet Explorer 10 fixes this issue and won’t be a problem any more). This applies even with the combination of <link rel=”stylesheet” /> and <style> tags in the same page. This article by Microsoft explains that there is not only a limit for the styles defined but the rules (the article says that you cannot apply more than 4095 rules to a webpage in IE).

I found a nice blog post by John Albin (Drupal Evangelist) about the issue and looks that even using the ugly @import rule you would be limited to 993 stylesheets in the same page for Internet Explorer, ugly.

How to solve this issue? well, the easy way is simplifying your styles and using a style minizer and compressor (like the Bundler or SquishIt for ASP.NET). Lesson learned: “don’t abuse of your stylesheets”.

At least an element should be filled validation using jQuery validation

Today I got a nice client side validation request, actually was nice because was a simple and very common use case in form validation. Make sure the user fill at least one of the fields in the form before continue.

Let’s say this is the case:

The user should fill any contact detail to validate the form, sounds simple, and it is! the simple way to solve the issue is just creating a jQuery validator method then simply adding the class to the elements in the same group, using the magic of the special jQuery validator selector :filled would return the number of non empty fields in the group and it’s just matter of falsy or truly. Maybe something like this:

The only problem with this approach is the validation messages, we don’t want to see the same label error message everywhere, we just want to display the error message once. Well, just matter of specify a validation group in jQuery validation, that’s all!

See? nothing to worry about!

ASP.NET MVC3, Filter attributes and dependency injection

Today a co-worker made me a nice question regarding ASP.NET MVC3, sounds like a simple question with a simple answer, but I think it worth the blog post.

How do I inject a concern into my custom authorization attribute (or any other filter attribute) in the ASP.NET MVC3 framework?

The case is pretty simple, let’s say you have the following service and of course you are using a container to inject your dependencies

public interface ILogger {
    void Log(string message);
}

Well, let’s say that we need to use that service inside our custom attribute for logging:

public class LogAttribute : FilterAttributeProvider {
    public override void OnActionExecuting(ActionExecutingContext context) {
       // I need to use the ILogger service here!
    }
}

Well, we have two options here, the proper and the hack… let’s see the hack option first!

For the hack option we just need to use the Service Locator included with the ASP.NET MVC3 framework:

public class LogAttribute : FilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
	var log = DependencyResolver.Current.GetInstance<ILogger>();
	// do whatever you want to do here
    }
}

This probably would be one of the only two places you should use a Service Locator, and of course I don’t like it… Thanks to the guys in the ASP.NET MVC framework we have a ‘proper-like’ way to do it, using a filter provider:

The idea is simple, we have an specific special class to provide the attributes that we need to do the job, in ASP.NET MVC3 that class is an implementation of FilterAttributeFilterProvider, most container integrations already has support for it and bundle your filter provider, in this example we would use Autofac (because was the container used in that particular project).

First we need to register the needed service and the provider in your registration code (generally in your Global.asax.cs file), maybe something like this:

var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<Logger>().As<ILogger>().InstancePerHttpRequest();
builder.RegisterFilterProvider();

DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

To make this work remember to add a reference to Autofac’s MVC3 integration assembly.

Now just create a property dependency in your FilterAttribute

public class LogAttribute : FilterAttribute {
    public ILogger Log { get; set; }
    public override void OnActionExecuting(ActionExecutingContext context) {
	// Now we can use Log here!
    }
}

And well, that’s all… just matter of apply the attribute to your actions/controllers

Personally I don’t like neither of the approaches, I think attributes should be only markers, not behaviour concerns. A good implementation would be splitting the attribute in two, a marker interface and a behaviour class that would act if the attribute is present. With a little of hack this could be possible (would involve creating your own FilterProvider class that would get the present attributes and apply the correct filter attribute action to the engine, something like that)… Well, you got the point =)

As always, I’m open to suggestions and I hope this would help you my friend.

Brad Wilson has a really good blog post series about Dependency Injection and MVC3, including Filter Providers, go and give a read.

Sample solution in bitbucket https://bitbucket.org/cprieto/blogsamplecode/src/