February 28, 2011

How to execute custom queries on Recess framework

Working with Recess framework can be fun if you are ready to dig into the source code of the framework. Due to its small code footprint, going through the code is no trouble for even a beginner. In this article, we will have a look at how to execute custom mysql query.


Recess framework keeps a registry of data sources available for an application. The Database class provides this registry and provides static methods to access the data sources. The class holds all the data sources in an array. It also has a separate variable to hold the default data source.

The framework does provide you with its own ORM and makes CRUD very simple and zero lines of coding. But there are times when you need to execute complex quires against our data sources. I assume you have set your data source as default in recess-conf.php. Now, to get hold of your PDO object (data source), you can simple call the getDefaultSource method. eg:
$pdo = Databases::getDefaultSource();
And here is an example of executing the query:
$pdo = Databases::getDefaultSource();
$sql = "SELECT * FROM MyTable";
$rows = $pdo->query($sql);
foreach ($rows as $row)
{
 /* Process the selected rows */
}

Other methods of Database class
The Database class also provides access to named data sources through other static methods. You can use the addSource and getSource methods to add and get a named source.

You can get the array containing all the data source using the method getSources. And also set the default data source using the setDefaultSource method.

February 23, 2011

Multiple file upload using ExtJS & ASP.Net MVC

Recently I had to build an image gallery for one of my project which used ExtJS & ASP.Net MVC. The gallery consisted of many components, and I will explain the multiple image file upload functionality used in this gallery.


There are many ExtJS plugins already available for file upload that uses flash. One of my requirements was to avoid flash in my project. So, I could not use plugins like
Awesome uploader or UploadForm. So, if you need some fancy looking component & functionality, I suggest you have a look at them as well!

Here I have a simple uploader form that can be used for any server side. I will be using ASP.Net MVC. I have clean URLs as my application follows REST. Let’s have a look at the javascript first:
UploaderWindow =  Ext.extend(Ext.Window,{
    title: 'Upload Window',
 closeAction: 'close',
 id: 'upload-window',
 folderID: null,
 initComponent : function() {
  
  // Upload Form
  var uploadForm = new Ext.form.FormPanel({
   id: 'upload-form',
         fileUpload: true, 
         frame: true,  
   border: false,      
         bodyStyle: 'padding: 10px 10px 0 10px;',
   labelWidth: 50,
   defaults: {
          anchor: '100%'
         },          
   items: [{
             xtype: 'hidden',
             name: 'fieldCount',
    id: 'fieldCount',
    value: 0             
   },{
    xtype: 'hidden',
    name: 'folderID',
    id: 'folderID',
    value: 0
   },{
             xtype: 'fileuploadfield',
             emptyText: 'Select an image',
             fieldLabel: 'Image',
             name: 'file0'            
   }],
   buttons: [{
    text: 'Add File',
    iconCls: 'add_icon',
    handler: function(button,event) {
      
     var fIndex = parseInt(uploadForm.findById('fieldCount').getValue()) + 1;
     uploadForm.add(newField('file' + fIndex));
     uploadForm.findById('fieldCount').setValue(fIndex);
      
     uploadForm.doLayout();
            
    }
   },{
    text: 'Upload',
    handler: function(button, event){
     
     if (uploadForm.getForm().isValid()) {
      uploadForm.getForm().submit({
       url: '/Gallery/Upload',
       waitMsg: 'Uploading your photo...',
       success: function(form, o){        
        alert('Successfuly uploaded!');
       },
       failure: function(form, o){
        alert('Error in uploading the files');
       }
      });
     }
    }
   },{
    text: 'Cancel',
    handler: function() {
     var win = Ext.getCmp('upload-window');
     win.close();
    }
   }]
  });
  
  // Initial Configuration for the window
  var initConfig = {
   resizeable: false,
   modal: true,
   frame: true,
   width: 400,
   autoHeight: true,
   items: [uploadForm]
  };
  
  Ext.apply(this, Ext.apply(this.initialConfig, initConfig));
        UploaderWindow.superclass.initComponent.call(this);
 },
 onRender: function(){
  var fidField = this.upForm.findById('folderID');
  fidField.setValue(this.folderID); 
  UploaderWindow.superclass.onRender.apply(this, arguments);
 } 
});
I have extended Ext.Window class to create my component. The window provides all the controls necessary to upload multiple files onto the server. The upload form is basically embedded within the window. This helps in reuse of the entire component and also helps in customization. In the new component, we have some custom parameters. Once, such parameter is folderID (the default value is null). But when the upload window is created, I would pass a real value. On the server side, the uploaded images are stored according to the folderID passed.



The initComponent method is used to initialize the component. I have the form panel and its elements defined here. Note that I a hidden field to hold the number of files being uploaded (fieldCount) and is set to zero. I also have a field to hold the folder information. This hidden field is populated when the window is instantiated. The file selection functionality is provided by the well known ExtJS component: FileUploadField.

Each time the user click on “Add File” button, we create a new element of the type FileUploadField. This is done with the help of newField method:
function newField(name) {
    var rulesField = new Ext.ux.form.FileUploadField({
        name: name,
        emptyText: 'Select an image',
        fieldLabel: 'Image'
    });
    return rulesField;
}
Now, let’s have a look at the server side code. Our server side is accessed through the URL /Gallery/Upload and the method will be obviously POST. One of my requirements was to upload only images so; I added a simple check for the file extension on the server side. You could do the same on the client side as will. Here is the server side code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload()
{
    string[] supportedTypes = new string[]{ "png", "gif", "jpg", "jpeg" };
    int count = int.Parse(Request.Params["fieldCount"]);
    int folderID = int.Parse(Request.Params["folderID"]);
    
    try
    {
        for (int i = 0; i <= count; i++)
        {
            HttpPostedFileBase postedFile = Request.Files["file" + i];
            if (postedFile != null)
            {
                string x = Path.GetExtension(postedFile.FileName);
                if (supportedTypes.Contains(x.TrimStart('.')))
                {
                   // Process the image
                } else {
                   // document not supported!
                }
            }
        }
        
    }
    catch (Exception e)
    {
        
    }
}
Improvements: There is always space for improvements. You can go ahead with lots of modifications to this component. By end of the day, I had lot of changes. Few improvements are:
  1. Removing added files from the form. 
  2. Client side validations.
  3. Option for entering meta data for the images being uploaded.
  4. Progress bar like other components mentioned above. .. etc 
Your comments are welcome. Enjoy coding! :)

Read other ExtJS related articles!

February 14, 2011

Recess framework - An ignored PHP RAD tool!


My new personal project is being built on PHP stack instead of Java or .Net! My team (group of friends) not I are regular PHP coders and we decided to give PHP a try. Our application needed a simple MVC framework, REST support & small learning curve. During the search I stumbled upon Recess! - A RESTful PHP framework.

Recess! is a RESTful PHP framework that claims to be built for implementing RESTful application with strong object-oriented design, annotations and RAD tools. I decided to give it a try even though we have plenty of famous frameworks like Zend stack, CakePHP, Symphony etc.

I got quite exited after viewing the first screen cast about the framework. At the same time, I was little disappointed to see the framework was versioned 0.2 and dated to 2009. Nevertheless, I decided to download and try. I got my first blockade with the framework in 20 minutes to deploying it on my PC. Turned out that, the version 0.2 had bugs and I had to switch to the cutting edge version. With the latest version, I was running my first application in no time. But when you go beyond “Hello Wold” applications you will find real trouble due to lack of documentation.

The framework introduces annotations to PHP! Unlike java, annotation symbol used is ‘!’ annotation. Applications routing information, data model relationships, etc. are all provided in the form of annotations. In addition to this the framework provides an interactive toll to create application, scaffolding and manage your data models. Yes! You have CLI tools for other frameworks but this is simple and real RAD. Apart from these features, the framework had a plugin architecture and easy to extend.

But, even with these features, I don’t see the framework becoming popular. One reason for this could be the lack of documentation and tutorials. The framework lacks documentation and you will have to read the source code in order to understand and fix your issues. The community is also very small, so you are left out in the cold. This actually takes away the ‘RAD’ in Recess and your learning cure shoots up.

Another reason for lack of community would be because the framework has had very little changes after 2009. With no active development happening, new developers (like me) usually do not try it and end up with other frameworks.

Here is my final take on the framework:
Pros:

  • Create RESTful application quickly and with great ease.
  • GUI based tool for creating project structure, scaffolding etc.
  • Declarative PHP with the help of annotations.
  • Loosely coupled Model-View-Controller.
  • Makes use of Don’t Repeat Yourself (DRY) philosophy & practice.
  • Caching-oriented architecture.
  • Provides a simple ORM library that is integrated into the framework.

Cons:

  • Lack of community interaction and support.
  • Lack of Manuals, tutorials and API documentation.
  • Very slow development of the framework.
  • ORM is still not powerful enough compared to other available libraries.

Recess framework is really good RAD and its developers and community should take it forward. It makes PHP programming real fun!

January 28, 2011

Cascading Combo box in ExtJS

This week, two Techno Paper readers had approached me with questions on cascaded loading of combo box in ExtJS. Rather than replying them with mails, I decided to put it up for on the blog so other readers can also get it. In this tutorial I will explain how to cascade the loading of combo box options.


Cascading combo box can help in avoiding huge combo boxes. You can provide the user with a drill down of options that you offer and this helps them narrow down the options to select. When you have large data to display, it would be better to avoid combo boxes and go for a list view.

For now, let’s take a simple form where the user is asked to select geographical location & language. The selection of city is made by selecting country and region. So, we have three combo box:
  • To select region (Continent)
  • To select country
  • To select city
User does a drilldown on these three combos to finally select the city. First the user selects the continent. Selection triggers loading of all the countries in that continent. And similarly selection of country will trigger the loading of cities of that country.

Now, let’s get our hands dirty with the code. We will have a data store for each of the comobo boxes. In this tutorial, we will use Json store. You should be able to use any other store Ext JS library provide. Let me introduce the store for holding continents:
var mainStore = new Ext.data.JsonStore({
 autoLoad: true,
 url: '/GetContient',
 fields: ['item','value']
});
The store is very simple and straight forward. We set three properties of the json store. Unlike other dropdowns, the continent is starting point of our cascading. In order to load it along with the form, we will use autoLoad property of the stores. You need to define the url from which the store will be loaded & the fields array provides information on the fields.

The other two stores are slightly different. They will be loaded through selection of the respective drop downs. So, they are not initially loaded with values. Here are the stores for country and city:
var countryStore = new Ext.data.JsonStore({
 autoLoad: false,
 pruneModifiedRecords: true,
 url: '/GetCountry',
        fields: ['item', 'value']                   
});
     
var cityStore = new Ext.data.JsonStore({
 autoLoad: false,
        pruneModifiedRecords: true,
        url: '/GetCity',
 fields: ['item', 'value']                   
});
We have set pruneModifiedRecords property inorder to clear records each time the store is loaded. Now we have our stores ready. Let’s code our form and its fields.

Apart from the three drop downs, I will have a text field for keying in the language. We will render the directly onto the HTML document’s body tag. So, here is the code:
var Example = new Ext.Panel({
    title: 'Example of Cascading combos',
    renderTo: document.body,
    width: 400,       
    frame: true,
    items: [{
        xtype: 'form',
        url: '/FormSubmitURL',
        id: 'ex-form',                                                                      
        method: 'post',
        defaults: {
            anchor: '95%'
        },
        items: [{
            xtype: 'combo',
            fieldLabel: 'Continent',
     emptyText: 'Select a Continent',
            store: mainStore,                            
            editable: false,
            allowBlank: false,
            forceSelection: true,
            valueField: 'value',
            displayField: 'item',
            triggerAction: 'all',
            hiddenName: 'continent',
            id: 'continent',
  listeners: {        
          'select' : function(field,nval,oval) {
    countryStore.load({
                      params: {'id': nval.data.value }
             });
    }
   }
        }, {
   xtype: 'combo',
            fieldLabel: 'Country',
   emptyText: 'Select a Country',
            store: countryStore,
   mode: 'local',
            editable: false,
            allowBlank: false,
            forceSelection: true,
            valueField: 'value',
            displayField: 'item',
            triggerAction: 'all',
            hiddenName: 'country',
            id: 'country',
   listeners: {
    'select' : function(field,nval,oval) {
     cityStore.load({
                params: {'id': nval.data.value }
             });
    }
   }
  },{
   xtype: 'combo',
            fieldLabel: 'City',
   emptyText: 'Select a City',
            store: cityStore,
   mode: 'local',
            editable: false,
            allowBlank: false,
            forceSelection: true,
            valueField: 'value',
            displayField: 'item',
            triggerAction: 'all',
            hiddenName: 'city',
            id: 'city'       
  },{
   xtype: 'textfield',
            fieldLabel: 'Language',
            name: 'language',
            id: 'language'
        }],                        
        buttons: [{
            text: 'Submit',
            handler: function() {
    alert('Submit the form');
   }
        }]
    }]
});
Now, lets focus on one of the combo boxes. Notice how we cascade the loading of the combo boxes using the select event. The select event callback function provides us with all the information we need. It has three parameters and they are:
  1. The combo box
  2. The newly selected field record
  3. Numerical index value of old selection
From the callback’s parameters, we get the new selection information, which is used to load the country or city data store using the load method.

You can download the Javascript source code and try it. I have not included the any server side or ExtJS files with the package. Please provide your comments and suggestions. :)

Read other ExtJS related articles!

January 18, 2011

Working with .Net serialized dates in ExtJS

ASP.Net’s JSON serialize encodes DateTime instance as a string. If you return a JSON from a MVC contoller, you will notice your data encoded in the form:
\/Date(1295163209177)\/

This is basically nothing but Jan 16 2011 10:33:29! ExtJs components like data grid, datepicker do not consume this format and needs to be transformed.

Why does Microsoft serialize DateTime in this form?

One of the major disadvantages of using JSON is its lack of date/time literal. The support for date and time values is provided by the Date object in javascript. So, In order to represent the date and time, there are two options available:

1. To express the data as string
2. To express it in numerical form.

The numeric form would be the the number of milliseconds in Universal Coordinated Time (UTC) since epoch. But in either form, we still have the issue of not being able to identify it as date / time. In order to overcome this, MS came up with encoding DateTime values as string in the form:
\/Date(ticks)\/

How to fix it in ExtJS?

Deserializing in ExtJS can be done with the help of Date class. You can use the parseDate static method to convert the serialized date into Date object.
var dt = Date.parseDate(date,'M$');
dt.format('d/m/y');
The deserialized dates can be displayed in any desired format! :)

Read other ExtJS related articles!

January 11, 2011

Getting "Dive into HTML5" for Free!!!

There are many references available for HTML5. But, there is one reference you should not miss as a web developer.

Dive into HTML5 by Mark Pilgrim is free for the public. Site: http://diveintohtml5.org/

For those you need the hard copy, you can get the book titled HTML5: Up & Running by the same author (Costs around $18).

January 10, 2011

Creating toolbar in ExtJS Viewport

Building application UI using Ext JS can be complex and confusing for new comers. When you build applications, you usually make use of the border layout for placing different components onto the main screen of your application. In most of the cases you will require a toolbar with menus and buttons. But the viewport component has a catch.


Unlike the panel component of Ext JS, Viewport does not have a tbar option. So, you cannot attach a toolbar component into viewport. The best solution is to convert north region of your application to a toolbar.

To keep things simple, will have north, west and center regions of my border layout. I will also avoid handler methods and other actual content of the application. First lets simple define the application layout alone.
var application = new Ext.Viewport({
    renderTo: document.body,
    layout: 'border',
    items: [{
        region: 'north',
        border: false,
        frame: true,
        html: 'this is north'        
    }, {
        region: 'west',
        layout: 'fit',
        width: 200,
        border: true,
        frame: true,
        html: 'This is the left panel'
    }, {
        region: 'center',
        html: 'This is the center panel',
        frame: true,
        border: true
    }]
});
Once you have the layout, you just need to convert the north region into a toolbar. To do so, you will have to create a tbar instance in the north region’s panel. The complete code given below:
Ext.onReady(function(){
    Ext.QuickTips.init();
        
    var application = new Ext.Viewport({
        renderTo: document.body,
        layout: 'border',
        items: [{
            region: 'north',
            border: false,
            tbar: [{
                text: 'New',
                menu: [{
                    text: 'Add New X'
                }, {
                    text: 'Add New Y'
                }]
            }, {
                text: 'Refresh'
            }, {
                text: 'Tools'
            }, '->', {
                text: 'Options',
                iconCls: 'options_icon',
                menu: [{
                    text: 'User Info'
                }, {
                    text: 'Settings'
                }, {
                    text: 'Switch Theme'
                }]
            }, {
                text: 'Help'
            }, '-', {
                text: 'Logout'
            }]
        }, {
            region: 'west',
            layout: 'fit',
            width: 200,
            border: true,
            frame: true,
            html: 'This is the left panel'
        }, {
            region: 'center',
            html: 'This is the center panel',
            frame: true,
            border: true
        }]
    });    
});
You will have to add handlers for the buttons or menu you added to the toolbar. You can add the appropriate handler function to the property named handler. For example, let’s assume we are adding a handler to “Add New X” menu item:
text: 'New',
                menu: [{
                    text: 'Add New X',
      handler: function() {
Ext.Msg.alert(‘Alert’, 'Add new X item!');
} 
                }, {
                    text: 'Add New Y'
                }]
As always your ideas, doubts and comments are always welcome. Also share your experience on web technologies on Techno Paper facebook page!

Read other ExtJS related articles!