Marketing digital. Making results.

Set up JSON action output in CakePHP 1.3

Working  on setting up the Rest Plugin for CakePHP helped me realize that i wanted to set up JSON output for some of my actions. This way, if you request for example “” in the url, you will be returned the JSON post data. This excellent tutorial here will help you achieve it. The steps are simple:

  • Enabling JSON parsing in your app/config/routes.php: Router::parseExtensions('json');
  • Enable the RequestHandler component in your app_controller.php:  //Only enabling json response parsing for url requested with the .json extension  if ($this->RequestHandler->ext === 'json')  {      $this->RequestHandler->setContent('json', 'application/json');  //Prevent debug output that'll corrupt your json data      Configure::write('debug', 0);  }
  • In your app/layouts folder, create a json folder with the default.ctp (so the file path should be app/layout/json/default.ctp) file with the following content:  < ?php  header("Pragma: no-cache");  header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");  header('Content-Type: application/json');  echo $content_for_layout;  ?>
  • Now for all controller actions that you want the json output enabled for, set the variable  in the viewVars for examples in my PostsController view action, i return the post data I want to view as:  $this->set('post', $this->Post->read(null, $id));
  • Now second, we need to create the json view for this data. I created a "json" folder in my "views/posts" folder and created a "view.ctp" file (views/posts/json/view.ctp) with this content:  <?php      echo $this->Js->object($post);   //Some old posts you will find have this as echo $javascript->object($aPosts); This was done with the old Javascript helper, doing some //might give you trouble as it did for me. use the new JS helper syntax as of 1.3  ?>
  • And that’s it you are home free, json output a go go for your action. Access you will get your regular html output, access and you will be returned your Json output, to view the Json file in Firefox install the JsonView extension.

Now you will notice that for all json views, we will be re-using the same code, basically just changing the name of the variable to output. This call for a JsonView, and I will post aboutit once i get it implemented correctly.

On expertise, self confidence and job hunting

Every time I go through a job search as I am going through right now, it is always surprising to me how much of an humbling experience it becomes. Reading job descriptions is a good way to quantify and effectively gauge what you have accomplished, that you might not even value as actual skill, and how to express it to a potential employer. My own conundrum is, to express it in a medical allegory, that as far as my web development background, I am a generalist, I’ve dealt with different architectures, frameworks and languages, and reached a point where I am trying to become a specialist. It is a little like trying to go from being a family doctor, to a foot surgeon.

Continue Reading

My first mobile Hackathon experience

On Saturday October 15th 2011 I attended the ATT Mobile App Hackathon held at the AOL headquarters in Dulles Virginia. It was quite a drive for me to get there, on top on waking up early on a Saturday morning but I figured it was worth it, I was already on a roll attending the UM Technology Startup Bootcamp the day before, which was informative in its own right. So i got to the AOL building a little after 10:00 enjoying 45 minutes or so of good reggae in my car and when I got into the building I was surprised by the “hipness” of it all. The event was held on the fifth floor and getting to the actual conference room just confirmed what I suspected at that point: AOL means business now. I met TeamAOL’s main man Christopher Gibson who gave me a card right away and let me know AOL was hiring mobile developers (A good man, if you are looking for a solid mobile dev gig, email This email address is being protected from spambots. You need JavaScript enabled to view it. ). After a healthy fruit based breakfast, I milled around, networking with the other developers and met others who like me were there for the first time.

Continue Reading

Beginning Entrepreneurship

It’s not easy and I just started. It’s intimidating and exciting like a blank canvas. It feels like I am standing at the edge of a plane or a precipice looking down and appreciating or dreading the free fall. The difference is whether I have a parachute or not, and whether that parachute will indeed function as designed. I’ve made my first couple of moves last week by attending a couple of networking events, one in Baltimore by Innovate Baltimore and the Co-Founders Wanted meetup in Rockville. I’ve already made some good connections and it felt reassuring to meet other people at various stages of the entrepreneurship path. It remains scary and I dread it. Like that task you keep putting off because you are scared of how big it seems and the effort it will take to get it done.

Continue Reading

Leverage your web developer skills for mobile development

In the world of mobile application development, you can either build applications the standard way, which means using Objective-C to write Apple iOs applications, or Java with the Android SDK for your Android applications etc etc, you get the point. But a new paradigm has appeared that is very appealing to web developers like me as complementary to a skill set I already possess: writing mobile applications using HTML, CSS and Javascript. The tool that makes this magic possible is called PhoneGap and version 1.0 has just been released to I bet, the delight of many mobile developers out there. The concept behind PhoneGap is simple:

  • Build your app using HTML and Javascript
  • Access the native phone APIs through the PhoneGap wrappers
  • Deploy to multiple platforms

The appeal here is reminiscent of the early Java slogan, “Write Once Run Anywhere” or WORA, for those who still remember, and PhoneGap is even lauching a beta for PhoneGap Build, a service that will allow you to “write your app using HTML, CSS or JavaScript, upload it to the PhoneGap Build service and get back app-store ready apps for Apple iOS, Google Android, Palm, Symbian, BlackBerry and more”.  There are a  number of Javascript frameworks out there that can be used to build apps in conjunction with PhoneGap, the  two most popular are JQuery Mobile and Sencha Touch. Both are very capable frameworks that make use of the latest advances in CSS3 and HTML5. Your choice in a guttural way would depend on your familiarity with their browser counterpart (JQuery or ExtJS). What you have to understand at the end of the day with the PhoneGap architecture is that your finished app would basically be a web page running within a browser. Here are a couple tutorials to get you going either on Sencha Touch or JQuery Mobile.

Continue Reading

ExtJS: Show a loading mask during Ajax calls

This is my first ExtJS post in a long while and sorry it’s not related to ExtJS4; maybe in the near future.Recently I was asked to implement a page wide mask during Ajax calls to prevent user from interfering with the current call by clicking on the screen or doing something they otherwise should not be doing while the call is running. I initially used the “wait:true” option of the Ext.MessageBox configuration, but the stakeholders did not like it since the progress bar it displayed was not synced to the actual length of the call. This is how I ended up implementing it:

function showLoadingMask(loadingMessage)
if (Ext.isEmpty(loadingMessage))
loadText = 'Loading... Please wait';
//Use the mask function on the Ext.getBody() element to mask the body element during Ajax calls
Ext.Ajax.on('beforerequest',function(){Ext.getBody().mask(loadText, 'loading') }, Ext.getBody());
Ext.Ajax.on('requestcomplete',Ext.getBody().unmask ,Ext.getBody());
Ext.Ajax.on('requestexception', Ext.getBody().unmask , Ext.getBody());

Hope it helps!


The meat of the functionality is in binding the mask() and unmask() function of the Ext.Element object to the ‘beforerequest’, ‘requestcomplete’ and ‘requestexception’ events of the Ext.Ajax object. I need a custom message to be displayed depending on the context that’s the reason why i encapsulated that logic in a function. I also tweaked my CSS a little to customize the mask style, overriding the ExtJS style, as well as the style of the message displayed to the user:


.ext-el-mask-msg div {
background-color: #EEEEEE;
border-color: #A3BAD9;
color: #222222;
font: 1.2em tahoma,arial,helvetica,sans-serif;

.ext-el-mask-msg {

padding: 10px;


Installing SSH2 manually on Debian Linux

Phew. I’ve just succeeded in installing SSH2 on my DreamHost hosting account, which happens to run on Debian. I am more of a Windows guy which explains why it took me so long but I am none the wiser for the experience. Let me show you how I did it. I used these two excellent articles as my points of reference:

Installing SSH2

Make SSH Connections with PHP

First of all, let it be said that I am running on PHP 5.3. So if you are using DreamHost as your hosting provider, follow this guide here to update your account:

PHP Upgrade Guide

Continue Reading

How to create site thumbnail images

If you have ever in need of create a thumbnail image of a site, or just get an image of a site, there are a lot of services out there that offer that capability online. The best one I have found so far for casual usage is:


By providing it with a URL, Thumbalizr will return you a screenshot of the site in a variety of formats. You can even specify a custom size. Their prices seem to be reasonable for a heavier type of usage but if your goal us just to capture a quick screenshot and you don’t want to worry about editing it, Thumbalizr is the way to go.

The First Rule Of Development: Nothing will work as expected!

Allow me to be bold with this one, but today I ran again into another one of those environment set up issues that make you question your sanity. No need to get into the details, but ever since the beginning of my career, which has involved quite a bit of J2EE development, one of the things that have amazed me is the ramp up time it took to get started on a project. I am not talking about merely perusing through the code, trying to understand the architecture, get a feel for what’s going on, but simply checking out a project from repository, into Eclipse, and being able to run it on my localhost. “What about the documentation?” I hear you say, you smug devil,  and I smile with full teeth at your foolish smugness. Documentation? Who has time for “Documentation”. “Documentation” means one eager programmer like you was kind enough to flesh out the major steps that should get you to where you need, but in development: THE DEVIL IS IN THE DETAILS…

Continue Reading

Sencha Touch MVC Application Tutorial

I have been catching up on the work of CAM, who has an excellent, so far 3 part series on how to build a MVC mobile application using Sencha Touch. The Sencha Touch tutorials seem to leave a lot of people confused so CAM hand holding and informative approached is quite refreshing. Head over to the site:

Programming: “It pays the bills” vs “It satisfies me”

At this point in my career I find myself increasingly frustrated with my day to day work. You see, living in the DMV area (DC-MD-VA), a lot of the jobs available are in government contracting and as many will tell you, those are well paying jobs with a certain level of job security added. For a while I did it and enjoyed it but deep inside i knew that this was not really what i want to be doing for the rest of my life. With things being the way they are, even when trying to switch jobs, it has been easier to do so going from one government contract to the next, with my attempted moves to the private sector being unsuccessful primarily because first my experience is mostly related to government projects, and second, the pay range was below was I was willing to go for. It is not greed on my part, but being married with kids means ” I got mouths to feed man! “(<= in Dave Chappelle’s voice) and obligations I have to tend to and can’t ignore.

Continue Reading

Google Music Beta: A couple of months later…

I was excited to participate in the Google Music Beta testing and so far i can say that i really like the app. It performs well as far as playing music, specially through Bluetooth which i use daily. Be warned though that you better organize your music before uploading to the cloud. As I have found, once it’s up there, if you need to delete anything, well, let’s just hope that you have a blazing fast connection and the patience of a pimp. I basically gave up. My collection is unorgazined and since it seems that Google is following the convention (is it one?) or organizing albums by the “Album Artist” property of the IDv3 tag, well let’s just say that i have thousands of albums of one song…in the cloud…teasing me…Anyway, I looked for a way to wipe my collection clean and start over, but it seems that for now, no dice. You just can’t delete all your files in the cloud.

Continue Reading

Programming mistakes and how to avoid them

For a good write up on some common programming mistakes and how to properly avoid or mitigate them, check out this excellent article by Paul Tero. Not only you get an explanation of the mistake, but he also gives you some tools and techniques to use alongside. What i really appreciated as well about the article is that Paul is not shy about admitting to past mistakes, no matter how serious, which helps give perspective about their repercussions and is without a doubt a sign of experience and maturity. Insightful to say the least, I have made some of these mistakes and picked up a few best practices from him

Debugging: joy or necessary evil?

That’s it, you’ve done it. Spent countless hours programming this feature, the design was excellent, the coding grueling but finally: It is ALIIIVVVEEE…Wait! What was that? No…No, that’s not how it’s supposed to go, WTF (What The Fortran)!?. And so it begins, you now need to DEBUG! Personally, I do enjoy it and i recognize that due to its nature, it is understandably not a cause of enjoyment for all. First of all, there has to be a distinction made between debugging your own code, and debugging code written by somebody else. I do not enjoy the later as much as the first.

Debugging someone else’s code

Debugging somebody else’s code is obviously a longer process, where you have to get into their thinking mode, and reverse engineer their code. If the code lacks comments or proper documentation and is not particularly clearly written, then to me, debugging becomes a necessary, soul sucking, sarcastic evil. It can provide for some entertainment though, and is nonetheless a good learning tool whether the code is great, in which case you learn new techniques or patterns and improve yourself, or find the most horrifying pieces of code that even as an inexperienced but sharp programmer you can detect all that is wrong with. In both cases you are able to grow by learning from someone else’s coding abilities (or not).

Continue Reading

Update on Programming: “It pays the bills” vs “It satisfies me”

I’ve gotten a lot of positive responses for my previous article: Programming: “It pays the bills” vs “It satisfies me”  and it has now be republished in Chinese here , here, and here. Thanks to my Chinese readers. I can now check off another item on my list of lifetime To-Dos. Programmers of the World, Unite!


Mysql: Remove Duplicate Values on Creating A New Table

I had a reference table for all of the World Countries that i wanted to extract Currency data from to another new table. I initially use this code which created a new table with 263 records.

CREATE TABLE currencies SELECT tld, currency, currencycode FROM countries ; 

I quickly realized that for the purpose I was creating this table, which is to have a unique list of currency codes, this didn’t work. The 263 rows were 99 too many as there are only 164 unique currency codes in my table. Dug around the net for a while and came up with this query:

CREATE TABLE currencies SELECT tld, currency, currencycode FROM countries GROUP BY currencycode; 

That took care of my initial problem.

Download phpssh2.dll extension for PHP 5.3 compatible with WAMP Server 2.1

A project that I am working on now requires shell access basically to dynamically create cron jobs. This took me a minute and will be the topic of an upcoming post but for now, in my local WAMP based dev environment, I need SSH2 set up and good to go. I quickly found out that the version downloaded from the official PHP site needs to be compiled in a DLL.  No time and not set up with MS Visual Studio for that. I was able to procure a version that worked with my local set up of WAMPServer V2.1 on Windows XP:

You can download it here.

Hope it helps!

Visual Editor Tool for CSS 3 Gradients

Colorzilla offers a gradient creator tool I found to be useful in quickly and visually create gradients. They have preset that you can build upon or create your own custom gradients.

Check it out at:

Visual tool for creating CSS gradient properties

Here is a cool little online visual tool to create CSS gradient values for Firefox and Webkit compatible browsers:

Pretty nifty! It creates the -moz-linear-gradient and -webkit-gradient property for your elements

WAMP Apache Error: “You don’t have permission to access / on this server”

Installing and setting up WAMP is a breeze on Windows, but you are bound to run into issues. I’ve encountered a peculiar one this weekend while trying to run a PHP application I am working on. I had XAMPP already running on my machine, and to avoid having both WAMP and XAMPP lauching by side, i decided to switch all my projects to running on the Apache server provided by WAMP. To do so, i needed to set up a Virtual Host to point to the directory previously holding the projects i had running under XAMPP. I modified my httpd.conf this way:

  #Uncommented the line loading the Virtual Host configuration file    Include conf/extra/httpd-vhosts.conf    

Then in the httpd-vhosts.conf file.

<pre>#  # VirtualHost example:  # Almost any Apache directive may go into a VirtualHost container.  # The first VirtualHost section is used for all requests that do not  # match a ServerName or ServerAlias in any <VirtualHost> block.  #    <Directory "C:\Dev\Workspace">    Order Deny,Allow    Allow from all    AllowOverride all  </Directory>    <VirtualHost *:80>      ServerAdmin This email address is being protected from spambots. You need JavaScript enabled to view it.      DocumentRoot "C:\Dev\Workspace"      ServerName  </VirtualHost></pre>  

With the configuration set up that way, I lost all access to my localhost when starting WAMP. I could access all the projects in the C:\Dev\Workspace folder, but not the ones in the C:\wamp\www standard folder. I could still access phpmyadmin web interface but nothing in the www folder, even a simple html file. Trying to access for example the WAMP index page (www/index.php) would get me:

<h1>Forbidden</h1>  You don't have permission to access / on this server.    

I tried messing with the settings in the httpd.conf for the DocumentRoot at C:\www\wamp folder to Allow All, minding that this is unsafe on a live web server :

<pre><Directory />      Options FollowSymLinks      AllowOverride None      Order deny,allow      Allow all  </Directory></pre>  

but got a:

  The requested URL / was not found on this server.    

error from Apache. A clue about going on to fix this came from commenting out the VirtualHost configuration line again in httpd.conf. That done, I was back in business with my www folder being visible again as well as all the projects within. It seemed that the VirtualHosts configurations were overriding the default Server configuration in httpd.conf. I then added the following code in httpd-vhosts.conf and both my C:\Dev\Workspace and C:\wamp\www folder were again “visible” and I was able to access projects in both locations:

<pre><Directory "C:\Dev\Workspace">    Order Deny,Allow    Allow from all    AllowOverride all  </Directory>    <VirtualHost *:80>      ServerAdmin This email address is being protected from spambots. You need JavaScript enabled to view it.      DocumentRoot "C:\Dev\Workspace"      ServerName  </VirtualHost>  #Added this configuration for the WAMP www folder  <VirtualHost *:80>      ServerAdmin This email address is being protected from spambots. You need JavaScript enabled to view it.      DocumentRoot "C:\wamp\www"      ServerName localhost  </VirtualHost></pre>  

Hope it helps!

Zend Framework: mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication

Setting a new project that uses Zend Framework in Zend Studio I ran into an issue trying to launch the app. I got an this error;

  Fatal error: Uncaught exception 'Zend_Db_Adapter_Exception' with message 'SQLSTATE[HY000] [2000] mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file' in C:\wamp\frameworks\ZendFramework-1.7.8\library\Zend\Db\Adapter\Pdo\Abstract.php on line<em>143</em>    

It turns out, the version of Zend I am running is 1.7, which is coded against an earlier version of PHP and when i installed WAMP i installed the latest version which came with PHP 5.3 which uses a new “mysqlnd” driver, thus the error. I guess at this point the choice is either to install an older version of WAMP or to reset the password for the database user as suggested in the bug description.

How to easily delete Subversion Folders in Windows

You’ve probably ran into a situation where you needed to just remove Subversion SVN folders from your project, maybe do a new checkout or whatever. I’ve ran into the issue while trying to create a new working copy of a repository i have been working with after getting a :

<pre>Unsupported working copy format  svn: This client is too old to work with working copy 'C:\myproject'; please get a newer Subversion client</pre>  

This happened because i checked out the project with an older copy of Subclipse, and probably did an update with the latest version of Tortoise SVN i had installed. Googling around the remedy seems to be to check out a fresh copy of the project using the older client, removing the older SVN folders from the unsupported working copy and then overwriting the fresh working copy with the SVN folder free unsupported working copy, effectively preserving your edits, while being able to check them back in. To delete the SVN folder from the unsupported copy, create a registry file as such in a text editor, run it and click Yes to add it to your registry.

Windows Registry Editor Version 5.00  [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]  @="Delete SVN Folders"  [HKEY_CLASSES_ROOT\Folder\shell\DeleteSVN\command]  @="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""  

Alternative in case the above script does not work for you:

Windows XP

Windows Registry Editor Version 5.00  [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]  @="Delete SVN Folders"  [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]  @="cmd.exe /c \"@ECHO OFF && TITLE Removing SVN Folders in %1 &&  COLOR F0 && ECHO Searching for .svn folders recursively in %1 &&  FOR /r \"%1\" %%f IN (.svn) DO ( RD /s /q \"%%f\" && ECHO Deleting %%f... )\""  

Windows Vista/7

Windows Registry Editor Version 5.00  [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]  @=”Delete SVN Folders”  [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]  @=”cmd.exe /c \”TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \”%1\” %%f IN (.svn) DO RD /s /q \”%%f\” \”"  

When done, in Windows XP you should be able to delete all SVN folders in a folder by right clicking on the folder and selecting “Delete SVN Folders”.


Deleting a file or folder monitored by TortoiseSVN

If you are trying to delete a file or folder and it won’t let you by saying that it is being used by another process and you are sure that no other visible program has it opened, chances are it is being monitored by TSVNCache.exe, the background process that watches your file system for SVN related files and folders. Killing that process will allow you to delete the file or folder you need. Note that if you want to delete a file that is being versioned you should do it through the SVN delete command and not through Windows as you risk corrupting your working copy. This particular case applies to instances where you want to delete a folder that is no longer being version controlled. If it does not immediately work, then restarting your computer after deleting the SVN folders should do it.

An Overview of the new ExtJS 4 Javascript framework

Having worked with ExtJS 3.1, it’s a real pleasure to see them keep pushing forward today with the release of version 4. ExtJS is a great framework for doing specific types of UI, and it takes a minute to wrap your mind around the mainly class system configuration programming style required to get things rolling but once you do, you realize the genius and flexibility behind. So kudos to the Sencha team on this achievement. I’ve looked at the press release and notes and  there is some improvement all around. The’ve added a lot more documentationthan with previous releases. The class system has been extended to support dynamic loading, mixins and live dependency calculation. It is also completely sandboxed which for example allows you to run multiple versions of ExtJS within the same page. A major change, not that major if you have been following their work with the Sencha Touch mobile development framework, is the introduction of an MVC application architecture which should help streamline application development and faciliate transitions between team members. Welcomed as well is the addition of SDK tools with support for Javascript code optimization.

Continue Reading

How to POST cross domain and access the returned data using ExtJS

Here is how to post data to a server on a different domain and receive data back using ExtJS (with inspiration from the GWT implementation).

First the FormPanel. The fields are standard and in the JS file we define two variables that are critical to making this work as they’ll allow us to keep track of what’s happening:

//These two variables are critical to the success of this operation    var xdm_formSubmitted = false;  var xdm_sameDomainRestored = false;  var renderDivId='myWidget';    var consigneeForm = new Ext.FormPanel(  {   id: 'customerWidget',   renderTo:renderDivId,  //By default, ExtJS uses XmlHttpRequest, this has to be a standard submit POST  standardSubmit: true,   url: '',   border: false,   hideBorders: true,   items:  [  {   xtype: 'textfield',   name: 'customerFirstName'   },  {   xtype: 'textfield',   name: 'customerLastName'   }    ],    bbar:  [  //This is where the form post is triggerd  {   xtype: 'tbspacer',   width: 300  } ,    {   text: 'Save',   handler: function()    {   var form = Ext.getCmp('customerWidget').getForm();   form.getEl();   //On Submit we set this variable to true, you'll understand why in the event handler function   xdm_formSubmitted = true;   form.submit();  }  }  ]  

Notice that before submitting, we are assigning the target of the post to an iframe that exists on the page (form.getEl() This is the second and crucial step of the process. The iframe we are using is defined in the same js file:

  //This hidden iframe is used to receive the results of the form POST:    {   hidden: true,   renderTo:'myHiddenIFrame',   html:'<iframe id="' +iframePostContainerName + '" name="' +iframePostContainerName+ '"   onload=\"setupIFrameOnLoad(\'' + callbackFunction +  '\')"></iframe>'    }  //The callbackFunction variable is passed to the script by the calling page.    

Which brings us to the third critical piece of the process which is to attach an event handler function to the onload event of the iframe, and this is where all the magic will happen. As you can see i’ve name my event handler function setupIFrameOnLoad and here is the definition:

  setupIFrameOnLoad = function()  {   //If the form was submitted and we have loaded data from our own domain, we are good. Thank you for coming   //and here is your data! It's gonna be 5 dollars, Thank you!   if(xdm_formSubmitted && xdm_sameDomainRestored)   {        //You can access your data now using the property, but        //I've got other plans in my callbackFunction so until such time...        var callbackFunctionCall = callbackFunction + "()";        eval(callbackFunctionCall);   }   //If this is the initial response from the POST, we are still in the POST server's domain   else if(xdm_formSubmitted && !xdm_sameDomainRestored)   {         //Now you know we're about to restore the local domain right?         xdm_sameDomainRestored = true;         //localResourceUrl is passed by the calling page and points to a local 1px image or empty page         document.getElementById(iframeName).contentWindow.location = localResourceUrl;   }   else   {         return ;   }  }    

What is happening here is basically the solution to the cross-domain issue in being able to pass data back to the calling page. Once your form is submitted, the response will be posted back to your iframe within your form page. Since the response is coming back from the server, security on the browser will keep us from accessing any of the properties on the window. To be able to access the data in could be in JSON format if you wanted), the solution is simply to load a local resource file from your environment. It could be a simple blank 1px image or an empty HTML file, anything really to switch the iframe’s source content to be on the same domain where you are calling from. Once the iframe has reloaded you can simply access your data in the property. To close the cycle, the response from your server needs to be a script which sets the property. Using Spring, here is how my action was set up:

</pre>  private void addThisCustomerForMe(HttpServletRequest req, HttpServletResponse response) throws Exception  {    Long customerId = customerController.addOrUpdateCustomer(req);  response.setContentType("text/javascript");  OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());  StringBuffer buf = new StringBuffer("");  buf.append("<html>");  buf.append("<script type=\"text/javascript\">");  buf.append(""+customerId+";");    // can set json data here if you want  buf.append("</script>");  buf.append("</html>");    os.write(buf.toString());  os.flush();  os.close();    }

Of ExtJS’s ScriptTagProxy, Spring Actions, TreePanels and JsonStores

I recently had to implement an Organization lookup (backed by a LDAP repository) widget that will be used by some of the web applications I developed and this in a cross-domain environment.  The data displayed within the widget is broken down in Organization->Group->Person hierarchy and on selection of a Person and click of a button, a callback would sent some information about the selected person to a function in the calling application.

The  organizational hierarchy was implemented logically with a tree using an ExtJS TreePanel component. The challenge then became to propertly load this TreePanel. The ExtJS documentation specifies that a  “TreePanel must have a root node before it is rendered“,  which can be done by specifying the ‘root’ property, or using the setRootNode method. For the purpose of my widget, i needed the tree structure to be completely rendered with parent nodes already expanded to reveal children. What needed was to create this hierarchy in my Spring controller and return it to be loaded in my TreePanel. The component was the key in allowing me to make the cross domain call the widget needs to retrieve the Tree data (Check this article if you are using IE6 and getting a Javascript error when using ScriptTagProxy).

Continue Reading

Invalid Argument Error using ScriptTagProxy and IE6

As explained in my earlier post, i used proxy for some cross-domain AJAX data retrieval. Testing in IE6, I kept getting an “Invalid Argument” error in IE traced to this line in the code. A search on the Sencha forum turned up only this post, with no good solution posted. I traced the problem to thethis.head.removeChild lines, for some reason, IE6 chokes on it. The fix is quite simple, i overrode the function to use parentNode.removeChild:

Ext.override(, {  	destroyTrans : function(trans, isLoaded){  	try  	{      	this.head.removeChild(document.getElementById(trans.scriptId));  	}  	catch(e)  	{  		//IE6 does not like removeChild() to be called directly from the parent element  		  document.getElementById(trans.scriptId).parentNode.removeChild(document.getElementById(trans.scriptId))  	}      clearTimeout(trans.timeoutId);      if(isLoaded){          window[trans.cb] = undefined;          try{              delete window[trans.cb];          }catch(e){}      }else{          // if hasn't been loaded, wait for load to remove it to prevent script error          window[trans.cb] = function(){              window[trans.cb] = undefined;              try{                  delete window[trans.cb];              }catch(e){}          };      }  }  	});

Cross Domain Form Post (XDM) in ExtJS with returned data

I’ve helped a colleague of mine work on a cross domain widget we are building for our applications that allows a user from an application to add information to another application through a pop up widget. Implementation wise, we used a  a simple form implemented using ExtJS FormPanel class. Some of the form fields like State and County dropdowns are  dynamically loaded after rendering, again using ExtJS’s ScriptTagProxy for cross-domain retrieval, no issue here and for more information on cross-domain data retrieval you can check out this post here.

Continue Reading

Android Development: PhoneGap’s “No such file or directory” Error

I was following the tutorial on the Phonegap wiki to set up the example project within the Eclipse SDK and ran into this issue where PhoneGap could not find the phonegap.jar under the framework directory:

`stat’: no such file or directory android-sdk-path.bat
D:/Development/Android/example_android/framework/phonegap.jar (Errno::ENOENT)

I had followed the previous steps and was puzzled by this error. It turns out the issue was the version of Ruby I was using was the issue. I was using 1.9.2 and scaling back to 1.9.1 got rid of the error and i am now able to build fine. I was getting also previous errors about the android-sdk-path.bat missing and those were due to the PhoneGap bin directory missing from my PATH variable so make sure to update your path correctly and you will be good to go!

ExtJS: Printing Panels and Grids

One of the features i had to implement in one of the ExtJS application I’ve worked on  is printing. I was surprised to find out that there was no official print stylesheet for ExtJS. Overall, my strategy was to bring up the print layout within a popup window and call the window.print() command once rendering was done. My application being composed of a mixture of form fields, text and grids within the same screen, the number one issue here for me was how to show that same information in a printable format. No magic from ExtJS here, i referenced a PDF version of the application to redesign the UI for printing purposes. As far as the data itself, i could simply grab everything i needed by referencing the Ext object in the parent window:

  var parentExt = window.opener.Ext;    

My first issue was dealing with Grids. For that, i used the excellent Ext.ux.Printer extension by Ed Spencer that i had to tweak it a bit to get it to work with that i was trying to do since it is designed to print a grid within a popup window. The grid being part of my print page, i just modified its GridRenderer object to render the grid as an HTML table to the DOM. Note that, because of dimensions requirements being different for a print layout, and also display columns requirement being different between the application grid and its printed version, the more convenient resolution was to create a second hidden gridpanel within the application, with its dimensions and columns optimized for printing. The also comes with a print stylesheet that i used as a base for my own.

Continue Reading

Popup Window in IE6: Window appears behind or below the main or parent window

I’ve been trying to open a popup window on selecting an item from a ComboBox in ExtJS and on opening the window, using,  

the popup would start loading and then quickly move below the current page. The behavior i observed only happened in IE6, Firefox loaded the popup fine and it stayed on top. With a bit of research and debugging on my own, i came to find out that something in the ExtJS code was causing the focus to return the <body> element of the main page. The solution to the problem?

//Function to open the Window  openDelegateWindow= function()  {  var popup = "qantume.htm", "Selector", "alwaysRaised=yes, status=0, height=300, width=650, resizable=0" );   if (window.focus)   {   popup.focus()   }   return false;  }    ....  //Function  calls for opening the window in your code  ...  setTimeout(openDelegateWindow()', 100);  ....  

By delaying the start of the openDelegateWindow code, i am figuring the code execution has enough time to return the focus to the <body> tag, and then the open popup window can start uninterrupted and keep the focus on the popup window.

For your reference also i have found this script, which is helpful in making your popup quasi modal in that it checks the focus to make sure that it is not away from the current popup window, unless the focus is on one of the controls within the popup window. If the focus is anywhere else, it is rendered back to the popup window, making it basically stay on top until the user closes it. This is not foolproof, there are ways around, but they are really for the “I really need to break your script” type of user, as explained by the author. You can find it here:

ExtJS: Reloading a Combobox’s Store using OnTriggerClick

I am working on an application where i use a grid and have a combobox outside the grid whose selections are based on the selected rows within the grid. Basically the content of the combobox is dynamically updated based on the selection of rows. I’ve tried many ways of going about solving this problem since as usual i started getting Javascript errors in IE6. I first thought and tried to override the onTriggerClick function of the combobox, but i kept getting this bug where the first click on the trigger did not display the return list of values, but instead displayed a very thin blue box, and any subsequent click would then actually load the store and display the values correctly. Unable to find a solution i gave up on this approach and then tried to use the expand event to reload the combobox’s store. There i also encountered a bug where i would get an “Object is undefined” error in IE while clicking to trigger the combobox. I then did some research on the Sencha forum and then tried moving my code inside the beforequery event listener of the combobox. This worked like a charm.

For code example and a more detailed explanation, check the thread on the Sencha forum:

ExtJS JSON Date Serializer: TimeZones and Format

Through development, we finally ran into the Javascript date issue where the dates sent between the front and the backend were not in sync. The front end was sending the dates to the backend in “YYYY-MM_DD” format, and the Jackson’s deserializer would append the application’s server timezone to the date, and this would result in inconsistent dates in the right conditions since it assumed that the date sent was in GMT and would try to convert it to the local time which ended up shaving a day of the date. To solve this problem, we decided the frontend would send the date with the local timezone which would be saved on the server. It took me a little while to figure it out, but i finally used this piece of code to set the serializer’s date format:

Ext.util.JSON.encodeDate = function(o)  {   return '"' + o.format("Y-m-d'T'H:i:s.uZ") + '"';  }  

To set the correct format for your particular server, check the Date format patterns accepted by ExtJS Date object:

IE6: Invalid Argument Error

If you are using ExtJS and getting an “Invalid Argument” Javascript error in IE6, make sure to check your CSS for example, i get them when dynamically setting “Width” on an element. If the value is not conventionally expressed in pixels. IE will choke on it while Firefox will still accept it. Make sure then to check your style for mispelled words, or incorrectly specified widths or heights

Disappearing ExtJS buttons in IE 6

I officially hate IE6 and know the reason why now, ExtJS. Working with this library has opened my eyes to the deficiencies in the browser. Enough has been said on the topic so let me get to the meat of the matter.I spent a crazy amount of time figuring out why one button i was trying to set up would not display in IE6. It would some some kind of image, but would only show the entire button when the button was hovered on with the mouse. I tried setting the width, the height, the line height with no results. Here is how i was trying to set up my button:

  var lookupButton = new Ext.Button({  text:'Lookup',  style:'float:right'  })    

Doing so, i got an error in IE6 that stated:

el.owner.createDocument.createRange Object doesn’t support this property or method.

It turns out this is a bug in IE where trying to insert a block level element after a plain text creates this error. The solution for me was to add a span around the text i was creating like:

  {  width: this.displayWidth,  html: '<span>' +  String(this.value) + '</span>'    }    

Hope it helps!

Disappearing Ext JS RadioGroup and CheckboxGroup inputs in IE6

I ran into an issue in IE6 with a bunch of my controls not showing up when the page loaded. It was specially with the RadioGroup control in ExtJS. The radio buttons would display fine in Firefox but not appear at all in IE6 even though the HTML was present. I thought it was a width or height issue as it is often the case with ExtJS and IE6 but nothing i did could take care of the problem. I then looked at the container panels of the RadioGroups i was trying to display and realized that i was using a “layout:column” setting, which floats the items in the container left.

Continue Reading

ExtJS: ComboBox display issues

I was trying to set up a couple of comboBoxes for a custom ExtJS triple input (Month/Day/Year) datefield and the comboxes would display but be cropped to 17px. No matter what the width i set on the control, the boxes would not display right. I tried a few things and finally realized that i had specified a “hiddenName” property to be the same as the field’s ” id” property. If such is the case, make sure to specify a unique “hiddenId” property and your comboBoxes will display fine.

Maven WAR plugin: Copying resources to another folder

For the purpose of building an exploded war for my application I am using the maven-war-plugin. There is a common set of UI files that are used by the applications i am working so they’ve been exported to their own SVN folder and the build process copies this folder to the final WAR or exploded war directory. After playing with my POM for a while and trying the maven-resources-plugin without much success, i ran into the <webResources> property of the maven-war-plugin. This is the maven-resources-plugin functionality adapted to the maven war plugin. I originally set up my configuration as such:

  <plugin>   <groupId>org.apache.maven.plugins</groupId>   <artifactId>maven-war-plugin</artifactId>   <version>2.0</version>   <configuration>   <webappDirectory>c:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\${project.artifactId}-${env}</webappDirectory>   <webResources>   <resource>   <targetPath>common</targetPath>   <filtering>false</filtering>   <directory>C:\eclipseGalileo\eclipse\workspace\common</directory>   <includes>   <include>**/*.*</include>   </includes>   <excludes>   <exclude>**/*.svn</exclude>   </excludes>   </resource>   </webResources>   </configuration>   </plugin>  

No luck in getting it work although there were no errors in syntax, all the files in the “common” directory just were getting copied to the root of my webapp directory in my exploded war no matter what the path was i specified
for “targetPath”. The simple fix for that was to upgrade my version of the plugin to 2.1 as such:

<artifactId>maven-war-plugin</artifactId>  <version>2.1</version>  

Et voila! Problem solved.

Validating a checkbox in CakePHP 1.2

I was looking for a good way to validate a checkbox for a site i was working on, and came upon this link that pointed me in the right direction:

I followed the instruction, mainly:

  'agree' => array(  'rule' => array('comparison', '!=', 0),  'required' => true,  'message' => 'You must agree to the terms of use',  'on' => 'create'  )    

But for some reason, it would not work for me no matter what i tried, my checkbox still failed validation, even when the box was checked. I narrowed down the problem to the:

'required' => true,  

line. It seemed to break the validation for a reason I do not know. So removing this line should get you through the validation correctly. I did my validation another way by using a new CakePHP core validation function, inList. Here is the code i use to account for all possible values i am expecting my checkbox to have when checked. I added it to the necessary model class:


  'terms_of_use'=>array(  'rule' => array('inList', array('1',1,'true', true,'on')),  'message' => 'You need to accept the Terms Of Use to be able to register.')    

As you can see, the ‘inList’ validation will check to see if the checkbox value is within the array values submitted so you can account for all possible values you need your checkboxes to have to pass validation. This will improve reusability within your code.

Hope It Helps.

Using the CakePHP 1.2 Email component

I was following the documentation at

about sending an email with CakePHP using the Email component, used the sample code they provided but could not get my application to send email. A little bit of googling helped me figure out what was going on. I have CakePHP setup within my XAMPP htdocs directory and my MercuryMail server was not started. You need to have a mail server setup to be able to send email and there are a few more steps you need to do as well to get up and running. It’s beautifully summarized here:

Once your Mercury is properly setup, you are good to send emails from CakePHP!!!

Lesson learned i guess!

Hope It Helps!