Ph: 29779039


Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Creating custom menu in D6

Posted on August 23, 2008

WDK of Documentum 6 brings in come major enhancement for developers. The new library is Section 508 compliant and has also undergone user testing for accessibility and usability by the NFB (National Federation for the Blind). The list of new features is a big list including change to UI like right-click context menus, XML-based fixed menus that can be modified or extended, Configurable keyboard shortcuts etc. In this post we will see how to add a menu to the menu bar using configuration elements rather than extending menubar component.

In previous versions on WDK, you would have extended the menubar component and placed the xml in custom/config folder. You would also move the menubar.jsp with your new menu and menu items. In D6, things are little different. Let me quote from WDK tutorial PDF:

In earlier versions of the Web Development Kit, you would extend and override the configuration information files that come with the product as shipped. That approach still works. However, in Version 6, you have the option of modifying the user interface by adding, removing, or replacing individual configuration elements.
And this is exactly what we are going to do today. The concept of configuration elements is a great advantage to developers. By just changing XMLs you can modify the component. There is no need to extend each component for a minor change. This concept also makes the customizations more manageable and developer friendly.

WDK introduces component modification instead of extending it. To modify a specific component all you have to do is create a XML file in custom/config and specify the component you need to modify using modifies attribute of component element. Have a look at the below XML where I simply add a new menu item in tool menu of the webtop:
<config>
<scope>
<menuconfig modifies="menubar_tools_menu:webcomponent/config/library/menubar/menubar_component.xml">
<insert path="menu[name=tools_menu]">
<actionmenuitem dynamic = "genericnoselect"
name = "hello_world_menu_item"
id = "hello_world_menu_item"
value = "Hello World"
action = "hello_world_action"
showifinvalid = "true"/>
</insert>
</menuconfig>
</scope>
</config>
The XML is simple and clean. In earlier versions, you will have used the “extends” attribute and specified the component you are extending. Here we just specify the component you want to modify and specify the section (in the above case menubar_tools_menu). WDK offers five different configuration elements: insert, insertafter, insertbefore, replace and remove. You can use these elements to modify any component.

An important change to notice is the way how menu component works. If you open menubar_component.xml in /webcomponent/config/library/menubar you will notice that all the menu and menu items are declared as part of the component.In previous versions, this would have been part of the JSP. Also notice each menu is defined by the tag menuconfig. These entire menus are declared in menuconfigids element as shown below:
<menuconfigids>
<id>menubar_file_menu</id>
<id>menubar_edit_menu</id>
<id>menubar_view_menu</id>
<id>menubar_tools_menu</id>
</menuconfigids>
To add a new menu, we will have to modify the menuconfigids and our custom menu into it. Let’s see how we will insert a new menu into menuconfigids:
<component modifies="menubar:webcomponent/config/library/menubar/menubar_component.xml">
<replace path="menuconfigids">
<menuconfigids>
<id>menubar_file_menu</id>
<id>menubar_tools_menu</id>
<id>my_tools_menu</id>
</menuconfigids>
</replace>
</component>
And to define the menu and one menu item:
<menuconfig id="my_tools_menu">
<menu name="Level1" value="Level One">
<actionmenuitem dynamic = "genericnoselect"
name = "hello_world_menu_itemx"
id = "hello_world_menu_itemx"
value = "Hello World"
action = "hello_world_action"
showifinvalid = "true"/>
</menu>
</menuconfig>
So finally we have a single XML containing the above two fragments:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config version="1.0">
<scope>
<menuconfig id="my_tools_menu">
<menu name="Level1" value="Level One">
<actionmenuitem dynamic = "genericnoselect"
name = "hello_world_menu_itemx"
id = "hello_world_menu_itemx"
value = "Hello World1"
action = "hello_world_action"
showifinvalid = "true"/>
</menu>
</menuconfig>
<component modifies="menubar:webcomponent/config/library/menubar/menubar_component.xml">
<replace path="menuconfigids">
<menuconfigids>
<id>menubar_file_menu</id>
<id>menubar_tools_menu</id>
<id>my_tools_menu</id>
</menuconfigids>
</replace>
</component>
</scope>
</config>
A simple WDK refresh will make your menu appear on webtop! That's all and it's time for a hot tea :)
Read more >>

Using XSL-FO to create PDF files

Posted on June 05, 2008

Libraries like iText,PDFBox are some of the best libraries available for PDF creation and manipulation. But these libraries have its disadvantages. One such disadvantage is templating the PDFs you create. In a enterprise where reports (PDF files) are generated automatically and routed to work-flows or stored in content management repositories. These reports follow an enterprise level style and pattern which can be reused, can change and will require proper management. Hardcoding styles and formats of reports into your application can cause lots of issues in future. That's when XSL-FO and Java (or other language) come into picture. In this article I will introduce XSL-FO and Apache FOP.

Let me intoduce XSL-FO first. XSL-FO stand for Extensible Stylesheet Language Formatting Objects and is a language for formatting XML data. It was initially part of the XSL W3C recommendation. So W3C has come up with XSLT for transforming XML documents and XSL-FO for formatting. XSL-FO documents are XML files that contain information about the output layout and output contents. But they do not specify the content type of the output. This output can be any document type; all you need is a transformation library that transform the XSL-FO to the appropriate content. In this article I will make use of Apache FOP, which is part of Apache XML Graphics Project.

First look at XSL-FO:
Here is a sample XSL-FO file. Like any other XML file, its starts with XML declaration:

<?xml version="1.0" encoding="utf-8"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">

<fo:layout-master-set>
<fo:simple-page-master master-name="A4">
<fo:region-body margin="2cm" />
<fo:region-before/>
</fo:simple-page-master>
</fo:layout-master-set>

<fo:page-sequence master-reference="A4">
<fo:flow flow-name="xsl-region-body">
<fo:block>Hello World!</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
The element is the root element of XSL-FO document. contains one or more template pages and master-name attribute specify the name for the template. elements describe the page contents. contents are not directly placed, they are placed inside a flow which in turn hold block. Each block can hold the data that is displayed. For further details please go through the tutorial.

Apache FOP:
Apache FOP (Formatting Objects Processor) claims to be the first processor that reads a formatting object (FO) tree and renders the resulting pages to a specified output. The primary output format is PDF but the following formats are supported:
PDF (Portable Document Format) PS (Adobe Postscript) PCL (Printer Control Language) AFP (MO:DCA) SVG (Scalable Vector Graphics) XML (area tree representation) Print AWT/Java2D MIF RTF (Rich Text Format) TXT (text)
Using the FOP library, you will be able to process any XSL-FO and render it to PDF. The library is very simple and straight forward. Since all the details of formatting is in the XSL file, all we need is to make use of the transformation API to transform and generate the output. This content is stored as file on your file system. FOP makes use of JAXP. Have a look at the Java application to transform a simple XSL-FO document into PDF.
OutputStream outputPDF = new BufferedOutputStream(new FileOutputStream("hello.pdf"));

FopFactory ff = FopFactory.newInstance();
Fop fop = ff.newFop(MimeConstants.MIME_PDF, outputPDF);
TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = factory.newTransformer();
Source src = new StreamSource(new File("hello.fo"));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
For your reference, you may download the sample application. Like I mentioned, the main advantage will be to use XSL for formatting and designing the templates of different and simple use the API to generate the complete report. This way, all reports will have consistency and it will be easy to modify the reports style if necessary.Read more >>

Google Introduces AJAX Libraries API

Posted on May 28, 2008

With plenty of open source AJAX libraries out there (and increasing), Google has come up with the idea of host the most popular once. This will developers instant access to AJAX libraries like jQuery, Dojo etc. Web developers ; I would say mostly people who have blogs and wikis hosting on free services like blogger, wordpress etc, will now be able to use these libraries by just loading them using the new API.

AJAX Libraries API will simply help you to loading architecture for the most popular open source Java Script libraries. These libraries are hosted on Google's servers. Developers can use Google's API loader's google.load method to load the library. Presently, Google hosts the following Java Script libraries:

jQuery Dojo prototype script.aculo.us MooTools
And Google promises to keep the list growing! Google has struck a deal with all these libraries to host the latest versions as they release. But I am not sure for how long they will retain the old versions. The major advantage of using this API will be the ability to access these open source libraries even without hosting them. Also, you will be able to use features from multiple libraries in your blog or web site. I am the major reason for Google to come up this library API and hosting them is to enable these Java Script libraries to their App Engine. With these libraries at developers disposal developers will be able to embed lot of UI and client side features to the web applications they develop.

All these look good, but did Google miss somebody? Or did they ignore them? I am talking about Ext JS. Ext has been recently "hot" on web for wrong reasons! I was just wondering Google really missed them or ignored them? And I don't have to comment on YUI. I am sure, Yahoo's java script library is not going to make to the list!Polities aside; lets have look at how to use this library!

Introducing google.load() Method
Google with its vast API set, has a very simple API loading technique. To use the basic API you need to load a JS from the URL http://www.google.com/jsapi. Some API will require you to have the Google API key. But the AJAX library do not require one. Developers load the necessay Java Script files on the client side using a simple method google.load(). For example; if we need to load jQuery version 1.2.3:
<script src="http://www.google.com/jsapi"></script>
<script>
// Load jQuery
google.load("jquery", "1.2.3");
</script>

Ok, so now I have the jQuery library load. How do I use it? Google also provides a callback function which is invoked once the module (library) is loaded. The callback method is specified by google.setOnLoadCallback(myMethod) method. And finally, myMethod will have all my logic!

Trying an example!
To have a feel of the need API, I just tried out some simple tasks using jQuery. Here is the example and its source:
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.3");

google.setOnLoadCallback(function() {

$("a").click(function() {
alert("Hello world!");
});

$("#sam").click(function() {
alert("display");
$("#hidden").show();
});

});
</script>
</head>
<body>
The content begins.. <br/>
<div class="divStyle newStyle"> <a href="http://www.google.com">This</a> is a test </div> <br/>
<div id="sam"> This is another Test <div id="hidden" style="display:none">hidden text</div></div>
The content ends.. <br/>
</body>
</html>

I will give a demo on adding some useful components and widgets from these libraries later. Till then bye!
Read more >>

Using Ext JS library in Documentum

Posted on May 14, 2008

Documentum provides a very good framework for web applications called WDK. If you have worked with WDK, I am sure you must have come across the Ajax and webtop examples. When ExtJS 2.1 was released I needed to test it features, and the idea of using Ext in Documentum struck me! Here we will integrate Ext and Documentum in a simple WDK application. We will use WDK widgets to build the regural forms but add Ext Slider widget (not available in WDK) to the form.

Integrating or mashups are not always easy. As web developer we all would think that just adding the Ext java script files to the WDK application folders will be enough to get things started. But that turned out to be wrong. So lets start with troubled water.

Troubled Water
We will have few questions first and try answering them. Where will be deploy our Ext files? Where will we access Ext files from (container JSPs or our custom component JSPs)? I will answer these questions collectively. I assume you already have a skeleton WDK application on your server and I am sure you know our customizations will go into to custom folder.

We will hold all Ext related files in customjs folder under the custom folder. And as any normal WDK application, I will have my configurations in config and create appropriate JSPs. Now lets come to the second question. We will access these files from component JSP and will use complete context path to access the java script files. The reason to use complete context path is that, container JSPs access all java script files from /wdk/include folder. Now you know the folder structure, let move to programming.

Setting up Ext
Like any other Ext enabled application I will have a appjs which hold my custom Ext files. In customjs folder I have two folders : appjs and extjs. extjs will hold all the Ext library and appjs will hold our application.js file. In our application we will just be adding a slider to the Documentum form. My application.js will look like this:

app = function() {   
var sampleSlider;
var sliderClick = function(slider,event) {

sobject = document.getElementById("agetxt");
sobject.value = slider.getValue();

sobject = document.getElementById("sliderval");
sobject.value = slider.getValue();

}
return {
init:function() {
sampleSlider = new Ext.Slider({renderTo:'sample-slider',width: 200,minValue: 0,maxValue: 100});
sampleSlider.addListener('dragend',sliderClick);

}
};
}();

Note that I have simply initialized Ext.Slider object and rendered it to "sample-slider". I also have added a listener to listen clicks on the slider. We will come back to this later.

Programming you WDK component
I will just create a simple component with a JSP and a behaviour class. The JSP will have a form that will request Name, Age and a slider with which user can select a value. The user will be able to select his age using the slider. But the demo I have displayed a text field for the Age. Ideally we will not need this and we will use a hidden field to hold data. But why do we need hidden fields? In the behaviour class you will not have direct access to the Ext widgets. But you have access to all WDK widgets. This is where hidden field comes to rescue. From the behaviour class you will be able to access the values user sets using the slider. The listener methods that we attached to the slider helps in storing the slider value to the hidden field in the JSP page.

Finally on running the WDK application you will get a good looking Ext widget. You can download all the files (I have only the components, and ext js files). But you will have to build the skeleton by yourself. Let me know if you have better ideas or problems.

Read more >>

Adding Spry widgets to blogger

Posted on April 28, 2008

In my previous article I introduced you to Adobe's Spry framework for Ajax and explained its pros and cons. In this article, we will implement Spry into a blog and see how beautifully it works. Our aim will be to add an accordion in the right column. We will display a panel of badges, and widgets like Blog Rush and Feedjit in this accordion.

Spry provides widgets that are independent to one another and this makes it very easy to implement it restrictive environment. Another plus point is that your implementation of accordion is going to be very small. And the implementation is very simple. Once you have the downloaded Spry framework, you need unzip it and get hold of just two files located at \widgets\accordion. You need SpryAccordion.css and SpryAccordion.js files to build your project. If you want to make come changes, you can modify the CSS file. The file contains all the necessary style classes required for the accordion widget.

Once your custom modifications are done. Its time we move it on to the web! To host these two files, I will be using Google Pages. Many of you will be wondering why I am using Google pages and not other services that are specifically used to host files on web. The reason is, majority of these hosting services are bocked at corporate gateways and offices. I am not willing to mess up by blog when professionals access my blog. So, I will be using Google Pages. Coding a Spry widget is very simple. The accordion we are building will be represented as DIV tags. We will have a main DIV tag denoting the widget and each accordion panel will be represented as separate DIVs inside the main one. Each panel is further divided into panel heading and content. Both these parts are also denoted using DIV. So our widget code will look like this on completion:


<div class="Accordion" id="sampleAccordion" tabindex="0">
<div class="AccordionPanel">
<div class="AccordionPanelTab">Panel Heading</div>
<div class="AccordionPanelContent">
All the blog badges, images, will go in here.
I can have multiple para tags and other tag here.
</div>
</div>
<div class="AccordionPanel">
<div class="AccordionPanelTab">Panel Heading next</div>
<div class="AccordionPanelContent">
Content for Panel 2 goes here!
</div>
</div>
<div class="AccordionPanel">
<div class="AccordionPanelTab">Final</div>
<div class="AccordionPanelContent">
Content for the last accordion panel goes here!
</div>
</div>
</div>


Spry framework will not render the above code as accordion. We need to initialize the widget using Java Script. The initialization is also simple and straight forward as creating a object in Java using constructors. Have a look at how we initialize the widget:
<script language="JavaScript" type="text/javascript">
var sampleAccordion = new Spry.Widget.Accordion("sampleAccordion");
</script>

You can add this code into blogger template or use a HTML page element to hold the widget. Last modification to the blog is to add the CSS and widget JS files to the blogger template. This can be as simple as:
<link href="http://araotest.googlepages.com/SpryAccordion.css" rel="stylesheet" type="text/css" media="all" />
<script src="http://araotest.googlepages.com/SpryAccordion.js" type="text/javascript"></script>

You can see the demo on my testing blog where I build templates and test different functionalities. I am sure you will be confident enough to implement any other Spry widgets on a blog or site. Watchout for some interesting widgets to appear on my blog soon.

Read more >>

db4o : Introduction to Object Oriented Database

Posted on April 06, 2008

All computer graduates must be familiar with a paper named DBMS (where we cramp about RDBMS, relational model etc). I am sure majority of you must have come across the book “Database System Concepts” authored by Silberschartz, Korth and Sudarshan. The book has one or two chapters on Object Oriented Database which most of use just skim through or doesn’t even bother to read. Even though the book only introduces the basic concepts… it was dumped deep in memory until I found db4o.

Db4o is a open source Object Database for Java and .NET. It provides a native object database engine that can be embedded into any application. The database like many other successful open source product is dual licensed. The free version is licensed under GPL. So what’s special about db4o?

In 1990s many non-native ODBMS make into market that was unsuccessful for technical and business reasons. ODBMS stores objects directly into database but this is not what we see now. We usually use RDBMS (Oracle, MySQL or SQL Server) and our programming paradigm (OOP) does not match up with RDBMS. Industry has provided solutions to reduce the complexity. One such example is Hibernate. But using these ORM (Object-Relation Mapper) does not solve the problem completely.

We now have pure ODBMS to solve these issues. Db4o works for both Java and .NET programming environment and claims to be 55x faster than Hibernate. The database is also very small and supports features like ACID transactions, replication system, data compatibility with RDBMS and very important; easy coding. The database also provides multiple querying system, has a GUI interface (ObjectManager) where users can browse, view, read, delete objects. You will also get database tuning tools so db4o is worth a look!

I did some code to have a feel the object database and found it very simple and straight forward. Db4o provides multiple ways to query and an interesting method is Query-By-Example. When we study DBMS as a paper during graduation, we concentrate on SQL and RDBMS; I think students should have a look at ODBMS and try it along with RDBMS.

Read more >>

CRUD application using Ext and Java

Posted on March 21, 2008

Finally I have the CRUD application built on Ext and Java. CRUD stands for Create Read Update and Delete. This application will show how to build a simple but complete web application. I have used Java as my server side and Oracle XE to store my data. You can use any server side technology and persistence technology. Now let’s look at the application.

The major reason to build this web application was to make use of multiple Ext components and show how they can be used in an application. Please note that I have kept the code simple. You will find many improvements that can be made. I leave it as an exercise for you to do. The Application has three parts: Front End (Ext), server side (Java Servlets) and back end (Oracle).

The Front End:
The front end consists of a HTML page and JavaScript file. The complete application code goes into this JavaScript file. We have a main menu, forms for creating, editing and a grid view to display all the records available. The main menu is stick to the body as toolbar. I have implemented both drop down menu and normal action button to demonstrate how both of these can be implemented.

Below is a snap shot of the front-end:



The Server Side:
I work on java and love it! So my server side is Java. You may use PHP,.Net or any other of your choice. I have four Servlets create; each for my major operations. With minor tweaking, you can easily reduce the number (yet another exercise!). All these Servlets connect to Oracle XE for INSERT, SELECT, UPDATE or DELETE operations.

The Back End:
Finally the last part of the application: the back end where all the data is stored. Oracle provides its version of DB freely named Express Edition. The DB has all features available for its commercial version. But XE has some restriction like your DB size cannot exceed 2GB. But the product comes with a very good web application to do all sort of operations from admin to application building.

Our table consists of four fields: Name, Age, City and Phone number. I have not specified any primary key but for update operation I make use of name as search field. Below is the table structure:


The Code:
Enough of background! Let’s have a look at the Ext coding:



app = function() {

var createForm;
var updateForm;
var ds;
var dataGrid;
var menu;
var updateMenuItem;
var createMenuItem;
var readMenuItem;
var deleteMenuItem;
var tb;
var sm;

var onCreateClick = function() {
createForm.show();
}

var onReadClick = function() {
dataGrid.show();
ds.load({params:{start:0,limit:3,forumId: 4}});

}

var onUpdateClick = function() {
if(sm.getSelected()) {
var record = sm.getSelected();

var rname = record.get('name');
var nameComponent = updateForm.getComponent('upName');

var rage = record.get('age');
var ageComponent = updateForm.getComponent('upAge');

var rcity = record.get('city');
var cityComponent = updateForm.getComponent('upCity');

var rphone = record.get('phone');
var phoneComponent = updateForm.getComponent('upPhone');

nameComponent.setValue(rname);
ageComponent.setValue(rage);
cityComponent.setValue(rcity);
phoneComponent.setValue(rphone);

updateForm.show();
} else {
Ext.MessageBox.alert("Error!!!","Please select a record that you would like to update!
For selecting a record, click on Read and choose any record from the data grid.");
}
}

var onDeleteClick = function() {
if(sm.getSelected()) {
var record = sm.getSelected();
var rname = record.get('name');
Ext.Ajax.request({url:'DeleteAction',success: doneFunction,failure: errorFunction,params:{name:rname}});
} else {
Ext.MessageBox.alert("Error!!!","Please select a record that you would like to delete!
For selecting a record, click on Read and choose any record from the data grid.");
}
}

var saveButtonHandler = function() {
createForm.form.submit({url:'FormAction', waitMsg:'Saving Data...',success:doneFunction});
}

var updateButtonHandler = function() {
updateForm.form.submit({url:'UpdateAction', waitMsg:'Updating Data...',success:doneFunction});
}

var closeButtonHandler = function() {
createForm.hide();
}

var cancelButtonHandler = function() {
updateForm.hide();
}

var doneFunction = function(form,action) {
Ext.MessageBox.alert("Save Status","Data Saved to DB");
ds.load();
}

var errorFunction = function() {
Ext.MessageBox.alert("Error","Error Error Error ");

}

var onRowClick = function(SelectionModel,rowIndex,record) {

}

return {

init:function() {

menu = new Ext.menu.Menu();
createMenuItem = new Ext.menu.Item({text:'Create',handler:onCreateClick});
readMenuItem = new Ext.menu.Item({text:'Read',handler:onReadClick});
updateMenuItem = new Ext.menu.Item({text:'Update',handler:onUpdateClick});
deleteMenuItem = new Ext.menu.Item({text:'Delete',handler:onDeleteClick});

menu.add(createMenuItem,readMenuItem,updateMenuItem,deleteMenuItem);

tb = new Ext.Toolbar();
tb.render('menu');
tb.add({text:'Operations',menu: menu});
tb.add({text:'Create',handler: onCreateClick});
tb.add({text:'Read',handler:onReadClick});
tb.add({text:'Update',handler:onUpdateClick});
tb.add({text:'Delete',handler:onDeleteClick});

createForm = new Ext.FormPanel({applyTo:'createForm',
bodyStyle:'padding:10px',
title:'Create data record',
labelWidth:50,
items:[new Ext.form.TextField({fieldLabel:'Name',
name:'name'}),
new Ext.form.NumberField({fieldLabel:'Age',
name:'age',
width:25,
maxLength :2}),
new Ext.form.TextField({fieldLabel:'City',
name:'city'}),
new Ext.form.NumberField({fieldLabel:'Phone',
name:'phone'})
],
buttons:[{text:'Save',handler:saveButtonHandler},
{text:'Close',handler:closeButtonHandler}
]
});

ds = new Ext.data.Store({
url:'ReadToList',
reader: new Ext.data.XmlReader({record:'record'},
['name','age','city','phone'])
});

var cm = new Ext.grid.ColumnModel([{header: "Name", width:80, dataIndex: 'name',sortable: true},
{header: "Age", width: 50, dataIndex: 'age',sortable: true},
{header: "City", width: 100, dataIndex: 'city',sortable: true},
{header: "Phone", width: 100, dataIndex: 'phone',sortable: true}
]);

sm = new Ext.grid.RowSelectionModel({singleSelect:'true'});
sm.addListener('rowselect',onRowClick,this);

var tbp = new Ext.PagingToolbar({pageSize:3,store:ds,displayInfo:true});

dataGrid = new Ext.grid.GridPanel({applyTo:'readPanel',
ds:ds,
cm:cm,
sm:sm,
tbar:tbp,
title:'CRUD Data from Database'
});

updateForm = new Ext.FormPanel({applyTo:'updateForm',
bodyStyle:'padding:10px',
title:'Update data record',
labelWidth:50,
items:[new Ext.form.TextField({id:'upName',
fieldLabel:'Name',
name:'uname'}),
new Ext.form.NumberField({id:'upAge',
fieldLabel:'Age',
name:'uage',
width:25,
maxLength :2}),
new Ext.form.TextField({id:'upCity',
fieldLabel:'City',
name:'ucity'}),
new Ext.form.NumberField({id:'upPhone',
fieldLabel:'Phone',
name:'uphone'})
],
buttons:[{text:'Update',handler:updateButtonHandler},
{text:'Cancel',handler:cancelButtonHandler}
]
});
}
};
}();


Some Important points to remember for a bigger are

Form always returns JSON. Code your JSON carefully on the server side. When you return XML as your response, set the appropriate MIME.


Last Words:
You can download deployable war file or the complete Eclipse project and modify it. I also have the DDL to create the database table. Some of the improvements you can try are:
Validation to form inputs Pagination for the Grid display Display various forms using card layout or tabbed layout


Till next post: Keep Progarmming! :)
Read more >>

Getting started with Ext HtmlEditor

Posted on March 04, 2008

This is in response to the first comment I received for my previous post: All about Ext.FormPanel. My reader had requested for an example where HtmlEditor are used. And here is the response! We will learn to create forms that use the WYSIWYG editor provided by Ext.

The Basics
Ext provides developers with a good WYSIWYG editor under Ext.form.HtmlEditor. But making use of it can be bit tricky. The editor provided, is simple yet very powerful. It even has option for source editing apart from other normal options like font size, font family, colour, links etc. The library provides enough options to customize the components to user needs. Below are the important configuration options for the editor:

createLinkText – The default text for the create link prompt. defaultLinkValue – The value for the create link value. By default the value is http:// enableAlignments – Enable alignment buttons. enableColors – Enable foreground and highlight colour buttons. enableFont – Enables font selection. enableFontSize – Enables the option of increasing font size. enableFormat – Enables the formatting buttons like bold and italic. enableLinks – Enable links button. enableLists – Provides the facility to create numbered and bullet list. enableSourceEdit – Provide provision for source editing. fontFamilies – Used to specify the supported font families. This is an array of font names.

Options like enableAlignments, enableColors are boolean variables and are all set to true by default. A default for will have all the options enabled. In one way, these default values cause trouble. I will explain about the troubles soon.

Now let’s create our first HtmlEditor. Out approach will be to create a simple feedback for where will ask users to enter name, email address and suggestion. This suggestion field will be represented as a rich editor. Have a look at the code:


formObject = new Ext.form.FormPanel({applyTo:Ext.getBody(),
title:'Sample form',
bodyStyle:'padding:10px', labelWidth:60, items:[new Ext.form.TextField({id:'tf',
name:'uname', inputType:'text', fieldLabel:'Name', allowBlank:false }), new Ext.form.TextField({id:'ema', name:'email', inputType:'text', fieldLabel:'E-mail' }), new Ext.form.HtmlEditor({id:'sug', name:'suggest', fieldLabel:'Suggestion' }) ],
buttons:[{text:'Submit',handler:buttonHandler}]
});


Everything looks good and planned? On execution of this code, you will get javascript errors saying tip.register is null!!

The Trouble
We just failed in creating our form. What is the solution to this error? Another problem is that I didn’t get much help from documentation either. But later I figured out the problem was because we didn’t initialize the tool tip.

What is the relation between tool tip class and our editor? A simple fact: the buttons in editor’s tool bar make use of tool tips. We need to initialize QuickTip as follows:


Ext.QuickTips.init();


First HtmlEditor
All you need to do is initialize the QuickTip and then create the form. The tool tip initialization can be done in init method of your class. Here is the final working code:


app = function() {
var formObject;

var buttonHandler = function(button,event) {
alert('You clicked the button!');
};

return {

init:function() {

Ext.QuickTips.init();

formObject = new Ext.form.FormPanel({applyTo:Ext.getBody(),
title:'Sample form',
bodyStyle:'padding:10px',
labelWidth:60 ,
items:[
new Ext.form.TextField({id:'tf',
name:'uname',
inputType:'text',
fieldLabel:'Name',
allowBlank:false
}),
new Ext.form.TextField({id:'ema',
name:'email',
inputType:'text',
fieldLabel:'E-mail'
}),
new Ext.form.HtmlEditor({id:'sug',
name:'suggest',
fieldLabel:'Suggestion'
})
],
buttons:[{text:'Submit',handler:buttonHandler}]
});
}
};


There you go! You have your HtmlEditor and forms working smooth.

The final comments
Ext forms have lots of features and forms are important part of web application. I personally feel Ext’s documentation should provide more explanation on the form elements, submitting and load of forms.
Read more >>

All about Ext.FormPanel !

Posted on March 02, 2008

Forms are very important part of a web application. As they play a major role in date collection and manipulation, designing a fully functional form becomes a challenging task. Ext provides all necessary widget required to build complex forms in a simple way. It also has a good validation, submit and data load functionality. I will cover creating and submitting of forms.

In Ext, forms are classes derived from Panel and the library provides two ways to build a form: BasicForm and FormPanel. We will see how to build a form using FormPanel.

The Basics:
Ext provides form related class under the package Ext.form. Creating a form starts with instantiating an object of FormPanel. Like any Ext component, the constructor accepts the configuration of the component you are creating. A simple form creation will look like this:



panelObject = new Ext.form.FormPanel({applyTo:Ext.getBody(),
title:'A simple form'
});


Wait! Running this, you will end up in error!!! Even though the above code is enough to create a panel, forms need more configurations. So what is the way out? For this you need to know some of the configuration option available with Ext forms. Below are some important config options:
applyTo – Like any component, you need to specify id of the node for the component to render. autoLoad – A valid url for form to load data on render. Buttons – Specify all the buttons required for the form (Buttons can be added to bbar also). frame – Used to specify if the form needs rounded borders. id – Unique id of the component. items – A very important config. Without this there is no form! You specify all your form elements in this. labelAlign – Specify the alignment of labels of the form elements. labelWidth – Specify the width of each label.

You will find many other config options. Most of them are already available in normal form and I will skip them.

Form Elements:
You don’t have a form without form elements. Below is the list of elements you can add to a form through the items config option:

Checkbox – A simple checkbox. It also has its own configuration options, so have a look at the API. ComboBox – A combo box control with support for autocomplete, remote-loading, paging and many other features. DateField – A date input field with a date picker dropdown and automatic date validation. HtmlEditor – A lightweight HTML Editor component. NumberField – Provides a Numeric text field that provides automatic keystroke filtering and numeric validation. Radio – Provides a simple radio button. TextArea – Provides a multi line text input. TextField – Provide a simple single line text input. TimeField – Provides a time input field with a time dropdown and automatic time validation.

Now, let’s build a simple form.

First Ext form:
To complete to coding of our first form, we need to add some elements using the items config. option. In our form we will have just two elements: a text field and text area. Have a look at the code below:


panelObject = new Ext.form.FormPanel({applyTo:Ext.getBody(), title:'A simple form',
height:170,
labelWidth:60 , items:[new Ext.form.TextField({id:'tf', name:'uname', inputType:'text', fieldLabel:'Name' }), new Ext.form.TextArea({id:'ta', name:'addr', fieldLabel:'Address', height:70,
width:150 }) ], bbar:[{text:'Submit',handler:buttonHandler}]
});


In this form, there is not complexity. Please refer to documentation for options of each element so that you can configure them to your needs. An important point to note here is how elements are created in the items option. Notice that each element is instantiated and its config options passed. If you don’t use new operator, you will end up a form without the element displayed.

A design tip in forms is not to have clear button along with your submit. When users click clear, all the elements of the form is cleared. Practically users don’t clear all the fields (except for BPO and support staffs that need data cleared at end of each session) and forms should be designed in a way where users spend less time filling it.

Submitting a form:
When I created form, building them took less time when compared to learning how to submit them! But now, I will make things simple for you. You would have noticed that we didn’t specify any action url, or method to send data across to the server side.

Ext makes use of Ajax to send form data across. It uses Ext.form.Action class to submit data. An important config option that we did not include in FormPanel was URL information. This can be configured using the url attribute. The form is submitted and data transferred when you hit the submit button. The corresponding button click handler method will invoke the submit action. Have a look at our final code:


app = function() {

var formObject;

var buttonHandler = function(button,event) {
formObject.form.submit({url:'FormAction',
waitMsg:'Saving Data...',
success:doneFunction
});
};

var doneFunction = function(form,action) {
alert("success");
}

return {

init:function() {

formObject = new Ext.form.FormPanel({applyTo:Ext.getBody(), title:'Sample form', height:300, contentEl:'panel1', labelWidth:60, frame:true, collapsible:true, items:[ new Ext.form.TextField({id:'tf',
name:'uname',
allowBlank:false,
inputType:'text', fieldLabel:'Name }), new Ext.form.TextField({id:'pa', name:'password', inputType:'password', fieldLabel:'Password' }) ], buttons:[{text:'Submit',handler:buttonHandler}] });
}
};
}();


You can download the complete code and play with it. I prefer you play lot with different element to get comfortable with forms.

Wrapping up:
Like I promised, this is my second post of "All About…" series and more will come. For those who have missed, have a look at my post about Ext.Buttons. Till next post; happy programming!
Read more >>

Implementing Section 508

Posted on February 22, 2008

One fellow programmer raised this question in jGuru forum; "if a user logs-in to my web application written in PHP in Firefox, Java Script should simulate doing 'Ctrl+' so that the screen size increases". For me it sounded like implementing one of the points mentioned in Section 508. Section 508 was an amend to US congress which says electronic and information technology should be accessible to people with disabilities. Many sites like BBC have implemented this. Let have a look how we can implement one of the point in Section 508.

Here we will implement in a very small way. The solution I have provided is not complete, but you need to take it forward and modify if you need to use it in blogs or sites. For experiencing a good implementation of Section 508 check out this.

The Requirement:
As a simple statement: Provide keyboard shortcuts to increase and decrease font size in a browser. Usually sites will have button where users can select the size, font and even colour of the page’s text. In this work, we will focus on to provide button to increase and decrease font size and also provide keyboard shortcut.

Why Keyboard shortcut?
Until recently, web application never supported keyboard shortcuts. They have become famous through Gmail and Google Reader and it has been success ever since. Providing shortcuts to you web applications and web pages can improve the productivity of the user. It can also help in quick navigation. But the problem is providing a “standard” set of shortcuts which will work on all browsers. For example, you can increase the font size in Firefox with “Ctrl + Plus”, but this is not applicable in IE.

Our implementation:
We will have a non-standard keyboard shortcut to increase and decrease the font in our implementation. :( (I can’t help it!). To handle keyboard events through javascript you will find many libraries available on web. I will be using the openjs library and the reason? It’s a simple, single file library. To keep your implementation simple and easy to handle we will have the styles, script and HTML in one file.

To start with, we will be using CSS to apply style to all content in your page. Let say we have many styles, but what we need is the list of CSS class which needs to be updated when user request to increase or decrease font size. We will update all these CSS styles through JavaScript when user click on the appropriate button or hit the keyboard shortcut. To handle keyboard, we will initialize listeners in an init method.



shortcut.add("Ctrl+Shift+A",increment);
shortcut.add("Ctrl+Shift+Z",decrement);


This method will be called on onLoad event of the webpage. We will track Ctrl+Shift+A and Ctrl+Shift+Z keystrokes and the appropriate methods will be called (increment and decrement).

To modify the font attributes, we need to search through styleSheets object list of a document. I have created my own method to do so.



function getStyleByName(styleName) {
for (i=0; i<document.styleSheets.length; i++) {
if (document.styleSheets[i].cssRules) {
for (j=0;j<document.styleSheets[i].cssRules.length; j++) {
if (document.styleSheets[i].cssRules[j].selectorText == styleName) {
return document.styleSheets[i].cssRules[j].style;
}
}
} else {
for (j=0;j<document.styleSheets[i].rules.length; j++) {
if (document.styleSheets[i].rules[j].selectorText == styleName) {
return document.styleSheets[i].rules[j].style;
}
}
}
}
}


Given a CSS class name, the method traverse through the styleSheets objects and return the style object. In this example we will modify only one style, but if you need to modify multiple CSS styles, you will have to stores these names in an array.

Now have a look at the complete code:



<html>
<head>
<style>
.divStyle {
color: red;
}
.newStyle {
font-weight: bold;
}
</style>
<script type="text/javascript" src="shortcuts.js"></script>
<script type="text/javascript">
//<![CDATA[
function getStyleByName(styleName) {
for (i=0; i<document.styleSheets.length; i++) {
if (document.styleSheets[i].cssRules) {
for (j=0;j<document.styleSheets[i].cssRules.length; j++) {
if (document.styleSheets[i].cssRules[j].selectorText == styleName) {
return document.styleSheets[i].cssRules[j].style;
}
}
} else {
for (j=0;j<document.styleSheets[i].rules.length; j++) {
if (document.styleSheets[i].rules[j].selectorText == styleName) {
return document.styleSheets[i].rules[j].style;
}
}
}
}
}

function testStyleSheet() {
var styleObj = getStyleByName(".divStyle");
if(styleObj) {
alert('style.font-size: ' + styleObj.fontSize);
} else {
alert('style not found.');
}
}

function increment() {
var styleObj = getStyleByName(".divStyle");
if(styleObj) {
styleObj.fontSize = "20px";
} else {
alert('style not found.');
}
}

function decrement() {
var styleObj = getStyleByName(".divStyle");
if(styleObj) {
styleObj.fontSize = "10px";
} else {
alert('style not found.');
}
}

function init() {
shortcut.add("Ctrl+Shift+A",increment);
shortcut.add("Ctrl+Shift+Z",decrement);
}
//]]>
</script>
</head>
<body onLoad="init()">
<input type="submit" onclick="increment()" value="Increment Size"/>
<input type="submit" onclick="decrement()" value="Decrement Size"/>
<input type="submit" onclick="testStyleSheet()" value="Test StyleSheet"/>
<hr/>
<div class="divStyle">A sample text</div>
<div> Without the disStyle class attched to the DIV tag. the fonts will not increment and decrement. The big trouble is the key combination in mozilla.
http://www.openjs.com/scripts/events/keyboard_shortcuts/
</div>
<div class="divStyle newStyle"> This is a test </div>
</body>
</html>


So, there you go! Remember, this is NOT complete and you can take it forward.
Keep programming :)

Read more >>

All about Ext.Button!

Posted on February 10, 2008

I have already demonstrated the difference of ExtJS1.x and 2.0 with a simple "Hello World" program. Now let’s get deeper and this time it’s about buttons in ExtJS. In this article we will cover creating, handling and manhandling of Ext buttons.

Setting up your programming environment:

There isn’t much to this. If you do not have ExtJS 2.0, you need to download the latest version. All you have to do is unzip the downloaded file, place them in a proper folder structure. I usually have a folder structure as shown:



The js folder has all the JavaScript of the application. Inside this folder I have separate folders for different libraries and I store my custom JavaScript files in appjs. Again this appjs can have subfolders to separate JavaScript files module-wise. This might not be the best folder structure but for now we will stick to this. If you are new to Ext you can have a look at my "Hello World" program.

Ok! Now we are ready for some action. Let’s start with creating a simple button.

Creating a Button:

Ext has Button class implement in the base package ie, Ext. To create a button all you have to do is create an instance of this class and specify the attributes. The Button class has a parameterized constructor with one parameter, the button’s configuration!
Here is the code to create a simple button:



buttonObject = new Ext.Button({applyTo:'button-div',text:'Simple Button'});


You will see that we have used two configuration parameters. applyTo is used to specify which HTML element is going to become the button. The HTML element can be DIV, P or SPAN tag. Remember that applyTo should be passed for the button to render. The next parameter is the text of the button itself. Now another way to specify the holding element for button can be done my calling the public method applyToMarkup. The method takes a parameter which is the id of HTML element to which the button will be rendered.

Attaching handlers to button:


There are basically three ways to attach event to the button you created. One is to use the constructor to specify a callback when the button is clicked and the other is to use addListner method. This method is more generic because you can specify action for any type of events on a button.

The first method is by using the constructor you specify the call back function that needs to invoke when the button is clicked. Remember: It’s only for handling button clicks. Have a look at the example below:


buttonObject = new Ext.Button({applyTo:'button-div',text:'Testing',handler:buttonHandler});


buttonHandler is a method defined in our application class as private method. Here is the complete application code:


app = function() {

var buttonObject;

var buttonHandler = function(button,event) {
alert('You clicked the button!');
};

return {

init:function() {
buttonObject = new Ext.Button({applyTo:'button-div', text:'Testing',
handler:buttonHandler});

}
};
}();


The second method is to use the setHandler method to set the call back method for click event. The method has only one argument and it’s the call back method.

The third method to attach an action is to use the public method addListener. Through this you will be able to define actions for events like clicking, mouse over, mouse out etc. Take a look at this example:


buttonNext = new Ext.Button({text:'Touch me'});
buttonNext.applyToMarkup('nxt-button');
buttonNext.addListener('mouseover',mouseHandler);


The addListener method has four parameters out of which last two are optional. Thus in our above example, we have made use of just the feature of assigning action to certain events. The third argument specifies the scope in which the handler method should be executed and the last argument specifies the object containing handler configuration properties. These properties can be scope, delay etc.

Before we close, there is one more way to attach event handler to button. This can be done by calling on method. This method has the same number of parameters as the addListener method.


Firing and removing handlers:


ExtJS provides a good set of APIs to manipulate events and actions for any component. As its possible for developers to create and attach actions for button, its also possible to manually fire, stop and remove these event and action.

Situations arise wherein you need to fire an event or series of events when one components event is fired. To fire an event manually we have fireEvent method.
This method has variable length argument of which the first argument is the event name that needs to be fired and the rest is the parameters passed to the handler if any.Have a look at the example below:


app = function() {

var buttonObject;
var buttonNext;

var buttonHandler = function(button,event) {
alert('You clicked the button!');
buttonNext.fireEvent('mouseover');
};

var mouseHandler = function(button,event) {
alert('Mouse on me!');
};

return {
init:function() {
buttonObject = new Ext.Button({applyTo:'button-div',
text:'Click me',
handler:buttonHandler});

buttonNext = new Ext.Button({text:'Touch me'});
buttonNext.applyToMarkup('nxt-button');
buttonNext.addListener('mouseover',mouseHandler);
}
};
}();


Here we manually fire the ‘mouseover’ event for buttonNext when user clicks on the first button. Thus inturn, the mouseHandler of buttonNext is called.

Now, let’s remove handlers attached to the buttons. ExtJS provides two methods to remove a specific handler from an event. Developer as either use removeListener or un method (addListener and on for adding). And finally to remove all the handlers attached, you may call purgeListeners method.

Suspending and Resuming Events:

Adding, firing and removing is not all that. At times you may need to suspend the events so that the handlers are not fired. You can use suspendEvents and resumeEvents method to enable and disable the event firing for a component. For example:


buttonNext.suspendEvents();


This would suspend all event fired by buttonNext object.

Other Methods:


I am not explaining each function explicitly. But I am just covering the major once that a developer needs to know. For complete list of methods refer the Ext API Documentation.

Winding Up:

For a Ext beginner, I hope this will greatly helpful. Please let me know of any mistakes in this tutorial. You can download the final source code from here. Keep programming and I will be back with more "All About…" series.
Read more >>

jQuery introduces UI and Special effects

Posted on February 08, 2008

jQuery is one of the simplest JavaScript library available for handling events, performing animations, and add Ajax web pages. jQuery team has announced the alpha release of two new JavaScript libraries: jQuery UI and jQuery Ehchant! These two libraries add UI and special effects to existing jQuery library.

Like any other JavaScript library, jQuery UI provides a set of themable widgets on top of the jQuery core library. The (Alpha) library provides widgets like Accordion, Dialog boxes, Tabbed content panes, Tables etc. And the team still working on widgets like Menu, Toolbars, Tree, Splitter, Rich Text Editor etc. for a demo on the existing widgets try the URL : http://ui.jquery.com/1.5a/demos/.

On the other side, jQuery Ehchant is meant for special effects. You can see dome cool examples of this library here! To use these, you will need the jQuery core library. So download jQuery 1.2.3! this new release includes support for Adobe AIR, Namespacing and of course, jQuery UI. You can download these libraries at:

jQuery UI: http://jqueryjs.googlecode.com/files/jquery.ui-1.5a.zip
jQuery Enchant: http://jqueryjs.googlecode.com/files/jquery.enchant-1.0a.zip

You can also access all the documentations here. Happy jQuerying!

Read more >>

Wrapper libraries for ExtJS

Posted on January 26, 2008

Ext JavaScript library, used for building rich internet applications has emerged as a popular and very vast library. The Ext team has recently released 2.0.1 which is a maintenance release and fixes lots of issues it predecessor had. Over time, developers around have created wrapper libraries to make Ext more developer friendly and easier.

Ext makes the complete use of JavaScript to build the rich application. The code to build a page at times becomes quite large (especially if you have lot of components). Using Ext in its raw form can be difficult if you are new to JavaScript. This is mainly because it difficult to debug the js code and Ext still lacks good tutorials. But I have come across many open-source projects that are aimed to make developer’s life easy. All these projects seem to be quite good and moving in positive direction.

ExtTLD: Ext library extension for java developers! You have all Ext components represented in the form of tags. All you have to do is add the TLD library, add JSTL support and Apache commons library to your project. The project is still in beta stage and is available for download. But I am not sure of the license in which this library will be distributed and its Tag source code is not available for download.

To test, I downloaded the library and was programming the next minute. The steps are simple and easy. Have a look at sample code:



<ext:body>
<ext:window title="Testing" width="300" height="300" id="myWindow">
<ext:toolbar>
<ext:toolbar.button text="Button 1" />
</ext:toolbar>
<div style="padding:5px">This is a simple window in Ext </div>
</ext:window>
</ext:body>



MyGWT: This is a java library for Google Web Toolkit. The library helps developer to compile their java code to web applications and has been licensed under LGPL 3.0. The library seems to have stable release but I am not sure if the library supports Ext 1.x or 2.0. The site has enough examples and tutorials to start you up.

Let’s change the platform. The above mentioned wrappers are related to java developers. What about .Net, Rails and ColdFusion developers? Wrapper libraries for these platforms are also available. For Microsoft platform we have Ext Extender controls which is hosted on CodePlex. For Rails we have library provided by GL Networks Inside. ColdFusion developers have two libraries Ext.CFC and cfExt.

I am Java guy and have not tested libraries for .Net and others. May be you should test them and comment about it. So, web developers... What are you waiting for? Checkout the libraries!!!

Read more >>

Making better use of Google Analytics

Posted on December 15, 2007

Many bloggers and small companies make use of Google Analytics to analyze their web traffic. But how many of them are making full use of it? Analytics don't end at installing the code and setting Goals. There are many fine tuning a web developer needs to do in order to trac