New in C# 3.0: Extension Methods

Extension methods are static methods that are callable through instance syntax. For example, we might want to add methods to IEnumerable which is one of the cornerstones of generics. (Generics were added in C# 2.0.) However, if we add operators suited for our particular case, every existing and future implementer would be required to implement those methods whether they were suited for its purpose or not. The only way to share “interface implementation” in C# is to use static methods, which is what we’ve done with the EnumerableExtensions class used previously. Let’s suppose we wanted to implement a Where method which would select a set of customers fitting a particular criterion. IN C# 3.0 we can accomplish that b y defining Where as a generic extension method. A C# 3.0 extension method will look like this:
public static IEnumerable Where( this IEnumerable items, Func predicate )
This at the first glance incomprehensible but actually simple syntax defines a Where method which can be used as follows:
IEnumerable mySetByZip = customers.Where( ZipCode == "98004" );
and/or --
IEnumerable mySetByCity = customers.Where( City == "Bellevue" );
Extension method must be declared within a static class. As in previous versions of C#, static class is one that may contain only static members and that is denoted by the static modifier on the class declaration. This declaration instructs the compiler to allow Where to be called with the same syntax as an instance method on any type that implements IEnumerable. The Where method must, however, be accessible from the current scope. As a method is in scope when the containing type is in scope, he simplest way to bring extension methods into scope is through the using directive. Extension methods simplify class design in many ways. One of the most common will probably be to provide shared interface implementations. For example, suppose you have the following interface:
interface IBell { // Bell rings by default 2 seconds ( 2,000 milliseconds). void Ring(); // However, you can set your own time in this overload: void Ring(int milliseconds); }
This interface requires that every implementer write an implementation for both overloads. With the "Orcas" version of C#, the interface can be as simple as this:
interface IRing { void Ring(int seconds); }
An extension method handling the default value can be added in another class:
static class BellExtensions { // Rings for 2 seconds public static void Ring(this IBell bell) { bell.Ring(2000); } }
The implementer of the interface need only implement a single method, but the clients of the interface may freely call either overload.

New in C# 3.0: Object Initializers

Since its introduction in 2002, C# has been work in progress. C# 2.0 introduced, among others, generic types, yield iterators, nullable types and anonymous methods. C# 3.0, which will be part of the new Visual Studio code-named Orcas, introduces several new language features. This post describes object initializers.

Object initializers allow the assignment of multiple properties or fields in a single expression. For example, a common pattern for object creation is --
WebRequest request = WebRequest.Create(myUrl); request.Timeout = 5000; request.UseDefaultCredentials = true;
There is no constructor that takes a name and address; however, there are two properties, Name and Address, that can be set once an instance is created.
Object initializers allow the same creation with the following syntax:
WebRequest request = WebRequest.Create(myUrl) { Timeout = 5000, UseDefaultCredentials = true };
(If WebRequest constructor did not require a parameter, the parentheses could be omitted.)

Initializers have clear advantage over values passed to the constructor if the set of values varies and writing a constructor overload for each possible combination is not practical.

The ?? Operator in C#

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

if (myObject == null) { myObject = new MyClass(); } return myObject;
The above code can be represented using the one-liner below.
return myObject ?? new MyClass();

Extending XSLT with Extension Objects in .NET

XSLT 2.0 is good news but .NET 2.0 supports only XSLT 1.0. Even Orcas is not going to support XSLT 2.0.
Microsoft has a good explanation for this decision. They suggest you use XQuery 1.0.
You can read about  it here.

Anyway, I needed to do some special transformations (non-trivial string/date formatting and ebcdic encoding) that are
not supported out of the box in XSLT 1.0. I decided to look for free xslt extensions and tried exslt and others. After an unsuccessful attempt at tring to setup and use them, I gave up. Instead, I resorted to  doing the special handling on the C# side, where I am more comfortable. Here is how you do it.

Using the XSLT extension feature provided by .NET, custom code can be invoked from an XSLT stylesheet.

Steps required to use the Extension Object functionality:

    * Write a class with a method that implements the special functionality.
    * Create and object of the above class and add an extension object to the XsltArgumentList class using the AddExtensionObject method.
    * Pass this XsltArgumentList object to the XslCompiledTransform.Transform method.
    * Add the namespace in the XSL stylesheet to refernce the extension objects from the stylesheet


I am pasting a sample code snippet below which implements ToUpper().

Sample XML File
   
<?xml version="1.0" encoding="utf-8" ?> <root>
<node name="node1">Hello World!</node>
</root>
Sample XSLT File
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:stringhelper="urn:StringHelper">
<xsl:output method="text" omit-xml-declaration="yes">
<xsl:template match="/">
<xsl:for-each select="//Node">
<xsl:value-of select="StringHelper:ToUpper(.)">
</xsl:value-of>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Output: HELLO WORLD!

Code
namespace XsltTest { class Program { static void Main(string[] args) { XslCompiledTransform transform = new XslCompiledTransform(); transform.Load("XSLTFile1.xslt"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("XMLFile1.xml"); FileInfo fileInfo = new FileInfo(@"output.txt"); using (StreamWriter writer = fileInfo.CreateText()) { XsltArgumentList xsltArgs = new XsltArgumentList(); xsltArgs.AddExtensionObject("urn:StringHelper", new StringHelper()); transform.Transform(xmlDoc, xsltArgs, writer); } } } // // This is the extension class. // It implements the trivial ToUpper(), // but certainly can be used for complex operations // public class StringHelper { public string ToUpper(string str) { return str.ToUpper(); } } }

Quick notes: Douglas Crockford, The JavaScript Programming Language

Douglas Crockford delivered a series of Video lectures on the most misunderstood language - JavaScript. Below you will find my quick notes:
 
JavaScript has no connection with Java and it has been named so by Netscape to collaborate with Sun to win over Microsoft. The language is loose typed meaning that there is no strict data type enforcement so an array may contain a mix of integers, strings, objects, functions, etc. Unlike Java where class keyword is used to define OOPs concepts, JavaScript uses functions and a special kind of prototype object. Primitive values in JavaScript are number (only one type), boolean, string, null and undefined. Undefined is the default value for any object. Everything else is an object. Like any other language JavaScript offers various operators and the type conversion is quite powerful. There are bitwise operators and as they are implemented in a very bad way it is recommended to avoid them. JavaScript has "for…in" statement which is used to iterate all of the members of an object. Unlike in Java, "switch" statements can have string values. JavaScript error handling is done using “try..catch..throw”  much in the same way as Java. However, as there are no classes there cannot be multiple catch statements for a single try block. Avoid using "with" statement to limit the scope of the code block. It is just ambiguous and error-prone. Scope is only defined within functions. Variables are defined using var statement. Though optional, it is important to place var in front of all variable definitions to avoid messing with global scope. Constructors (discussed later) by default return “this” object.
 
An object in JavaScript is a collection of name/value pairs. Names are strings and values can be of any type, including other objects. Every object is like a little database.  Curly braces are used to define name/values pairs with names and values separated by “:” and each pair separated by “,”.  JavaScript offers Prototypal inheritance. This type of inheritance is different from classical inheritance. There are no classes, packages or modules in JavaScript, instead functions and a special prototype object is used to achieve inheritance. Prototypal inheritance is way more dynamic and expressive. All objects inherit prototype object and is used to augment properties dynamically. For example:- 

function Rectangle (w, h) {this.width: w, this.height:h}

If we define an instance of this Rectangle function like:

var r = new Rectangle(10,2) 

r is a rectangle object with attributes width and height and dynamically Rectangle could be augmented  by

Rectangle.prototype.area = function () {return this.width* this.height} //enables object r to have area attribute.

 It is important to differentiate between classical and prototypal inheritance. In prototypal inheritance there are no rigid classes. Sub-class objects are created on existing objects using customized Douglas object function:   

 function object(o) {

    function F() {}

    F.prototype = o;

    return new F();

}

var o = new Rectangle()

var sr = new object(o) // subclass of rectangle. 

New objects can be decalred  by curly braces or “new Object ()” or “object (Object. prototype)”  as

var o = {};  // best way

var o1 = new Object();

var o2 =  object(Object.prototype); 

Members in an object could be deleted using “delete” operator.

Arrays are special types of objects. They are declared with ‘[]’. They are dynamic so there size can be increased after initialization (unlike in C). Index starts from 0 as in Java. As in other languages JavaScript provides various array utility methods. Though arrays are objects they must be used when the names are sequential integers. Like objects prototype could be used to augment array properties. 

Functions are objects. Functions can be defined both as statements and literals: 

var func = function func() {} // statement

var func = function() {} // literal

var func = function func() {}  // literal (from 1.5)

Functions can contain inner functions. Inner functions have access to variables and parameters that it is contained within. This brings to an interesting concept “Closure” where inner functions have access to outer function variables even after outer function returns. When a function is contained in an object it is known as a method. While function invocation extra parameters are ignored and missing parameters will have undefined value. There are four ways to invoke a function: 

functionObject(arguments) // function form

thisObject.methodName(arguments) // method form

new functionObject(arguments) // Constructor form

functionObject.apply(thisObject,[arguments]) // Apply form 

Though constructor form is a function invocation, it has to be preceded with “new” keyword. In order to treat constructors different it is recommended to have the first function name start with capital letter. Parameter “arguments” an array-like object is available in the function. Statement “eval” and “Function” should be used cautiously.

Avoid using global variables. Wrap the application in an anonymous function like: 

YAHOO.Trivia = function () {

    // define your common vars here

    // define your common functions here

    return {

        getNextPoser: function (cat, diff) {

            ...

        },

        showPoser: function () {

            ...

        }

    };

} ();   

(direct copy from Douglas presentation)

JavaScript is a dynamic language so there is no need for classical inheritance pattern. It is neutral on threads concept. On the client side (browser) JavaScript runs in a single thread. Coding style standards should be practiced more importantly in JavaScript as it is untyped/soft language. More information about coding conventions is available at http://javascript.crockford.com/code.html

Presentation is available at http://developer.yahoo.com/yui/theater/  titled “Douglas Crockford — "The JavaScript Programming Language".  Thanks to douglas and yahoo.

My opinions

Douglas points out many design flaws and one of the primary reasons I feel is to emulate Java features in JavaScript. Trying to borrow classical language features in a prototypal language won't work well and this including many other reasons led to confusion in the community.
Advent of Ajax made JavaScript more powerful and may fulfill yester year’s netscape dream of delivering robust/powerful applications via web browser eliminating the dependency on OS.


Class Organization in Ruby

Modules are used to organize classes in Ruby. Modules in Ruby may contain classes, functions and variables. To distinuish different class implementions with the same name, Namespaces are used -

module  Example1
  class Test
  end
end

module Example2
  class Test
  end
end

Now, Example1::Test and Example2::Test will  differentiate the 2 classes with same name. "require" keyword is used to import the source modules. The same could be achieved by "load" keyword. However "load" will import the source more than once if defined whereas "require" will ONLY  import the source once.

Ruby doesn't support multiple inheritence like Java. However, mix-ins could be used to achieve multiple-inheritence. "include" is the keyword for mix-in. Ruby's Comparable module could be included in any model with keyword 'include' and when <=> (comparable) method is overridden the model will have all the comparision methods like between, less than, greater than, etc.    

JavaScript Functions

Functions in JavaScript can be defined both as data and object methods.

Functions as Data

var b = Array.new();
b[0] = "test";
b[1] = function(x) { return x; };
b[2] = 2;

var c = b[1](b[2]);
will result c having  2 as value

Functions as Methods:

var object = { x:1, y: fucntion(p) {return p;}, z: 2 }
var c = object.y(2); will result c having  2 as value

Function literals are unnamed  like var x = function(x) {return x;}; 

Also, functions can be defined with optional arguments and varibale arguments.

optional args:
function opt_args(a,b,c) { return a;}; x = opt_args(2) will assaign x value 2

variable arguments:

function sum_of_args {
var total = 0;
for(var i=0;i<arguments.length;i++){
total += arguments[i] ;
}
return total;
}

var sum = sum_of_args(1,2);
var sum = sum_of_args(1,2,3);

A special kind of arguments identifier is used to determine the value of the arguments passed to the function. This short intro to fucntions should make you understand and write more complicated JavaScript functions.

Surya Rednuchintala

OOPS in Ruby

Encapsulation:   Everything in Ruby is an Object, even NIL (null) is an object. Classes in Ruby are defined as
                          

                           class Root
                            
                             def  initialize(param1,param2)
                                    @instance_attr1 = param1
                                    @instance_attr2  = param2
                             end
 
                              def method
                                 return @instance_attr1 + "  " + @instance_attr2
                              end
                            
                            end                             

Object is created by:  r = Root.new("sample","prog") and then r.method returns "sample prog". Instance variables are denoted using @,  Class Variables are denoted by @@ and local variables with no symbols :)
                               
 
Information Hiding
:  private, protected and public modifiers are used in classes to protect certain atributes

                         using the same above  class
                        
                         class Root
                           
                              def method1
                              end

                              def method2
                              end
                             
                              def method3
                              end
                               
                              private:  method1
                              protected: method2  
                        
                         end  

Here method1 is only available in the class scope and method2 is available for only specific object instance and by default method3 is public   
                       

Inheritance:  '<' is used for inheritance.

                     class Root
                      
                         def method1
                         end 
                        
                     end

                    class Child < Root
                    end       

Child objects inherit method1

Polymorphism:  Polymorphism is enabled by method override in the child class.

                          Class Root
                          end

                        class Child1 < Root
                            def method1
                            end
                         end     
                      
                     class Child2 < Root
                            def method1
                            end
                         end     

c = [Child1.new,Child2.new] and c[0].method1 will invoke the method defined in the child1 whereas c[1].method1 will invoke the method in Child2 class. 

Surya Renduchintala

Top 3 Cool Features of Ruby

  1. Ruby is English:
    1. 2.times do print "Ruby is English" end  - Outputs to screen "Ruby is English"  twice 
    2. print "Ruby Rocks!" if 2 != 3  -  Outputs to screen  Ruby Rocks!
    3. 2.upto(5) {|num| print num} -  Outputs to screen 2 3 4 5
    4. [1,2,3].first(2).join("-") results 1-2
  2. Terse and Efficient:
    1. [2,3,4,5].join(',') results 2,3,4,5
    2. [1,2,3,4].collect {|num| num *2} results [2,4,6,8]
    3.  print "Ruby" * 4 - Outputs to screen Ruby 4 times
    4. (1..5).to_a.each{|x| print x} - Here we are defining a range from 1 to 5, converting it to an array and then finally printing 1 2 3 4 5
  3. It is possible to define methods with code block as params. For instance, you can define a method like 

         def func
            yield(1)
         end   
         
         When invoked by "func {|num| print num}" it will output 1 to the screen. Here func is called with a code block  "{|num| print num}" and yield in the function definition passes 1 to the block which gets executed and prints 1 to the
        screen. It is also possible to store a code block in a variable and later call:
        
        print_to_screen = lambda {|x| print x}
        print_to_screen.call(1) will output 1 to the screen

        Here lambda keyword is used to store the code block and then using "call" we output 1 to the screen. 
      
Features shown are my top 3 picks but there are many more magic’s in ruby and Rails uses them to full potential to create a beautiful Web 2.0 framework.

Surya Renduchintala      

DSL: A New Way to Program

DSL which stands for Domain Specific Language is the next level of abstraction above Object Oriented Programming. Rather than working with API, framework oriented languages, DSL let’s to code in a specific domain and decrease the level of blotted code use. In the Java world we utilize DSL by describing the ANT config files. This type of approach leaves us with unnecessary config files lying around. It would be great if the same tasks could be integrated inherently into the framework/language and provide us with generic tasks. And that’s exactly what Rake does in RoR(Ruby on Rails). By default Rails provides a set of tasks (db:migrate, db: schema, db:session, etc) which are decoded and are executed appropriately. These tasks act upon specific domain (database,test,etc). Also other notable DSL in Rails is ActiveRecord. In most situations rails custom models have at max 5-10 lines of code to define the relationships and rest all find methods are dynamically made available to models. It will be a great effort to write code that writes code but this type of programming will be the next evolution as more and more development efforts focus.

YUI CSS Foundation Library

We might all have applied some hacks and tricks to make CSS work the way we desired across all A class browsers. Now yahoo has just standardized these hacks and tricks into one CSS file (reset-font-grid.css). The library can be found at http://developer.yahoo.com/yui/. They have it well documented with many examples. Although it comes with a Java Script framework you can ignore by just copying reset-font-grid.css file into your project. I have successfully implemented in one of my projects. I bet you will be glad to know about it :).

Surya          

Book Review - Ruby on Rails E-Commerce from Apress

I have a very bad impression on Apress publications. Particulary, I get bored with their same cover design on all of thier books unlike O'Reilly's interesting covers. Even tho this book got bad review in amazon I quickly gazed upon the material in one of the local  book stores and I am really suprised that it caught my attention in no time. Eventually I bought the book after few hours of reading at the store. The material was fantastic and the thing that sets it apart is the style that authors have taken in using TDD (Test Driven  Development) methodology. It may not suit for novice ppl but it certainly need to be in the bookshlef of any RoR serious developer!  Thanks Hellsten and Laine .  

Ruby on Rails - Part 2

Below are few links which helped me in understanding features of rails better

1. Introduction
2. Java Vs Rails
3. Data layer - Active Record
4. Rails Migrations
5. Ajax + Rails
6. Case Study
 
I will cover Controller, View and Integrated Testing in Rails in my next blogs.

Open Source JavaScript Libraries

JavaScript on browsers has been problematic for years, both due to the variance between browser platforms as well as the relative immaturity of the language.  However, the past few years have seen strong growth in the production of open source JavaScript frameworks that are platform independent and full featured.  These are platform independent, easily fitting within .Net, Java, or scripting based application frameworks. 

Though they have yet to displace technologies like Flash for specific behaviors, it's clear that day is coming.

Dojo ToolKit
AJAX, SVG & vector graphics support
http://dojotoolkit.org/

Scriptaculous
AJAX controls, drag and drop, animation, DOM utilities, unit testing
http://script.aculo.us/

MooTools
Compact AJAX framework, agnostic event handling, animation, used in several WebOS implementations
http://mootools.net

Yahoo! UI Library (YUI)
A set of utilities and controls for richly interactive web applications using DOM scripting, DHTML and AJAX
http://developer.yahoo.com/yui

Grails (Groovy + Rails)

Given the rise of popularity of "agile" frameworks like Ruby on Rails, one question still persists as far as their utility in large, enterprise scale applications.  For Ruby, the focus has been on quick prototyping, as well as roles where requirements aren't pushing high volumes of hits, or large numbers of transactions.  Regardless, Ruby on Rails success has inspired a number of other frameworks featuring similar methodologies and concepts.  Some of the most powerful among these are scaffolding, closures, and perhaps most importantly, dynamic methods (Meta Object Protocol).

With the latter, the run-time interpreter is able to resolve and execute dynamic service method invocations using a naming convention.  The methods actually have no explicit definition.  Rather the compiler parses the name of the method being invoked, and deduces the appropriate business logic to execute.  When establishing the service layer to access data, these method calls resolve directly to SQL statements executed against a database.  Having business logic defined solely in the name of a dynamic method is a huge win in terms of reducing effort and preventing coupling between components.

Given the power and popularity of these features, a JVM based scripting language called Groovy was adapted to the Rails model, resulting in a framework called Grails.  Several aspects of Grails have really impressed me over Ruby on Rails.  First, Grails bases its framework on established components such as Spring for MVC, and Hibernate for persistence.  Hibernate, with its support for clustering, should be enough to meet most scalability requirements.  However, the Terracotta framework is planned for integration with Grails, promising a data-grid solution that has demonstrated impressive transactional metrics.  If you haven't heard of Terracotta, please read more at:

http://terracottatech.com/

Finally, Grails is JVM technology, and can leverage existing Java classes and technologies.  Groovy script compiles directly to Java Byte Code, which eliminates the run-time interpretation associated with most scripted languages.  In a word, it's fast.  And conversely, Grails components can be leveraged by Java code, opening up many possibilities.  Here's an excerpt from The Server Side:

As one impressive example of its enterprise integration abilities, Grails let's you quickly and easily build a web application backed by your existing EJB3 entity beans. But, it doesn't stop there. Grails gives your entity beans a hearty shot of steroids, but does so completely dynamically, without altering your EJB source code in any way. Grails Object Relational Mapping (GORM) is built on Hibernate 3 (but will eventually offer support for the Java Persistence API) and uses Groovy's Meta Object Protocol (MOP) to add all sorts of handy dynamic methods to your otherwise-static entity beans. And those methods are not only accessible from Grails and Groovy; your Java code can invoke those methods as well! We suddenly have all the enterprise-level capabilities of JEE/EJB3 and the benefits of RAD web application development!

This looks like a technology to watch.  It's currently at 0.5 project maturity, but already several large production sites are using it, including PepsiCo, which went live with the 0.4 release.  They've provided a post-analysis that gives a brief synopsis on the experience.