Monday, November 17, 2008

Adobe Flex

Adobe Flex

This blog is extracted from my presentations that I gave one and half years ago (May 02, 2007) in my firm to introduce flex technology and make my company realize the importance of flex and its future. I am glad that my prediction made at that time about flex future was right. Rightnow flex is the hottest RIA solution in the market and its hard to find its good developer. I am also glad that there are around more than 4 project in flex that my firm is doing and it has developed good flex expertise developer during last two years that I can bet probably among few excellent flex resource in the world.

Following are the contents of the blog:

Introduction

  • Since the invent of internet and its improvement in the bandwidth endeavors were being made to develop RIA (Rich Internet Application) that would be same as desktop applications. Researches, cientist and developers (especially companies like Adobe and Microsoft) made their efforts to develop a platform that would make RIA dream a reality.
  • There comes the race among different companies for providing a platform for developing RIA. Microsoft made some serious efforts few years ago and come up with RIA and SOA based technology called “Microsoft SilverLight”. Similar effort has been made by Adobe whose outcome is in the form technology called Flex.

Successful stories

Followings are the Flex successfuly implementations:

How RIA Development Challenges resolved in Flex

  • Provide a familiar programming model: Flex provide a familiar programming model for both java and .net Programmers that is based on OOPs.
  • Leverage existing architecture: Flex provide integration with existing application servers and SOAs. So provide organization who have invested heavily on application servers and SOAs to implement RIA.
  • Support standard protocols and application programming interfaces (APIs): Flex has support for Standard Protocol and APIs like HTTP, XML and SOAP/Webservices etc. Flex provides easy integration with famous java frameworks like Hibernet, Xfire and Spring etc.
  • Follow common key design patterns: Flex provide MVC based Framework known as “Cairngorm”/"PureMVC".
  • Integrate with existing processes: Flex can be easily integrated with existing development processes like using automated build script ant for deployment etc..
  • Provide rich tooling: Flex provide rich tools.

Flex Runtime Architecture

What is Flex Programming Model?

The Flex programming model is made of:

  • MXML, an XML language used to declaratively lay out the user interface of your application.
  • ActionScript, an ECMAScript compliant, object-oriented programming model. With some syntactical differences, ActionScript looks and feels similar to Java, and supports the same object-oriented constructs: packages, classes, inheritance, interfaces, strong (but also dynamic) typing etc.
  • An extensive set of class libraries. The online API documentation is available in a Javadoc-like format.

How Flex Code is compiled?

The Flex source code (.mxml and .as files) is compiled into Flash bytecode (.swf) that is executed at the client-side by the Flash virtual machine.

There are different ways you can use the Flex compiler (mxmlc):

  • From the command line
  • As part of an ant script
  • Using FlexBuilder: the compilation process is integrated in the IDE
  • Using the web compiler (available with the Flex Data Services). This is similar to the JSP compilation model: The first time an application is requested it is compiled into bytecode, which is then cached to serve subsequent requests.

Flex product line

  • The Flex product line includes:
    • The Flex SDK which is free and includes the Flex libraries, the compiler (mxmlc), the debugger, and the documentation.
    • Flex Data Services (FDS), an optional set of server-side components deployed in your J2EE application server. FDS includes a Java RPC service, publish/subscribe messaging, and data management services. FDS is free for a single-CPU deployment (FDS Express), and is licensed per CPU when deployed on multiple CPUs.
    • FlexBuilder, an optional IDE for Flex development. Built as an Eclipse plug-in, FlexBuilder includes a design view and a code view, code hinting, visual debugging, etc. FlexBuilder is licensed on a per developer basis.
    • Optional charting components licensed on a per developer basis.
  • We can develop and deploy Flex applications entirely for free using the SDK and the IDE of our choice.

Source Code Example

Examples – 1 Fetching data from webservice

Source Code:

<?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” creationComplete=”ws.getList()”>

<mx:Style source=”main.css”/> <mx:WebService id=”ws” wsdl=”http://mysite.com/services/CatalogWS?wsdl” >

<mx:operation name=”getList”/>

</mx:WebService> <mx:Panel title=”Product Catalog”>

<mx:DataGrid width=”100%” height=”100%” dataProvider=”{ws.getList.lastResult}”>

<mx:columns> <mx:DataGridColumn dataField=”name” headerText=”Name”/> <mx:DataGridColumn dataField=”price” headerText=”Price”/> </mx:columns>

</mx:DataGrid>

</mx:Panel>

</mx:Application>

Example -2 Accessing data using Java RPC

Source Code:

MXML

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="#FFFFFF">

<mx:RemoteObject id="srv" destination="product"/> <mx:DataGrid dataProvider="{srv.getProducts.lastResult}" width="100%" height="100%"/>

<mx:Button label="Get Data" click="srv.getProducts()"/>

</mx:Application>

ProductService.java

public class ProductService {

public List getProducts() {

ArrayList list = new ArrayList(); Connection c = null;

try {

c = ConnectionHelper.getConnection(); Statement s = c.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM product ORDER BY name"); while (rs.next()) {

list.add(new Product( rs.getInt("product_id"), rs.getString("name"), rs.getString("description"), rs.getString("image"), rs.getString("category"), rs.getDouble("price")));

}

} catch (Exception e) { e.printStackTrace(); } finally { try { c.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } }

remoting-config.xml:

<?xml version="1.0" encoding="UTF-8"?>

<service id="remoting-service" class="flex.messaging.services.RemotingService"messageTypes="flex.messaging.messages.RemotingMessage">

<adapters> <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/> </adapters>

<default-channels> <channel ref="my-amf"/> </default-channels>

<destination id="product"> <properties> <source>flex.testdrive.store.ProductService</source> </properties> </destination>

<destination id="census">

<properties> <source>flex.testdrive.census.CensusService</source> </properties> </destination>

</service>

Flex 2 Tag Library for JSP:

  • The Flex 2 Tag Library for JSP is a set of JSP tags that you can use to embed Flex applications to a JSP page.

<%@ taglib uri="FlexTagLib" prefix="mm" %> <mm:mxml> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"> <% if (request.isUserInRole("admin")) { %> <AdminConsole/> <% } else { %> <UserConsole/> <% } %> </mx:Application> </mm:mxml>

Flex for Dotnet developer

WebORB for .Net

  • WebORB offers a complete native .NET implementation of Flex Remoting (RPC) and Flex Messaging and in the latest release (3.0) a partial implementation of the Flex Data Management Services capabilities.
  • Flex applications can rely on WebORB to provide functionality similar to that found in Adobe's Flex Data Services product.

How to bind Dotnet Object?

<mx:RemoteObject id="calculatorService" destination="GenericDestination" source="Weborb.Examples.BasicService" fault="gotError(event)">

<mx:method name="Calculate" result="gotCalculationResult(event)" />

</mx:RemoteObject>

Comparing Flex syntax with ASP.net

Comparing syntactical concepts of MXML and ASP.net

Asp.Net code Flex MXML code
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
<script runat="server"> void Find_onClick (Object sender, EventArgs e) { String prg = Program_txt.Text; String cat = Type_cbo.SelectedItem.Text; if (prg == "") { Message_txt.Text = "You've chosen to list everything in the " + cat + " category."; } else { Message_txt.Text = "You've chosen to search for '" + prg + "' in the " + cat + " category."; } } </script> <mx:Script> <![CDATA[ private function Find_onClick (event:Event):void { var prg:String = Program_txt.text; var cat:String = Type_cbo.selectedItem.label; if (prg == "") { Message_txt.text = "You've chosen to list everything in the " + cat + " category."; } else { Message_txt.text = "You've chosen to search for '" + prg + "' in the " + cat + " category."; } } ]]> </mx:Script>
<body> <form id="form1" runat="server"> <div align="center"> <asp:Label id="Program_lbl" runat="server" text="Program"/> <asp:TextBox id="Program_txt" runat="server"/> <asp:Label id="Type_lbl" runat="server" text="Type:"/> <asp:DropDownList id="Type_cbo" runat="server"> <asp:ListItem value="1" text="Literature" /> <asp:ListItem value=“2" text="Theater" /> <asp:ListItem value=“3" text="Visual Arts" /> </asp:DropDownList> <asp:Button id="Find_btn" runat="server" text="Find" onclick="Find_onClick" /> </div> <div align="center"> <asp:Label id="Message_txt" runat="server"/> </div> </form> <mx:VBox width="100%"> <mx:HBox width="100%" horizontalAlign="center"> <mx:Label id="Program_lbl" text="Program:"/> <mx:TextInput id="Program_txt"/> <mx:Label id="Type_lbl" text="Type:"/> <mx:ComboBox id="Type_cbo"> <mx:Array> <mx:Object data=“1" label="Literature" /> <mx:Object data=“2" label="Theater" /> <mx:Object data=“3" label="Visual Arts" /> </mx:Array> </mx:ComboBox> <mx:Button label="Find" id="Find_btn" click="Find_onClick(event)"/> </mx:HBox> <mx:HBox width="100%" horizontalAlign="center"> <mx:Label id="Message_txt"/> </mx:HBox> </mx:VBox>
Asp.net Output Flex output

More on Flex

  • There is MVC framework available in Flex called “Cairngorm”.
  • Hibernet and Spring frameworks can be used with Flex.
  • Unit testing framework is available in Flex called FlexUnit.
  • Flex can be integrated with any JSR 168 compatible portal server to develop portlets.
  • A Websphere portal page featuring five Flex-based portlets

Some queries about the technology

  • Would Adobe win RIA race against Microsoft?
    • Adobe made Flex open source. Microsoft is also planning to make Silverlight opensource.
    • Adobe is addressing large enterprise applications as well whereas Microsoft in spite of its struggle didn’t able to penetrate yet in large enterprise apps. For example Microsoft ERP solution Great Plain not warmly welcomed. On the other hand SAP is using Flex. Also Flex provides integration with Message Queue that makes it to be used with any middleware solutions.
    • Adobe has proved about its cross platform claims, whereas Microsoft past has some questions about it.
    • Microsoft Windows XP tour that is available at %SystemRoot %\system32\tourstart.exe is made in flash :)
    • According to Adobe, 97% of internet users have flash player installed in their browser.
  • Would Job market forJ2EE developer give preferences to developers having Flex skills?
    • A/c to a survey there has been an increase of 20% demand for J2EE developers having flex skills.

References:

Monday, November 3, 2008

Ruby On Rails For Java Developer

Ruby On Rails For Java Developer

In this blog I would discuss ruby on rails breifly from java developer perspective. Following are the contents of this blog:

What is Ruby on Rails?

Ruby on Rails is an open source Ruby framework for developing web-based, database-driven applications. One can develop web applications atleast ten times faster than any other typical java framework. Rails’ primary goal was to bridge the gap between PHP and J2EE by providing an extensible, reusable web framework that offered an enjoyable, productive development experience. That goal was certainly met, and Rails became more than just a web framework.

How Ruby On Rails acheive rapid development with quality?

Rails takes full advantage of Ruby programming language.

Rails use two rails guiding principles:

  • Less software Rails require developer to write few lines of code to implement application.
  • Convention over configuration Ruby On Rails put an end to verbose long XML configuration files. There is no configurations files in Rails. Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery.

What is Ruby?

Ruby is a pure object-oriented programming language. Below we will compare it with java.

Ruby for Java developer

Similiarties:

  • Memory is managed via a garbage collector.
  • Objects are strongly typed.
  • There are public, private, and protected methods.
  • There are embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc.

Differences:

  • You don’t need to compile your code. You just run it directly.
  • There are different GUI toolkits. Ruby users can try WxRuby, FXRuby, Ruby-GNOME2, or the bundled-in Ruby Tk for example.
  • You use the end keyword after defining things like classes, instead of having to put braces around blocks of code.
  • You have require instead of import.
  • All member variables are private. From the outside, you access everything via methods.
  • Parentheses in method calls are usually optional and often omitted.
  • Everything is an object.
  • Variable names are just labels. They don’t have a type associated with them.
  • There are no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
  • It’s foo = Foo.new( "hi") instead of foo = new Foo( "hi" ).
  • The constructor is always named “initialize” instead of the name of the class.
  • YAML tends to be favored over XML.
  • It’s nil instead of null.

Rails Architecture

Rails Application Structure

Following chart is above structure description:

Folder NameDescription
appHolds application specific code. This includes models, views, controllers, APIs and helpers.
componentsComponents are self-contained packages of controllers and views. These are normally utilized when there is a need to reuse a view that has associated reusable behavior.
configConfiguration files for Rails environment, URL routes and database
dbDatabase schema and migrations.
docHolds application documentation generated from RDoc.
libApplication specific libraries.
logDevelopment and production server logs.
publicThis folder is made available to the web server. It contains the dispatch scripts along with static content such as images, javascripts, stylesheets and default html files.
scriptHelper scripts for development server, automation, generation and plugin management.
testUnit, functional and integration tests along with test fixtures.
tmpTemporary directory for development server.
vendorContains plugins and external libraries the application depends on.

Rails App folder Structure

Model, View and Controller

Model:

  • Rails interacts with models through the ActiveRecord component.
  • ActiveRecord models are based on the Active Record pattern defined in Martin Fowler’s “Patterns of Enterprise Application Architecture.”
  • Active Record defines a model structure that encapsulates a row in the database and domain logic on that data.
  • The ActiveRecord component requires only the database connection information to be configured in order to work.
  • There is no need for explicit object to database mapping. ActiveRecord elicits field information directly from the database itself at startup time.
  • It is possible to have a fully functional model that just extends from the ActiveRecord::Base class.

    class Post < ActiveRecord::Base End

  • Currently, ActiveRecord supports the following 9 databases: DB2, Firebird,MySQL, OpenBase, Oracle, PostgreSQL, SQLServer, SQLite and Sybase.
  • Associations must be defined in the models themselves and those relationships follow specified naming schemes.

Views:

RHTML This is the default view for Rails applications. RHTML renders HTML based content back to a client web browser. RHTML also contains Ruby expressions that allow for programming within the view
RJS RJS templates are Ruby based javascript views. This type of view is used for asynchronous javascript calls (AJAX) made to a Rails app. RJS templates allow the view to execute javascript effects and manipulate the page where the AJAX call originated.
RXML RXML is Ruby generated XML code. It uses builder templates to easier construct an XML document to return to the client. Rails automatically returns RXML views as the XML content type.
  • All of the views in Rails are routed through a controller.
  • A controller action is responsible for passing information to a corresponding view. Any variables created in the instance of the Controller action will be made available to the view as well as application and controller specific helper functions.

    <h1>Posts</h1> <% for post in @posts %> <h2><%=post.title%></h2> <p><%=post.body%></p> <% end %>

Controller:

  • Controller take a dispatched request and decide what to do with it.
  • Controllers are responsible for interacting with the model, choosing which view to render and any redirects that take place.
  • The action is no longer a standalone class but simply a method within a controller.

    class PostsController < ActionController::Base

    def add  end def edit end def delete  end

    end

  • The default routing format to invoke one of these actions is: controller/action/id.

    class PostsController < ActionController::Base

    def show           @post = Post.find(params[:id ]) end

    End

  • By default Rails will render the corresponding view file with the same name as the action. Following is show.rhtml file

    <h1><%=@post.title %></h1> <p><%=@post.body %></p> posted by %=@post.author%

Creating Simple Application

Step 1- Creating App

Step 2- Create Database

Step 3 – Provide database connection Entry in cookbook2/config/database.YAML

# MySQL (default setup). Versions 4.1 and 5.0 are recommended.  #  # Install the MySQL driver: # gem install mysql # On MacOS X: # gem install mysql -- --include=/usr/local/lib # On Windows: # gem install mysql # Choose the win32 build. # Install MySQL and put its /bin directory on your path. # # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development:

adapter: mysql database: mydb username: root password: root host: localhost

Step 4- Generate Application

For Recipe:

For Category :

Lets Look at generated Code

Model Code:

class Category < ActiveRecord::Base end

Controller Code:

class CategoryController < ApplicationController

def show         @category = Category.find(params[:id]) end

def new         @category = Category.new end

def create

@category = Category.new(params[:category]) if @category.save

flash[:notice] = 'Category was successfully created.' redirect_to :action => 'list'

else

render :action => 'new'

end

end

End

View Code:

<h1>Editing category</h1> <% form_tag :action => 'update', :id => @category do %> <%= render :partial => 'form' %> <%= submit_tag 'Edit' %> <% end %> <%= link_to 'Show', :action => 'show', :id => @category %> | <%= link_to 'Back', :action => 'list' %> 

Step 5- Run development server

Here you go

References