Sunday, October 13, 2013

Angular Directive VS Service usage

Angular is built from ground up keeping separation of concern, modularity and testing in mind. One of the frequently asked question in AngularJS is where to use Directives and Services.

Directives 
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM - (angularjs.org/guide/directive)

As mentioned in the definition, Directives are strictly for the DOM manipulation only. Directives are genius way to make DOM more intelligent e.g. we can create a directive which creates new element with node name as "tab" which angular at run time which resolve as HTML. This gives HTML a new meaning by creating new reusable tags and also gives us one code place to explain what tag "tab" are and easy to maintain. 

Services
A service is any functionality which can be abstracted and then called by different functions e.g. $http, $routeProvider, etc. These services are needed to be injected in the controllers or other services using them to avoid direct reference to the functions. On injecting, these services are initialized and then can be used in the code without be directly object of the function. This is good code practice as we can mock the services for the test.

Ideally, directives should be strictly used for any UI view manipulation and services are abstracted functionalities which can be mocked for unit tests. Service should not be used for any DOM manipulation or event binding.

Tuesday, October 1, 2013

Project Euler - Problem 2 in F#

Even Fibonacci numbers

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is my solution

    // Create a mutable list, so that we can add elements 
    // (this corresponds to standard .NET 'List<T>' type)
    let l = new ResizeArray<_>([1;2])
 
    let rec fabonacci a b upperLimit = 
        match ab with
            | _, _ when a + b <= upperLimit -> 
                let c = a + b
                l.Add(c)
                fabonacci b c upperLimit
            | _ -> l
 
    let sumOfEven =
        (fabonacci 1 2 4000000)
            |> List.ofSeq
            |> Seq.filter (fun x -> x % 2 = 0) 
            |> Seq.sum 

Since its dynamic seq we are creating which depends on the last two numbers, we need a mutable list which we can populate according to our need and logic. For Fibonacci, we need to have access to previous two numbers in the list to generate new one.

This solution is flexible too with the upper limit, so this logic can be used anywhere to create the Fibonacci sequence with any upper bound. First step is to create Fibonacci sequence with the upper bound and initial number to kick start the sequence.Once seq is created up to desired upper bound, we are left with filtering of the sequence for even numbers only and get their sum.

Please leave your feedback and happy coding. 

Sunday, September 29, 2013

Project Euler - Problem 1 in F#

Multiples of 3 and 5

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Here is my solution

    // Option 1
    let sumOfNoDivisbleBy3or5UnderN n = 
        [for i in 1 .. n-1 -> i]
            |> Seq.filter (fun x -> x%3 = 0 || x%5 = 0)
            |> Seq.sum
 
    let sumOfNoDivisbleBy3or5Under10 = sumOfNoDivisbleBy3or5UnderN 10
 
    let sumOfNoDivisbleBy3or5Under1000 = sumOfNoDivisbleBy3or5UnderN 1000
 
    printfn "The sum of all the multiples of 3 or 5 is %d" sumOfNoDivisbleBy3or5Under1000
 
    // Option 2
    let sumOfFilteredSeq filterCri n = 
        seq { for i in 1 .. n-1 -> if filterCri i then i else 0 }
            |> Seq.sum
 
    let filteredSeqOf3or5 = sumOfFilteredSeq (fun x -> x%3 = 0 || x%5 = 0)
 
    let sumOfNoUnder10 = filteredSeqOf3or5 10
 
    let sumOfNoUnder1000 = filteredSeqOf3or5 1000
 
    printfn "The sum of all the multiples of 3 or 5 is %d" sumOfNoUnder1000

Here i have specified two solutions. 

Options 1 is hard coded with the filter criteria and is only flexible  in changing the upper bound of the List where as option 2 is flexible in both upper bound as well as the filter criteria

Tuesday, April 10, 2012

Partial View Vs. Display/Editor Templates

ASP.net MVC provides two different options to create re-usable components
  • Partial Views
  • Display/Editor Templates
But whats the different between both of them and what advantage one has got over the other.
Difference between Display and Editor Templates: 
Display templates and Editor templates are model driven templates but only differ by the convention that display should only render read only html like divs, labels or spans etc where are editor should render editable html with forms, input controls, etc. Developers are the one whole create these templates and there is no validation which prevent us to create templates in the opposite order. It is the convention over configuration policy which drives MVC to follow a specific standardize pattern and sticking to this will ensure that no matter what you pass into Display helper method(s) will always render the same result as expected. Once we specify UIHint on any property, we instructor MVC view engine to render the respective property using given template specified either under DisplayTemplates folder or EditorTemplates folder under shared folder depending whether we want readonly mode (Html.Display) or editable mode (Html.Editor).

Sample ViewModel for the same to demonstrate how we ViewModel can be decorated with attributes to leverage templates rendering thru ViewModels in MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using ReferenceImplementation.ViewModels;
 
namespace ReferenceImplementation.ViewModels
{
    public class PersonViewModel
    {
        public string FirstName { getset; }
 
        public string LastName { getset; }
 
        [UIHint("Int")]
        public int Age { getset; }
 
        [UIHint("Date")]
        public DatetimeViewModel DateOfBirth { getset; }
 
        [UIHint("Phone")]
        public PhoneViewModel MobileNumber { getset; }
    }
}
By specifying the UIHint attribute on properties in ViewModel, we are instructing MVC to render these properties with the respective templates (depending on its display or editor reference) from the respective folder instead of using standard MVC editor.
For the view code like the one given below
<div class="readonly">@Html.DisplayFor(m => m.DateOfBirth)</div>
Since we are using Display helper method, MVC will look for the Date template under DisplayTemplates folder and  for the view code given below
<div class="editale">@Html.EditorFor(m => m.Phone)</div>
MVC will look for template under EditorTemplates folder for the Editor helper method.

Difference between Partial View and Display/Editor Templates

By convention, Partial Views are considered to be View Centeric and MVC Templates are considered to be Model Centeric. This means that templates are more dependent on the view model and way they are rendered depends a lot on their properties but same is not true for the partial view as you are more concerned in choosing the correct partial view.
Partial View differs from Templates in the way they render Id's from the ViewModels. Partial view render the element name as it is but MVC Templates adhere to model hierarchies when rendering HTML helpers. e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName".
MVC Templates are more robust and smart. If you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(=> m.CollectionOfFoo), MVC templates are smart enough to see it as a collection and render out the single display for each item as opposed to a Partial, which would require an explicit for loop.
Templates are passed with additional information that partial views are not, in particular you receive ModelMetadata, such as that created by attributes. ModelMetadata are part of ViewData which is also accessible in partial view but are null as its only populated in templates ().
Note: Templates are partials which adhere to a specific convention. The situations which make templates better or worse than old partials are almost strictly dependent on whether or not the convention is worth adherence in your application

Monday, April 9, 2012

Bundle and Minification in MVC4

What is meant by MINIFICATION?

As described in wiki ...


"Minification (also minimisation or minimization), in computer programming languages and especially JavaScript, is the process of removing all unnecessary characters from source code, without changing its functionality. These unnecessary characters usually include white space characters, new line characters, comments, and sometimes block delimiters, which are used to add readability to the code but are not required for it to execute."


This is very helpful as we can reduce the size of the javascript file to be downloaded to the client browser from the server which reduces the data to be downloaded and increases the performance


What is meant by BUNDLING?

Bundling is the process of combining all the javascript files into one file so that client browser has to make only one request to the server to download all the files in go. For example, max browser can only process 2 request at a given instance (possibly has increased with the modern browsers). If we have more number of files then they have to wait for browser to request from server once the previous requests are complete which creates delay for the page to get complete resources before it is ready. On the other hand bundling process bundle up all the js files needed to be downloaded into one and does not have to wait for the server to process other request hence increasing the performance of the application. Same can be done for the CSS files.


Bundling and minification go well together as we can reduce the size of the file by minification and bundle up all the files like js and css in there respective file types to reduce the calls to the server.


Figure 1.1 shows a page being loaded with multiple script files. Total time to download all the files and before DOM ready event is fired is 2.14s.




Figure 1.1


Figure 1.2 shows a same page being loaded but this time we are using bundling and minification for the script files. So we have reduced the number of server calls to one and file is loaded in 370ms.


Figure 1.2




Using Bundling and Minification in ASP.net MVC4


ASP.net MVC 4 comes with new feature called bundling and minification.

var mainWebStyle = new Bundle("~/Scripts/libs"typeof(JsMinify));
mainWebStyle.AddFile("~/Scripts/jquery-1.7.1.min.js");
mainWebStyle.AddFile("~/Scripts/Knockout-2.0.0.js");
BundleTable.Bundles.Add(mainWebStyle);

In the above example, we can how bundles are created. This this example, we are bundling up two js file into one lib1 file. we can also bundle all the files in one folder with the following code.

var mainWebStyle = new Bundle("~/Scripts/libs"typeof(JsMinify));
mainWebStyle.AddDirectory("~/Scripts", "*.js", false);
BundleTable.Bundles.Add(mainWebStyle);

And in the view we can refer to  bundled file like this.

<script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/libs")" type="text/javascript"></script>

Microsoft.Web.optimization help to cache the file on the clients machine and at the same time also adds a magical versioning number to the file which changes if file is changed, hence forcing the client to request for new file if file is modified and not refer to cached file on the client side.

We can also use our own minification utility if we dont like the one provided by the microsoft e.g

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;

namespace MVC4Example
{
    public class YuiJsMinify : IBundleTransform
    {
        public void Process(BundleResponse bundle)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            bundle.Content = JavaScriptCompressor.Compress(bundle.Content);
            bundle.ContentType = "text/javascript";
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;

namespace MVC4Example
{
    public class YuiCssMinify : IBundleTransform
    {
        public void Process(BundleResponse bundle)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            bundle.Content = CssCompressor.Compress(bundle.Content);
            bundle.ContentType = "text/css";
        }
    }
}


In the above example, i have used Yahoo Yui compressor dll to minify my javascript and style files instead of JsMinify and CssMinify.

Please visit the link of the presentation that Scott Gu gave in Netherlands to demo bundling and minifications and some other new features coming out in MVC 4


Happy Coding

Saturday, February 11, 2012

jQuery Google Plusify

I recently created new plugin to imitate Google Plus photo album. I will try to explain briefly how to use this plugin. For demo click here and you can also download full and minified version over here.
To start with, include minified (for production) or full version (for development) in your page.


<script type="text/javascript" src="<javascript folder path>/jquery.imagePlusify-1.0.min.js" ></script>


Place your div with width and height where you want place your albums.


<div id='plusifyPics' ></div>


Remember to set style for the div. Set your width and height to cover the area where you want to display your photo album. 


On document ready, initialize your imagePlusify and pass the options.


$(function () {
    $.AjaxGet({
        url: imgUrl,
        callback: function (data) {
            $('#plusifyPics').imagePlusify({
                backgroundColor: 'white',
                source: data,
                displayLabel: true,
                onClick: function (id, name, src) {
                    alert('you have clicked on album with id: [' + id + '] with name "' + name + '" and ' + 'it has total of ' + src.length +' images !!!');
                }
            });
        }
    });
});

Here is the list of all the options we can set in this plugin.

Property Values Additional Info
border
valid css border style
'1px solid gray' is default value
borderOnMouseOver
valid css border style
'1px solid black' is default value
padding
valid css padding size
'5px' is default value
backgroundColor
valid css color
 '#fff' is default value
displayLabel
true / false
by default its false
labelColor
valid css color for the text color
'#000' is default value
randomize
true / false
by default its true
margin
margin between the image albums
'30px' is the default value
width
album width
'200px' is the default width
height
album height
'200px' is the default height
slideBy
int distance by which images should slide
30 is the default value
source
images, name and id as source to display image albums
source can be sent in 3 ways
1. Array of string where string is url of images
2. Object with id, name and array of string as members
3 Array of object where object has id, name and array of string as members
onClick
Callback event raised on click of album
album id, album name and all images url as array are returned in the callback function.

Wednesday, January 4, 2012

Singleton Pattern


Introduction
Singleton can be defined as single instance object. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

Implementation
Singleton has one static object which is the gateway to create the instantiate the class. 

using System;

public class Singleton
{
   private static Singleton _instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (_instance == null)
         {
            _instance = new Singleton();
         }
         return _instance;
      }
   }
}

Above example has a static member, "_instance" of type Singleton class. This was _instance can be accessed anywhere in the application.
Then we have private constructor of the singleton class which means that constructor can only be accessed within the same class, hence class cannot be initiated from the outside but only from inside the same class.
We also have readonly property called "Instance" which is only entry point to the singleton class. Since _instance is static object, so once _instance object is instantiated it is for lifetime.

Singleton Vs. Static Class
There are important differences between the singleton design pattern and the static keyword on classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation. 

Static class example 
You can make a static class with the static keyword. In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages.

Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.



Singleton Static Class
you can create one instance of the object and reuse it. You cannot create the instance of static class. 
Singleton instance is created for the first time when the user requested.
Static classes- are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. 
Singleton class can implement interface
Interface cannot be implemented on static classes
Singleton class can have constructor.
Static class cannot have constructor.

Hope you enjoyed reading this post ....