Thursday, August 25, 2011

Yet another way programming to the Interface In JavaScript, sort of

    i have just blogged about inheritance in Javascript, so next target would be programming to the interface.     I had two approaches in mind. The first solution is making an interface as a normal object that contains properties and methods. This object will be static and remain unchanged during the lifetime of the application. The second solution is making the interface using the same way as creating the class in previous post. That means the type of the interface is also a javascript "function". And because i want to use the operator instanceOf in javascript to check whether an object is an instance of a given type so apparently, the first solution will not work. So I have only 1 option and I need to make the interface not to be initialised like a class. Obvisously, you can't create an object with just an interface definition, can you?
    Alright, an interface would have a name and a constract that contains it's members. So I will make an utility which can return a function represents our interface:
function interface(name, contract){
    var _interface = function() {
        if (this._isImplementing !== true){
            throw 'Cannot initialize interface "' + name + '"';
        }    
        
        if (name === '' || typeof name !== 'string'){
            throw 'Must provide interface name';
        }
        
        if (contract == null || typeof contract !== 'object') {
            throw 'Must provide a contract as an object';
        }
        
        this._name = name;            
        this._contract = contract;    
    };        
    return _interface;
}

    I'm using a flag _isImplementing to avoid creating instances using above function. Now I need a method similar to method "Inherit" in previous post but instead of inheriting from a class, it would implement the interface and make the class has all members of the interface's contract:
Object.defineProperty(Object.prototype, "Implement", {
    enumerable: false,
    value: function(anInterface) {        
        if (typeof (anInterface) != 'function') {
            throw 'Can implement and interface only';
        }
        if (typeof (this) != 'function') {
            throw 'Can call method on a function/class only';
        }        
        anInterface.prototype._isImplementing = true;
        this.prototype = new anInterface();
        anInterface.prototype._isImplementing = false;
        
        this.prototype.extend(this.prototype._contract);
        this.prototype._contract = null;
    }
});

    On line 14, I used method extend which just simply copies all members from the contract to "this". So the class will have all members of the contract. You can find the implementation for that method in the file I attach at the end of this post. Finally, with all those stuff ready, i can introduce the demo below:
var IPet = interface('IPet', {
    Name: '', 
    Species: '', 
    GetDescription : function() {
        console.log('function.GetDescription: ' + this.Name + ' is a ' + this.Species);
    }
});
// define a class constructor
var Cat = function(name) {
    this.Name = name;
    this.Species = 'Cat';
}
// make that class implement an interface
Cat.Implement(IPet);

// create another class inherit from the above class
var Tiger = inheritFrom(Cat);


var cat = new Cat('Garfield');
if (cat instanceof IPet) {
    console.log('cat is an instance of IPet');           // Output: cat is an instance of Ipet
}
cat.GetDescription();                                    // Output: function.GetDescription: Garfield is a Cat

var tiger = new Tiger('Tony');
tiger.Species = 'Tiger';
if (tiger instanceof Cat){
    console.log('tiger is an instance of Cat');          // Output: tiger is an instance of Cat
}
if (tiger instanceof IPet){
    console.log('tiger is also an instance of IPet');    // Output: tiger is also an instance of IPet
}
tiger.GetDescription();                                  // Output: function.GetDescription: Tony is a Tiger
 
var tryToInitializeAnInterface = new IPet();             // ERROR: Can not initialize interface "IPet"

Well, the interface should not contain implementation. In fact, I should throw "Not implemented exception" in the contract when i create the interface, and implement that in one of the top class that implements this interface. Honestly, in my real code I would be happy to do like that, but I still keep this mistake for the demo :D Again, comments are welcome!!!
Source code

Cheers

Wednesday, August 24, 2011

Yet another way for Javacript class inheritance, sort of

    Recently, I'm so interested in Node.js and i'm planning to do something cool with that new stuff. I have .NET background so i would expect I can write Javascript in OOP style or at least I want to create classes with inheritance support. Again, as usual, I did some googling :D. That leads me to following blog:
http://ejohn.org/blog/simple-javascript-inheritance/
    That is an elegant solution and it works. However, there is a drawback: you can only inherit from object not from type which i want to do. I mean if you want to create a class Pet and another class named Cat inherit from Pet, using this approach, you have to create an object name Pet and extend that pet object to make another Cat object.
    I try to find other solution and find out some magic of using Javascript prototype which leads to my solution. First, we all know that everything in Javascript is object. Second we can create a function and it would be a constructor for any desire class.
    For example, we can create a class Pet like below:
var Pet = function(name, species){
    this.Name = name;
    this.Species = species;        
};

// Define abstract method
Pet.prototype.Shout = function() {
    throw "Not implemented exception"; // Like .NET huh?
};

// and then we can create an object of type Pet:
var pet = new Pet('Scoobydoo', 'Dog');

    Alright, what we want to do is some how creating a function Dog that can create dogs inherit from Pet, dogs should also have Name and Species property.
    I notice that in javascript, we can define methods, properties for "any object" at runtime using Object.defineProperty method. This ability is like extension methods in .NET but it's cooler since we can define the extensions at runtime.
    Okey, go back, with this idea in mine, i would implement the "inherit" method like below:
Object.defineProperty(Object.prototype, "Inherit", {
    enumerable: false,
    value: function(from) {
        if (typeof (from) != 'function') {
            throw 'Can inherit from a class function only';
        }
        if (typeof (this) != 'function') {
            throw 'Can call method on a class function only';
        }
        this.prototype = new from();        
        this.prototype._base = from.prototype;
    }
});

    So I can create the Dog class function like:
var Dog = function(name) {
    Dog.prototype = new Pet(name, 'Dog');
};

// Override the abstract method
Dog.prototype.Shout = function(){
    console.log('Woof!!!');
};

    If you notice, you can see that inside the "Inherit" method, i define a property name _base. That means the new type that inherits from provided type can access the base implementation:
Dog.prototype.Bark = function() {
    this._base.Shout();
};

    Run this code will throw the "Not implemented exception" because of the Pet base method. We can redefine the Bark method to call the override Shout method:
Dog.prototype.Bark = function() {
    this.Shout();
};

    In summary, to be able to call method "Inherit" you need to defined base type, then define a derived type with a constructor and finally call this method. I would make another utility that can be reused to completly inherit from a given type include it's default constructor:
// Call this method to completely inherit from a type include the base constructor
function inheritFrom(type) {
    if (typeof (type) != 'function') {
        throw 'type must be a function';
    }
    
    // constructor with more than 3 params is not a good practice
    // in that case, param3 should be an object that contains the rest params
    var theClass = function(param1, param2, param3){
        type.call(this, param1, param2, param3);
    };    
    
    theClass.Inherit(type);
    return theClass;
}

    There is 1 interesting point about this method is that it returns a function definition which is an object in Javascript. So the overall demo would look like:
// PET: base class with a constructor require 2 params
var Pet = function(name, species){
    this.Name = name;
    this.Species = species;    
};
// Define abstract method
Pet.prototype.Shout = function() {
    throw "Not implemented exception"; // Like .NET huh?
};

// DOG: directly inherit from Pet, include constructor
var Dog = inheritFrom(Pet);
Dog.prototype.Shout = function(){
    console.log('Woof!!!');
};
Dog.prototype.Bark = function() {
    this.Shout();
};

// FISH: define another constructor which call base constructor inside, then inherit from the base type
var Fish = function(name) {
    Pet.call(this, name, 'Fish');
};
Fish.Inherit(Pet);
Fish.prototype.Shout = function(){
    console.log('!!!!!!!!!!!!!!!!!');
};


// CAT: directly inherit from Pet, include constructor
var Cat = inheritFrom(Pet);


var pet1 = new Dog('Scoobydoo', 'Dog');     // call inherit constructor
var pet2 = new Fish('Nemo');                // call custom constructor without specify species
var pet3 = new Cat('Garfield', 'Cat');      // call inherit constructor

pet1.Shout();              // Output 'Woof!!!'
pet1.Bark();               // Output 'Woof!!!'
console.log(pet1.Name);    // Output 'Scoobydoo'
console.log(pet1.Species); // Output 'Dog'


pet2.Shout();              // Output '!!!!!!!!!!!!!!!!!'
pet2.Bark();               // ERROR: Object has no method 'Bark'
console.log(pet2.Name);    // Output 'Nemo'
console.log(pet2.Species); // Output 'Fish'


pet3.Shout();              // ERROR: Not implemented exception
console.log(pet3.Name);    // Output 'Garfield'
console.log(pet3.Species); // Output 'Cat'

Cheers, comments are welcome!!!

Saturday, August 20, 2011

MVC Donut hole caching for Razor View

    I was interested with Donut caching for a while and today I have a need for the Donut hole caching or partial view caching. As many of us, I tried to find whether some smart guys had solved this problem. And it seems like Mr.Haacked had mentioned this in his post. However, that solution is for ASP.NET view engine. I have no choice and have to solve it myself. Hopefully MVC team will support this feature in next versions of MVC framework. Hmmm indeed, it could be supported in version 4: See road map.


    My idea is if a view engine renders the view's content to a stream or text writer, we can intercept that process, cache the output string to somewhere together with the view's id or what ever that can identify the view. Then next time the view is rendered, we can determine whether or not to get the content from cache or let the view engine continue it's job. So i dig into the MVC source code and find this:
public class RazorView : BuildManagerCompiledView
{
    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
    {
        //.............
    }
}
    That's exactly what i need, isn't it? We probably can create a derived class from RazorView and override above method, get the content that the text writer receive and write it directly to the writer if the view is cached. So, i need a custom text writer that could return to me what it receive :D
public class TrackableTextWriter : TextWriter
{
    private readonly TextWriter _writer;
    private StringBuilder _mem;
    public TrackableTextWriter(TextWriter writer)
    {
        _writer = writer;
        _mem = new StringBuilder();
    }
    public override Encoding Encoding
    {
        get { return _writer.Encoding; }
    }
    public override void Write(string value)
    {
        _writer.Write(value);
        _mem.Append(value);
    }
    public string GetWrittenString()
    {
        return _mem.ToString();
    }
    protected override void Dispose(bool disposing)
    {
        if (!disposing)
        {
            _writer.Dispose();           
        }
        base.Dispose(disposing);
        _mem = null;
    }
}
    Alright, now it's time to create a derived of RazorView:
public class CachableRazorView : RazorView
{
	private const string ViewCachePrefix = "ViewCache__";
    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
	{
		var appCache = viewContext.HttpContext.Cache;
		var cacheKey = ViewCachePrefix + ViewPath;
		// Check if there was a Cache config that had been fully added to the cache
		var cacheConfiguration = appCache[cacheKey] as CacheConfiguration;
		if (cacheConfiguration != null && cacheConfiguration.Data != null)
		{
			writer.Write(cacheConfiguration.Data);
			return;
		}
		var trackableTextWriter = new TrackableTextWriter(writer);
		base.RenderView(viewContext, trackableTextWriter, instance);
		
		// Cache config has just been added when the view is rendered the first time thanks to the HtmlHelper
		cacheConfiguration = appCache[cacheKey] as CacheConfiguration;
		if (cacheConfiguration != null)
		{
			var writtenString = trackableTextWriter.GetWrittenString();
			cacheConfiguration.Data = writtenString;
			appCache.Remove(cacheConfiguration.Id);
			appCache.Add(cacheConfiguration.Id,
						cacheConfiguration,
						null,
						Cache.NoAbsoluteExpiration,
						TimeSpan.FromSeconds(cacheConfiguration.Duration),
						CacheItemPriority.Default,
						null);
		}
	}
}
    Then there's of course a place we can return this custom view instead of RazorView. That's definitely the RazorViewEngine. So next step is creating our custom razor view engine:
public class CachableRazorViewEngine : RazorViewEngine
{
	protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
	{
		return new CachableRazorView(controllerContext, partialPath, null, false, FileExtensions, ViewPageActivator);
	}

	protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
	{
		return new CachableRazorView(controllerContext, viewPath, masterPath, true, FileExtensions, ViewPageActivator);
	}
}
    As usual, we need to make the web application use this view engine by modifying the globals.asax
protected void Application_Start()
{
	AreaRegistration.RegisterAllAreas();

	RegisterGlobalFilters(GlobalFilters.Filters);

	ViewEngines.Engines.Clear();
	ViewEngines.Engines.Add(new CachableRazorViewEngine());

	RegisterRoutes(RouteTable.Routes);
}
    Using this approach, the traditional OutputCache will not have value. So the idea pops in my head is making a HtmlHelper extension and calling it in the view, something like this:
@{
	Html.OutputCache(new CacheConfiguration { Duration = 10 });
}
    So here is the implementation:
public static class CacheHtmlHelperExtensions
{
	public const string ViewCachePrefix = "ViewCache__";
	public static void OutputCache(this HtmlHelper helper, CacheConfiguration cacheConfiguration)
	{
		var view = helper.ViewContext.View as BuildManagerCompiledView;
		if (view != null)
		{
			cacheConfiguration.Id = ViewCachePrefix + view.ViewPath;
			helper.ViewContext.HttpContext.Cache.Add(cacheConfiguration.Id,
													cacheConfiguration,
                                                    null,
                                                    Cache.NoAbsoluteExpiration,
                                                    TimeSpan.FromSeconds(cacheConfiguration.Duration),
                                                    CacheItemPriority.Default,
                                                    null);
		}
	}
}
    Okey, it's time to test this implementation. I put the Html.OutputCache method in the Index page of default MVC application like above. So the view will be cached in 10 seconds. If the view is not accessed in next 10 seconds, the cache engine will remove the content from the cache. However, within 10 seconds, if the view is accessed again, the cache will remain for next 10 seconds and so on. Pretty cool, huh? I need to run the performance test on this page to see the actual result. There is a very cool tool in Linux named "curl-loader" but I didn't know any for Windows. After a while searching, I found apache benchmark very similar and usefull :D. I use "ab" tool to test the web app when enable and disable the cache. The result is very interesting. Eventhough the Index page is quite simple with only text, no database access but when I enable the cache, the web server can serve 1107 requests per second when I run 10000 requests to server at concurency level at 100 compare to only 531 requests per second when I disable the cache, 2 times faster:

benchmark result

    Summary, there is a outstanding issue using this approach, the builtin output cache of ASP.NET can not be utilised. It also ignores the value of ViewModel, that's mean this implementation has not supported caching by different view model. But I think we can do it if we really need that feature. Just find a way to distinguish the different between view model values, it could be a hash code or something :D.

Source code: Razor.DonutHoleCaching.zip

Cheers