Pages

Tuesday, June 23, 2009

JavaScript Event

How to handle the event object?

JavaScript event handling is a bit incompatible between IE and other browsers. So if you have not clear picture of what the difference then it'll be difficult to write proper event handling code in javascript that will work swimmingly in different browsers. By default when an event will be fired and you have bound some event handler code to handle that event, the event object should be passed automatically to the function. Though all browser works this way, Surprisingly the IE browser works different way. IE doesn't pass the object directly rather you need to access it through window object. So in an event handler you need to write code in any of the two ways as shown below to get the event object:

        function eventHandler(e) {

            e = e || window.event;

        }

        function eventHandler(e) {

            if (!e) {

                e = window.event;

            }

        }

In the first event handler, the OR operator (||) is used to take e if e is not null. If e is null then window.event is used (for IE). In the second handler above the shorthand OR is written in more elaborately.

 

How to prevent the default behavior of an event?

Now let think you have an anchor and when user will click on the anchor you need to do some validation on client side and if the validation is passed then you want the anchor url to be navigated. If validation is not passed then you want to prevent the user to move the url. So you need to write javascript code to prevent the anchor's default behavior (will navigate to the href defined). You can do so by calling event object's preventDefault method. But IE doesn't support preventDefault. Rather you need to use returnValue.

 

        function eventHandler(e) {

            e = e || window.event;

            // Prevent the default action of an event

            if (e.preventDefault) {

                //For Non-IE

                e.preventDefault();

            } else {

                //For IE

                e.returnValue = false;

            }

        }     

 

 

Event bubbling and how to prevent it?

When an event is fired in an element in javascript DOM and the event is not handled in the element then the event is passed to the parent of the element. If the event is not handled in the parent element the event is propagate to the upper. So this is called event bubbling. There's another model called event capture. You can read more details about event model from here. For all browsers except IE we can call the event object's stopPropagation method to prevent event bubbling. But for IE, we need to set cancelBubble to true. The code snippet below shows how we can write a cross-browser compatible javascript code.

            // Stop event from bubbling up: 

            if (e.stopPropagation) {

                // W3C compliant browsers: 

                e.stopPropagation();

            } else {

                // IE: 

                e.cancelBubble = true;

            }

 

Filter event by checking the source of the event

Sometimes we need to check the source of the event. We can do so applying event delegation technique. For example we have a table of data and whenever a row is clicked, we need to handle the event. Rather than writing event handler for each of the tr/td we can write an common handler and check the source element in that event handler and take necessary actions. The technique is called event delegation. With Event delegation we can apply event handler to an element and using this as a basis for manipulating its children element. In all browsers except IE you can access the source element of the event by accessing target property of the event. For IE you need to use srcElement.

            var targetNode = e.target || e.srcElement;

            // Test if it was a TR that was clicked: 

            if (targetNode.nodeName.toLowerCase() === 'tr') {

               

            }

 

Event delegation relies on event bubbling. The above code wouldn't work if the bubbling was halted before reaching the 'table' node.

Sunday, June 21, 2009

Lambda Expression Tree

Lambda expression is parsed as tree under the hood. The lambda expression is parsed and stored as tree-shaped structure. Each node in the expression tree is represented as expression. System.Linq.Expressions.Expression class contains static factory methods that can be used to build and manipulate expression tree. The following figure shows how a simple expression is parsed and represented.

image

As the above figure shows, the expression is represented with two parameters: Body and Parameters. We had two parameters in the image above. Each parameter is of type Expression (ParameterExpression). FYI, there are several types of expressions(BinaryExpression, ConditionalExpression, ConstantExpression etc) that is derived from base Expression class. Also, Body is of type Binary Expression. So lets take an expression and dissect it.

Analyzing an Expression Tree

ay we have a function representing delegate  Func<int, bool>. The expression is:

Expression<Func<int, bool>> expressionTree =(i => i> 5);  

The expression has subparts that has shown in the image below

image

Here in the above statement we see the lambda expression takes an integer value and check if the value is greater than 5 or not and return a boolean value. The above expreesionTree variable's two property we have used in the code below. One is parameters collection and another one is Body. Parameters collection is of length one as we have only one parameter i

//This is i before the lambda expression

ParameterExpression param = expressionTree.Parameters[0] as ParameterExpression;

//this is the body of the expression, right side of lambda operator (=>). i.e., i>5

BinaryExpression  body=expressionTree.Body as BinaryExpression;

//This is the the i in the body. I.e., i on the left side of greater than

ParameterExpression left = body.Left as ParameterExpression;

//This is the constant in the body. That is 5

ConstantExpression right = body.Right as ConstantExpression;

Console.WriteLine("Docomposed Expression: {0} => {1} {2} {3}", param.Name, left.Name, body.NodeType, right.Value);

Building an Expression Tree

We can build the same expression tree that we have seen in above (for expression i=>i<5). All we need to do to generate different expressions (BinaryExpression, ConditionalExpression,ConstantExpression etc) and combine these properly into a single expression. Finally we need to compile and invoke the expression. A shown in the code snippet below, we can use Expression static methods to generate various types of expressions. we can generate a full function from that expression with Expression.Lambda method.

 

//bulild the prarameter expression

ParameterExpression param=Expression.Parameter(typeof(int),"i");

//build the constant expression

ConstantExpression constant = Expression.Constant(5, typeof(int));

//build the binary expression

BinaryExpression numLessThanAndEqual = Expression.LessThanOrEqual(param, constant);

//build the whole expression. that is body

Expression<Func<int, bool>> func = Expression.Lambda<Func<int, bool>>(numLessThanAndEqual, new ParameterExpression[] {param });

//complile the expression

Func<int,bool> compiledFounction = func.Compile();

//invoke the expression

compiledFounction.Invoke(10);

 

References

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Friday, June 19, 2009

Lambda Expression: Basic and benefits

Generally, a Lambda Expression is anonymous function that use lambda expression (=>) which is read as "goes to". The format of the lambda expression is as follows:

parameters => body

Here if number of parameters is one the parenthesis is optional. If more than one parameters are used then parameters need to inside parenthesis. Also if the number of statements in body part is one then no second bracket is needed but if number of statement is more than one then statements need to inside second bracket. In the following code snippet I have declared two delegates. One represent integer binary operation signature and another is for unary operation signature.

 

The delegate with unary integer operation signature is as follows:

delegate int DelUnary(int i);

In the above statement the delegate name is DelUnary and it taken an integer value and return an integer value.

 

The delegate with binary operation signatue is as follows which takes two integer value and return an integer value:

delegate int delBinary(int t, int x);

 

Now lets talk about unary delegate. We need two methods for incrementing and decrementing values. So we can define these two functions and assign those two functions in a variable of type DelUnary as shown below:

            DelUnary increment = x => x++;

            DelUnary decrement = x => {x--};

In the above statement we have declared an variable (increment , decrement) of type DelUnary and then we have defined the body of the methods (increment, decrement). The body start after equal sign (=). The body part (x=x++;) or (x=>x--) has two parts. The left part of lambda operator (=>) is parameter (i.e., x) and right part of the lambda expression is the method body. The body may contains multiple statements but its recommended not to be more than 2/3 lines. In case of multiple statements you need to use curly braces({}) for enclosing statements.

Now we can call the method as

            int i=0;

            Console.WriteLine(increment(i));

            Console.WriteLine(decrement(i));

 

Similarly we can declare binary functions and call them as shown below:

            delBinary multiplication = ((x, y) => x * y);

            delBinary summation = ((x, y) => x * y);

            delBinary subtraction = ((x, y) => x * y);

 

            int m = 5;

            int n = 10;

            Console.WriteLine(multiplication(m, n));

            Console.WriteLine(subtraction(m, n));

            Console.WriteLine(summation(m, n));

 

Lambda expression allows us to write small code to do more. Lets say we have a collection of names and we need to find person whose name start with "mar". So in conventional C# we write something as shown below:

 

        string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

        IList<string> foundNames= new List<string>();

        foreach (string name in names)

        {

            if (name.StartsWith("mar"))

            {

                foundNames.Add(name);

            }

        }

 

But with lambda expression we can easily shorten the above code into small and more neat form as shown below:

string[] names = { "smith", "john", "mike", "mark", "seth", "maria", "manson" };

IList<string> foundNames = names.Where(s => s.StartsWith("mar")).ToList();

Isn't that goo huh? I like this coding style very much and I have used this style in my few new projects. Believe me I'm enjoying this coding style. When I started using lambda expression for the first time it was a kind of wired stuff to me. But as I'm exploring I'm finding this really interesting and I personally believe that it will increase programmer productivity as programmer need to write lees code.

Next time I'll explain Lambda Expression Tree which is also interesting.

Wednesday, June 17, 2009

CLR and .Net Framework: Some information to share

.Net Framework 4.0 in on the way and Vance Morrison, an CLR architect has talked about the how CLR has evolved from the the very beginning to till now. With .Net Framework 2.0 CLR version 2.0 was released. But with .Net Framework 3.x the CLR version was the same, i.e., CLR version 2.0. Now with .Net Framework 4.0 CLR version 4.0 is going to be launched. So Where is CLR version 3.0? Actually this does not exists and will never exists. To keep the CLR and .Net Framework version consistent CLR is named from 2.0 to 4.0.  I have recently come to know some new information about CLR and .Net Framework that are summarized below:

We can see source code of an assembly (if it's not encrypted) with reflector. Doesn't it break intellectual property?

Reflector unveil the source code and someone raise question about intellectual property but just unveiling source code doesn't mean the everything. A successful software system is more than just source code. Successful system is composed of dev team, test team, marketing policy, support team etc

Exception Modeling in CLR need to be optimized (As  per CLR Architect Vance Morrison)

The exception modeling in .net framework need to optimized. But the problem is that this will change the way programmer works. So changing the exception modeling, exiting exception handling may not work.

String Manipulation in CLR can be optimized (As per CLR Architect Vance Morrison)

By default string in .net takes two bytes of space as this is Unicode string. But in real world most of the systems are not multilingual system and needs only ANSI characters. So this is kind of waster of resources. Also more than 25--30% of the total resources in a system is string. So reducing the string size to half we can save around 10-15% of resources. So as per Vance Morrison, he has a vision to do something to make the string types configurable so that developers can specify which string they want to use.

Interface uses may create problem from version to version

We can't add default implementation of a method in an interface. For example in a class library version 1 an interface Interface1 has two methods. But in version 2 another one method is added. The problem is that with that new version of class library the older code will break. So Microsoft is working on .net framework to provide a way to say version 2 that "hey If this new method doesn't exist then create a default method"

Why multiple inheritance is not supported in c#?

The simple question is to make the implementation easier. If a class ClassA inherited from three different base class Base1, Base 2 and Base3 and each of them has a property (i wanna say state foo) then in composite object ClassA it might be difficult to find out which foo is to be incorporated in derived class. Some programming languages like C++ has virtual concept which may solve the problem but it make the inheritance model more complex and dotnet framework did not follow the path. These problem becomes even complex with diamond problem. State(class fields) are bad in this multiple inheritance as you need to decide which state to keep in case of multiple inheritance. But multiple contracts (methods) are fine as we can call the base contract(method) from derived one with prefixing base one (say Interface1.Contract1(), Interface2.Contract1() etc). So whether to allow multiple inheritance or not was a design problem for CLR designer and they choose not to allow multiple inheritance to avoid complexity with implementation. If multiple inheritance is supported then developer had to dealt with problems like diamond problem.

Saturday, June 13, 2009

Preliminary System Requirements for SharePoint 2010

The next Office Suit Office 2010  (including Office Web applications, SharePoint Server 2010, Visio 2010 and Project 2010)  will enter a technical preview in the third quarter of 2009 and will release to manufacturing in the first half of 2010. SharePoint 2010 will be 64-bit only. So Sql server 2008/2005 64 bit is supported with SharePoint 2010. Also Supported operating system is 64-bit Windows Server 2008 or 64-bit Windows Server 2008 R2.

The main focus on this next office suit is like "Office everywhere". So it just like office application on web. The line between home and work has blurred, so people want more choice and flexibility in how, where and when they work. They’re also demanding the ability to access and effectively manage their information whether at home, at work or on the go. With next office suit familiar interface will be provided across pcs, browser and cell phone. Microsoft has got that people want the freedom to use office applications from more locations (home, office and everywhere) and on more devices.

Though Office 2007  integrated with web but Office 2010 may be the true web base office system. So is Microsoft moving from "Microsoft office" to "Microsoft Office on Web"!!!!!!!