Friday, April 29, 2011

What is Unobtrusive JavaScript?

If we look at the dictionary, the word obtrusive means "having or showing a disposition to obtrude, as by imposing onself or one's opinions on others". The synonyms are as interfering, meddlesome, etc.


Hence, unobtrusive is just the opposite of obtrusive i.e non interfering or meddlesome.
Unobtrusive Javascript as it suggest just means non-interfering or non-meddlesome javascript.

If we are able to remove the javascript from the source document and place it in an external file, then we are alomost there to say we have achieved unobtrusive javascript. The reason we stressed almost there is because "unobtrusive javascript" is a technique where we separate the behaviour layer from the presentation layer.




Monday, April 25, 2011

Javascript : Closer look at closure

Closure as defined in "Javascript closures for dummies" :
  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

Javascript : Self-invoking functions : function() { } ();

A self invoking function is one that's invoked as soon as it's declared.
They are they run immediately upon read by the browser.

Understanding this concept will help you to understand closure in javascript.

[code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        }
 [code : html]
<input type="button" value="click me" onclick="obj.pub_func();" />

If you run the above example you will probably receive an error message like " Object doesn't support property or method 'pub_func'". The reason being the object is not created yet.

Well, we have a solution to this problem in javascript in the form of "self invoking function". We will need to get the browser invoke it as soon as it is definded by insert "( );" at the end of the function.


 [code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        } ();

Tuesday, August 24, 2010

Don't get caught up with IComparable and IComparer, just implement it.

IComparable and IComparer sounds similar but don't get caught up by their name, even though they have similar names they serve different purpose.
If we want to have an ability of sorting or comparison capability for our custom objects, then we must impelment either or both of these interfaces.

Lets start by creating an object called "Employee" and add them to a list called employees.

class Employee
    {
        public string Name { get; set; }
        public int Id { get; set; }  
    }

static void Main(string[] args)
        {
            var employees = new List<Employee>();
            employees.Add(new Employee { Id = 6666, Name = "Jack" });
            employees.Add(new Employee { Id = 1111, Name = "John" });
            employees.Add(new Employee { Id = 2222, Name = "David" });
        }

Now, if your try to sort this by
employees.Sort() then you will get and exception :


InvalidOperationException was unhandled
"Failed to compare two elements in the array."
Inner Exception : {"At least one object must implement IComparable."}

In other words, the error is asking us what we mean by sorting employees.
 Well, it is clear from the exception that we need to implement the IComparable interface to be able to sort the employees list.
IComparable is used for comparing two objects of a particular type. It can be thought of as default sort provider for our objects.
Hence, we implment the IComparable as follows :
class Employee : IComparable
    {
        public string Name { get; set; }
        public int Id { get; set; }

        // Implement IComparable CompareTo method - provide default sort order.
        int IComparable.CompareTo(object obj)
        {
            Employee c = (Employee)obj;
            return String.Compare(this.Name, c.Name);

        }
    }

The IComparable requires the implementation of a method called CompareTo.

Now if you do
employees.Sort() , it will sort based on the Name.
ICompares is similar to IComparable but it can provide additional comparison mechanisms. We may want to sort our list in descending / ascending order or may want to order our object based on several fields or properties, it is all achieveable by using IComparer.

IComparer requires the implementation of the method called Compare and takes two parameters. They are two objects we are going to compare.

We can implement IComparer as follows :
class EmployeeComparer : IComparer<Employee>
    {     
        public int Compare(Employee emp1, Employee emp2)
        {
            if (emp1 == null & emp2 == null)
            {
                return 0;
            }
            else if (emp1 == null)
            {
                return -1;
            }
            else if (emp2 == null)
            {
                return 1;
            }
            else if (emp1.Id < emp2.Id)
            {
                return -1;
            }
            else if (emp1.Id == emp2.Id)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
    }


Once you have implmented the IComparer you will be able to use
employees.Sort(new EmployeeComparer());   to do you comparison.
References

http://www.aspfree.com/c/a/C-Sharp/Building-Csharp-Comparable-Objects-IComparable-versus-IComparer/2/
http://support.microsoft.com/kb/320727
http://codebetter.com/blogs/david.hayden/archive/2005/03/06/56584.aspx
http://dpatrickcaldwell.blogspot.com/2009/03/implementing-icomparer-in-c.html
http://www.c-sharpcorner.com/uploadfile/camurphy/csharplists03302006170209pm/csharplists.aspx

Monday, August 23, 2010

C# - Fibonacci and lambda expression using Func Delegate

All of us who deal with C# in day to day life must have come across Func<T, TResult> Delegate many times, where T is the type of the parameter of the method and TResult the type of the return value of the method that this delegate encapsulates.

Lets try using Func on the Fibonacci squence.
Fibonacci sequence is a sequence of the numbers where the next number is found by adding up the two numbers before it.
eg.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

  • 2 is found by adding the two numbers before it(1+1)
  • 3 is found by adding the two numbers before it(1+2)

This Fibonacci Sequence can be written as a "Rule" :
                                 The Rule is xn = xn-1 + xn-2

where:
  • xn is term number "n"
  • xn-1 is the previous term (n-1)
  • xn-2 is the term before that (n-2)
There are many ways we can write the "Fibonacci" in C#:

A.
public static int Fibonacci(int n)
        {
            int previous = -1;
            int result = 1;
            for (int i = 0; i <= n; i++)
            {
                int sum = result + previous;
                previous = result;
                result = sum;
            }
            return result;
        }
B.
static int Fibonacci (int x)
{
   if (x <= 1)
      return 1;
   return Fibonacci (x-1) + Fibonacci (x-2);
}
C. Using the .Net 3.5 we can wirte this using Func

 static void Main()
{
    Func<int, int> fib = null;
           fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

        Console.WriteLine(fib.Invoke(10));
}

Other example of Func :
static void Main()
{
    Func<int, string> funcTest = (x) => string.Format("String is = {0}", x);
}

Sunday, August 22, 2010

Protect your Data in USB via BitLocker

Out of many data encryption packages, "BitLocker" is one of them.
We all face the same problem of securing our USB drives from the prying eyes. Well, BitLocker comes with Windows 7 Ultimate edition for our rescue and it is easy to setup.
Just Right-click your USB drive select "Turn on BitLocker" and follow the easy instructions to protect your private files.

Computer - Evil Maid attack

While researching the net over the security, I came across the term "Evil Maid" attack.
So, what is the "Evil maid" attack?

Well, here's the story.
Lets assume you leave you laptop in a hotel room and go lunch/dinner. The house maid comes in to clean the room.But, she is just any ordinary house maid, while she is there she installs the boot loader and key logger, then shuts down your laptop.
You return to the hotel room, you power on your laptop, enter the passphrase, do you work.
The next day, when the maid returns, she returns, most likely to either retrieve the key and restore the previous boot loader, erasing her tracks.
Now she has access to your data, can image the drive for offline analysis and perform all sort of nasty stuffs as desired. Hence, the term "Evil Maid".