Google analytics code

Monday, December 7, 2009

MySQL: Error 1305 - Function xxx does not exist

I ran into an odd issue on a project I updated awhile ago. I updated an existing sql statement to include IFNULL for an exclusion check. It worked fine on my dev machine, but caused an issue on the production machine.

The version of MySQL on my dev machine was a little bit newer than production so the issue never came up. Here is the error the sql server returned:
#1305 - FUNCTION [DATABASE_NAME].ifnull does not exist

Here is a little bit of the sql that caused the error:
AND IFNULL ( `tbl_category_admin`.`admin_key_id` =5, true )

The problem was caused by the space between IFNULL and (. Changing it to IFNULL( solved the problem. If you run into an issue where MySQL returns an error saying a given function does not exist look for spaces between the function and the "(".

Monday, November 30, 2009

Flex (Learning Flex 3 Book) : Removing IEventDispatcher error from the DataGrid

When I decided to learn Flex I started with Learning Flex 3. It's a great book and does an excellent job of introducing the MXML framework and Flex Builder IDE. I would recommend it to anyone.

One of the problems I have with the book is it doesn't teach you how to remove warnings from your code. A later code example produces the following error: warning: unable to bind to property 'contact' on class 'XML' (class is not an IEventDispatcher). It's not a big deal, but I like to write code that doesn't produce hidden errors.

Here is the code from the book:
<mx: Application
    xmlns: mx="http: //www.adobe. com/2006/mxml"
    xmlns: view="com.oreilly.view.*"
    layout="absolute"
    applicationComplete="contactsService.send()" >
    <mx:HTTPService id="contactsService"
        resultFormat="e4x"
        url="contacts.xml" />
    <mx:DataGrid id="contactsDataGrid"
        dataProvider="{contactsService.lastResult.contact}"
        selectedIndex="0"
        left="10"
        top="10"
        bottom="10"
        width="300">
        <mx: columns>
            <mx: DataGridColumn headerText="First"  
            dataField="firstName"/>
            <mx: DataGridColumn headerText="Last" dataField="lastName"/>
        </mx:columns>
    </mx:DataGrid>
    <view: ContactViewer
        contact="{contactsDataGrid. selectedItem}"
        x="318" y="10">
    </view: ContactViewer>
</mx: Application>

The problem is the dataProvider property of DataGrid. It's unable to figure out how to parse the data, so it throws a warning. This can be resolved with casting. We can tell the dataProvider what it should be and it will remove the warning. Here is the code that will remove the warning.

dataProvider="{XMLList(XML(contactsService.lastResult).contact)}"

contactsService.lastResult is an XML object. There are multiple children in the object. We can then cast the XML object as an XMLList to use contact child node.

Feel free to leave a comment if you have any questions.

Wednesday, November 18, 2009

Flex: TileList cell switching/redraw problem using an itemRenderer

While working with the TileList component I ran into a very odd issue. Images would move around while scrolling up and down. Also when I updated the dataProvider the TileList didn't display the new information. Here is an example so you can see what is going on. You can view the source the source by right-clicking and selecting "View Source".

After a lot of research, and a post on StackOverflow, I figured out what was going on. My broken example relies on a MXML completion method (init, creationComplete, etc..)  to set the source of the image in the itemRenderer.

index.mxml
<mx:Component>
    <itemRenderers:ImageTile_bad />
</mx:Component>

ImageTile_bad.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Image xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()">
    <mx:Script>
        <![CDATA[
            /**
            * This is an example of how not to use an item render in a TileList  
            * */
            private function init() : void {
                this.source = data;
                this.name = data.toString().split("/").pop().split(".").shift();
            }
        ]]>
    </mx:Script>
</mx:Image>

TileList reuses cells inside the component. I'm not sure why, but can't keep track of where things should render and starts switching images around. I tried overridding the data method and it works, but I wanted to find a solution that doesn't require overriding a private method.

The answer is to use a setter inside the itemRenderer to assign the value to the component. Here is a snip-it of code to show you what I mean.

index.mxml
<mx:Component>
    <itemRenderers:ImageTile img="{data}"/>
</mx:Component>

ImageTile.mxml
<mx:Image xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        <![CDATA[
            /**
            * This is an example of how to use an itemRenderer in a TileList
            * Create a setter that will always update the when the TileList redraws
            * */
            public function set img(value:String) : void {
                //make sure there is something to work with. avoid error# 1010
                if(!value) {
                    return;
                }
                this.source = value;
                this.name = value.toString().split("/").pop().split(".").shift();
            }
        ]]>
    </mx:Script>
</mx:Image>

When TileList redraws the cell it will pass data into the img setter. This will make sure that the cell receives the correct information when it redraws. Also switching the dataProvider on the TileList works properly now. Here is a link to the working example that has available source code. Feel free to contact me if you have any questions.

Thursday, November 12, 2009

Flash / ActionScript 3: Event Bubbling Example

Previously I wrote an article that showed an example of Event Bubbling with Flex. I wanted to write a similar example for ActionScript 3. The principle is the same, but it works just a little different.

Any class involved in bubbling must extend DisplayObjectContainer. Sprite is the most basic DisplayObjectContainer class and most examples I see use it, so that's what I will use. I gave a brief overview of how event bubbling works in the Flex example that I won't repeat here.

I'm creating three classes that include each other. The primary class includes Level1. Level1 includes Level2. Level2 includes Level3. Level3 triggers an event when it's added to the stage. The event from Level3 will bubble through Level2 and Level1 to the primary class without re-dispatching it.

event_bubbling_as.as
package {
    import flash.display.Sprite;
    import flash.events.Event;
    
    import obj.Level1;
    import obj.Level3;

    public class event_bubbling_as extends Sprite
    {
        private var _level1:Level1
        
        public function event_bubbling_as()
        {
            _level1 = new Level1;
            _level1.addEventListener(Level3.EVENT, onEvent);
            
            addChild(_level1);
        }
        
        private function onEvent(event:Event) : void {
                trace('caught event from level 3');
        }
    }
}

Level1.as
package obj
{
    import flash.display.Sprite;
    
    public class Level1 extends Sprite
    {
        private var _level2:Level2;
        
        public function Level1()
        {
            trace("in level 1");
            _level2 = new Level2;
            
            addChild(_level2);
        }
    }
}
Level2.as
package obj
{
    import flash.display.Sprite;
    
    public class Level2 extends Sprite
    {
        private var _level3:Level3;
        
        public function Level2()
        {
            trace("in level 2");
            _level3 = new Level3;
            
            addChild(_level3);
        }
    }
}
Level3.as
package obj
{
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class Level3 extends Sprite
    {
        public static const EVENT:String = "level3";
        public function Level3(){
            trace("in level 3");
            
            //trigger event when the object is added to the stage
            addEventListener(Event.ADDED_TO_STAGE, launchEvent);
        }
        
        public function launchEvent(event:Event) : void {
         var newEvent:Event = new Event(EVENT, true, true);
         dispatchEvent(newEvent);
        }
    }
}
You can download the Flex Project Archive example here. This can be directly imported into Flex. Run it in debug mode to see how each level is triggered.

Sunday, November 1, 2009

Flex: Event Bubbling Example

A refactor it gave me a chance to update the way I handled events. This page on Adobe's site explains the event bubbling model. To give a brief overview there are three phases: Capture, Targeting and Bubbling. The Capture phase will pass through each branch of a DisplayObject tree until it reaches the last node. The Targeting phase will look for objects that have event listeners bound to them. The Bubbling phase ascends the DisplayObject tree from the last node to the first node and activates the event listeners. Only DisplayObjects have a Capture and Bubbling phase.

Here is some example code I made in MXML that shows how event bubbling works. There are four files. The Application file includes Layer1. Layer1 includes Layer2. Layer2 includes Layer3. When Layer3 is created it will throw an event. The first property of the event is the string that will trigger event listeners, the second allows the event to bubble through the DisplayObject tree. The third allows the event to be canceled at any of the DisplayObjects it passes through.  The event will bubble through each DisplayObject and back to the Application without manually passing it forward.

UPDATE
If you're looking for an example of event bubbling in ActionScript please view this article.

index.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" styleName="plain">
    <mx:Script>
        <![CDATA[
            import obj.Level3;
            import obj.Level1;
            
            private var _level1:Level1;
            
            private function init() : void {
                trace("in the base");
                _level1 = new Level1;
                
                //add eventListener
                _level1.addEventListener(Level3.EVENT,onEvent);
                
                addChild(_level1);
            }
            
            private function onEvent(event:Event) : void {
                trace("picked up event from Level3 ");
            }
        ]]>
    </mx:Script>
</mx:Application>


Layer1.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()">
    <mx:Script>
        <![CDATA[
            private var _level2:Level2;
            private function init() : void {
                trace("in level 1");
                _level2 = new Level2;
                addChild(_level2);
            }
        ]]>
    </mx:Script>
</mx:Canvas>

Layer2.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()">
    <mx:Script>
        <![CDATA[
            private var _level3:Level3;
            private function init() : void {
                trace("in level 2");
                _level3 = new Level3;
                addChild(_level3);
            }
        ]]>
    </mx:Script>
</mx:Canvas>

Layer3.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="init()">
    <mx:Script>
        <![CDATA[
            public static const EVENT:String = "level3";
            private function init(): void {
                trace("in level 3");
                var event:Event = new Event(EVENT,true,true);
                dispatchEvent(event);
            }
        ]]>
    </mx:Script>
</mx:Canvas>

You can download the Flex Project Archive example here. This can be directly imported into Flex. Run it in debug mode to see how each level is triggered.

Thursday, October 29, 2009

Flex: Problems reusing the HTTPService class

UPDATE: This problem occurred because of a bug in the 3.4 SDK. This bug does not exist in 3.2 or lower. I've opened a bug with adobe on the issue.

UPDATE 2: The issue has been resolved in a new nightly build of the SDK. It should be fixed when 3.6 is release.

I ran into an issue using the HTTPService object that involved removing event listeners that were added inside MXML.

Here is a snippet of code in the project. This will open an xml file and load some data into a List.

//this will fetch all our content.
private var _httpService:HTTPService = new HTTPService; 

private function init() : void {
    _httpService.url = "stub/data/albums.xml";
    _httpService.resultFormat = "e4x";
    
    //set up http call
    _httpService.addEventListener(ResultEvent.RESULT, populateList);
    _httpService.send();
}

private function populateList(event:ResultEvent) : void {
    //set the data provider
    albumsComboBox.dataProvider = event.result.album;
    
    //remove listener
    _httpService.removeEventListener(ResultEvent.RESULT, populateList);
}

This will open another xml file and populate the TileList with images.

private function loadAlbum(event:ListEvent) : void {
    _httpService.url = "stub/data/" + event.currentTarget.selectedItem.@images;
    _httpService.resultFormat = "e4x";
    
    //set up http call
    _httpService.addEventListener(ResultEvent.RESULT, populateTilelist);
    _httpService.send();
}

private function populateTilelist(event:ResultEvent) : void {
    //set the data provider
    imageGrid.dataProvider = event.result.photo;
    
    //remove listener
    _httpService.removeEventListener(ResultEvent.RESULT, populateTilelist);
}

When loadAlbum calls send() it will call populateList first and then goto populateTilelist. removeEventListener didn't work. I posted a question to StackOverflow with the problem and got some great answers.


To get around this problem I created a HTTPService wrapper that can be reused with no issues because it's an ActionScript Class. It's very light weight, doesn't include everything under the sun, but it gets the job done in a pinch. This is the 3rd revision of the class. It's been cleaned up and there are fewer methods now.

package util
{
    import mx.controls.Alert;
    import mx.rpc.AsyncResponder;
    import mx.rpc.AsyncToken;
    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;
    
    public class HTTPServiceWrapper {
        //reference for connections
        private var _httpService:HTTPService;
        
        private var _alertTitle:String = "HTTPService: An error occured";
        
        // Holds all the tokens and callbacks
        private var _processingQueue : Object = {};
        
        /**
         * Create the HTTPService 
         * 
         */
        public function HTTPServiceWrapper() : void {
            //create the service
            _httpService = new HTTPService;
        }
        
        /**
         * Get content from URL 
         * @param url
         * @param resultFormat
         * @param callBack
         * @param request
         * @param returnErrorEvent
         * 
         */
        public function getContent(url:String,
                                    resultFormat:String,
                                    callBack:Function,
                                    request:Object = null, 
                                    returnErrorEvent:Boolean = false) : void {
            var asyncToken:AsyncToken;
            var internalIResponder:IResponder;
            
            //set the url and result format
            _httpService.url = url;
            _httpService.resultFormat = resultFormat;
            _httpService.request = null;
            
            //check for key/value pairs to be sent in the url
            if(request) {
                _httpService.request = request;
            }
            
            //send the request
            asyncToken = _httpService.send();
            internalIResponder = new AsyncResponder(onGetContentHandler,onFault, asyncToken);
            asyncToken.addResponder(internalIResponder);
            
            //give token unique ID
            asyncToken = tokenID(asyncToken);
            
            _processingQueue[asyncToken.ID] = new QueueObject(callBack,returnErrorEvent);
        }
        
        /**
         * This is the handler event for getContent. The callBack should accept a ResultEvent
         *  
         * @param event
         * @param token
         * 
         */
        private function onGetContentHandler(event:ResultEvent, token:AsyncToken) : void {
            var queueObject:QueueObject = _processingQueue[token.ID];
            
            queueObject.callBack(event);
        }
        
        
        /**
         * This is the fault event for the class. The callBack should accept a null ArrayCollection and a FaultEvent if
         * you want to handle the error.
         *  
         * @param event
         * @param token
         * 
         */
        private function onFault(event:FaultEvent, token:AsyncToken) : void {
            var queueObject:QueueObject = _processingQueue[token.ID];
            
            //handle the fault
            if(queueObject.returnErrorEvent){
                queueObject.callBack(null, event);
            }
            else {
                var displayMessage:String = event.fault.faultString;
                displayError(displayMessage);
                queueObject.callBack(null);
            }
        }
        
        
        /**
         * This will add a unique identifier to a token 
         * @param token
         * @return 
         * 
         */
        private function tokenID(token : AsyncToken) : AsyncToken {
            token.ID = Math.random();
            return token;
        }
        
        /**
         * Displays the error on a fault event in the content service 
         * @param event
         * 
         */
        private function displayError(displayMessage : String) : void {
            Alert.show(displayMessage, _alertTitle, Alert.OK);
        }
    }
}

class QueueObject{
    public var callBack:Function;
    public var returnErrorEvent:Boolean;
    
    public function QueueObject(callBack:Function, returnErrorEvent:Boolean){
        this.callBack = callBack;
        this.returnErrorEvent = returnErrorEvent;
    }
}


Using the class is really simple. Use getContent and pass it the file you want to load, the format it should be loaded in and the call back you want it to call after the file is retrieved. There are two extra properties I'm not using right now, but they will be helpful in the future. The fourth parameter accepts an Object of key/value pairs to be sent with the URL.The fifth parameter lets you capture the result of an error if one occurs. The call back should accept a FaultEvent object if you want to capture the error. If you let HTTPServiceWrapper handle the error an Alert window will pop up showing the error.
//http wrapper
private var _httpServiceWrapper:HTTPServiceWrapper = new HTTPServiceWrapper;

/**
* Runs when the application loads
* */
private function init() : void {
    //get the list of albums
    _httpServiceWrapper.getContent("stub/data/albums.xml", "e4x", populateList);
    
    //set event listeners for app
    albumsComboBox.addEventListener(ListEvent.CHANGE, loadAlbum);
}

/**
* This will populate the album list
* */
private function populateList(event:ResultEvent) : void {
 //if the result is null don't set it
 if(!event) {
  return;
 }
 
 //set the data provider
 albumsComboBox.dataProvider = event.result.album;
}

/**
* This will fetch the selected album
* */
private function loadAlbum(event:ListEvent) : void {
    _httpServiceWrapper.getContent("stub/data/" + event.currentTarget.selectedItem.@images, "e4x", populateTilelist);
}

This cut quite a bit of bloat out of my app and is also very reusable which saves time in the long run. The final version of this code is hosted here. You can view source on it by right-clicking in the app and selecting "View Source". Please let me know if you have any questions about it.

Flex: New Project Settings

When starting a new Flex project there are a few settings I like to use by default.

Changes to Flex Compiler
Flex Compiler options for a project can be found by right-clicking the project and selecting properties. Select Flex Compiler from the menu on the left. The following properties should be added to the Additional compiler arguments field.

When you're reading local xml files or image you might run into a sandbox security Error# 2140 or ReferenceError Error# 1069 using the HTTPService object. Use this switch to stop the error.
-use-network=false


The loading background color of a Flex app can be changed. Use this switch to change the property.
-default-background-color [HTML COLOR VALUE]
I typically use #FFFFFF.


Changes to the Application
I like to use a simple background for Flex apps. Add this property to the mx:Application to make the background white.
styleName="plain"

Friday, October 23, 2009

Android: Motorola Droid

This phone has caught my eye. I've had an iPhone since launch but have become a bit frustrated with it. It's a beautiful phone, but a bit of a walled garden. Android has always been interesting to me, but now it seems to be catching up with the iPhone.

I've started a wish list of things I hope the Droid will do. I'm updating it with links to articles that verify the features as time goes along.

http://spreadsheets.google.com/pub?key=tlQ3UVqx9gnphVI6h1aKTig&output=html

Tuesday, October 13, 2009

Flash / ActionScript 3 / Flex : Reading browser cookies

Part of an ActionScript 3 project I was working on required me to pull cookies from the users browser into Flash. I tried hunting around google to find a good method to achieve this, but found a lot of articles that wanted you to alter the embed code for flash. I wanted to find a way inside Flash to read the users cookies.

I wrote some code to do something similar in ActionScript 2 that used LoadVars. This class has been removed in ActionScript 3.

This is the ActionScript 3 code I came up with. It uses ExternalInterface to execute a bit of javascript that will pull the cookies directly into flash. It alters the cookie string to make it look like a URL and runs it through URLVariables.

package {
    import flash.display.Sprite;
    import flash.external.ExternalInterface;
    import flash.net.URLVariables;
    
    public class BrowserCookies extends Sprite
    {
        //this will parse the cookie data
        private var _urlVariables:URLVariables;
        
        /**
         * Return all the cookie values in one object
         * @return URLVariables 
         * 
         */
        public function get urlVariables() : URLVariables {
            return _urlVariables;
        }
        
        /**
         * Return one cookie value
         * @param value String
         * @return String
         * 
         */
        public function getCookieValue(value:String) : String {
            var returnValue:String = "";
            
            if(_urlVariables && _urlVariables[value]) {
                returnValue = _urlVariables[value];
            }
            
            return returnValue;
        }
        
        /**
         * This will connect to the browser and pull cookies into flash 
         */
        public function BrowserCookies() : void{
            //this will hold the data returned from javascript
            var browserCookieString:String;
            
            //pull the data from javascript
            browserCookieString = ExternalInterface.call("function(){return document.cookie}");
            
            //replace ; with & to make it look like a url
            browserCookieString = browserCookieString.replace(/;\s/g, "&");

            //parse the cookie string into variables. you can now access cookie variables as properties of this object
            if(browserCookieString) {
                _urlVariables = new URLVariables(browserCookieString);
            }
        }
    }
}


Now you can access any cookie property inside flash. Here is a quick example of how to use the class. Assume BrowserCookies.as exists in the same folder as the example class.
package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    
    public class Index extends Sprite{
        public function Index(){
            //this will pull all the cookies out of the browser
            var urlVars:BrowserCookies = new BrowserCookies;
            var textField:TextField = new TextField;
            
            textField.width = 200;
            textField.height = 200;
            textField.text = urlVars.getCookieValue("today");
            
            addChild(textField);
        }
    }
}

I've uploaded a Flex Projext Export version of this example available here. Feel free to contact me if you have any questions.

Flash / Actionscript 3: DataFormat doesn't exist

I was looking through the ActionScript 3.0 Cookbook today and started experimenting with the URLLoader class. The example on page 437 talks about setting the format for the incoming URL. When setting the dataFormat property of URLLoader it suggests using the constant called DataFormat. The only problem is this constant doesn't exist. It's a typo.

The real value is called URLLoaderDataFormat. You can read more about it here.

Sunday, October 11, 2009

PHP: Creating your own custom ini config file

In a continuing effort to make my life more difficult I've decided to write my own MVC. I could have easily used one of many frameworks(Zend Framework, Cake, Symfony, etc ...) but I was really interested in what it takes to write one. So far it's been a great experience and I've learned a lot about PHP5.

One of the things I noticed about a lot of the MVCs is they store settings in an external ini file. I had no idea how they pulled the information out of them until I ran across this article on IBM's website. They mentioned a function called parse_ini_file. This function has been around since PHP4, but I never knew about it. You could fill the grand canyon with the things I don't know, but let's focus on this for now.

This function allows you to read a external ini file and it returns an array of properties. You can also configure it to return an associative array of values grouped by category.

This allowed me to move a lot of settings into an external file and clean up a huge chunk of code. The problem is many of the variables I defined were dynamic. parse_ini_file doesn't evaluate external PHP code. The trick to that is to run eval on things you want it to parse.

Here is an example of some code I have stored in an external file.
[define]
PATH_HTTP = "http://{$_SERVER['HTTP_HOST']}/test_site/"

I created a function that will parse the ini file and will run eval on anything in the define group.
//configure define. this will parse php code
if(isset($ini['define']))
{
  foreach($ini['define'] as $key=>$item)
  {
    define($key, eval("return \"{$item}\";"));
  }
}

The important part to note when using eval is that it doesn't return a value. If you want to capture the evaluated variable prefix the variable with "return" and make sure to end the line with a ;.

Update
An important thing to note is that ini files can be read very easily in a web browser. You'll want to set up a .htaccess file that blocks viewing of ini files. You can copy-paste this into a .htaccess file at the root of your site.
<files *.ini>
order allow,deny
deny from all
</files>

Thursday, October 8, 2009

Javascript: Adding options to a select element

I've started working with javascript more and more now. I'm leaning away from using innerHTML and started creating the objects instead. As with anything javascript related Internet Explorer will cause more problems than solutions.

When you're creating a new option element that will be added to a select element IE wants to do it one way while everyone else can handle it another way. I'll show the first way I tried to tackle it, and then show the cross browser way to handle it.

I set up a try, catch block that would try IE first. If an error occurred it would fall back to the second method that works in most browsers.


//IE code
try
{
obj_option = document.createElement('<option value="test value"/>');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
}
//everyone else
catch(e)
{
var obj_option = document.createElement('option');

obj_option.text = "option text value";
obj_option.value = "test value";
}


Internet Explorer wants to place the value inside of the createElement method while other browsers can handle the assignment on the object property. Also IE wants the text added with createTextNode. It's a pain to have two methods for something so simple. After a bit of experimentation and research I have a method that works for all browsers.


var obj_option;
var obj_text;

obj_option = document.createElement('option');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
obj_option.setAttribute("value", "test value");


This is much cleaner and easier to maintain. setAttribute is also a handy method for assigning non standard properties to an object. Some client-side form validation scripts want to add proprietary properties to a tag. Using setAttribute is the easiest way to create them.

Sunday, October 4, 2009

Zend Studio 6.1: SVN update on Snow Leopard

I ran into an issue with a svn project today so I decided to create a new repository. The thing I didn't realize is that SVN has been upgraded to version 1.6.2 in Snow Leopard. This caused a major conflict with Zend Studio 6.1. When I tried to browse the repository with a project import it couldn't read the SVN tree.

After a lot of searching I figured out how to update the SVN plug-in.

Goto Help => Software Updates => Find and Install.
Select Search for updates of the currently installed features and click Finish.

When the search finishes check "Subversive update site 2.0.x".



Click the "Search" button. There should be an option listed called "Subversive update site 2.0.x". If you check the box you will get an error on a JavaHL 1.4.5 Win32 Binaries (Optional). Click the arrow to the left of to expose more options. Click the arrow to the left of "Subversive SVN Connectors" and uncheck all the JavaHL Win32 Binaries. This should allow you to install the new update.



When the update has finished Zend will prompt you to allow a restart. Once it closes you will have to restart it. You'll need to select the new SVN plugin. Goto Zend Studio for Eclipse => Preferences. Goto Team => SVN. Click the SVN Connector tab and select "SVN Kit (SVN/1.6.2 SVNKit/1.3.0)" from the SVN Connector down down.



You should be able to import a project from a new version of SVN without a problem.

Update 10/05/2009
I may have left out a key piece of resolving the SVN issue. I was trying many things at the time, and this might be one of the parts that made it work.

There is a new version of the SVNKit plug-in for eclipse. I don't have the exact steps at this moment to install them in Zend Studio, but the site has the steps for Eclipse and they're pretty close. You can view them here.

Thursday, October 1, 2009

Flex: New Classes won't import into a project from a library

I ran into an issue while working on a Flex project where a new class I created in a Library wouldn't import, or auto-complete in the working project. It was also throwing a few different errors.

This was displayed at Runtime:
Variable xxx is not defined.

This was displayed in the Problems window:
Access of undefined property xxx.

Sometimes Flex doesn't update the Build Path to include new classes. If you run into this issue you can check to see if everything in your project is included in the Build Path.

Right-click on your Library project and goto Properties. Select "Flex Library Build Path" on the left and look in the Classes tab on the right. Scroll through the list to make sure everything is selected. If you're getting the errors above there is more than likely something in the list that isn't checked.

Friday, September 25, 2009

Flex / ActionScript: Debugging

I ran into an issue while working on a project in flex. I was trying to figure out why something wasn't working and had a large amount of trace calls in my code. It was a complete pain to remove them all. This lead me to develop a debug class that I can turn off at a page level or you can turn if off in the class. It's a first draft. I'd like to make it a Singlton so I can turn it off for the whole project at a page level, but that's for later.

package 
{
public class Debug
{
private var _displayDebug:Boolean = false;
private var _incomingClass:String = "";
private var _logArray:Array = [];

//to stop all debugging set this to false
private var _turnOffDebug:Boolean = false;

/**
* Create the debug object 
* @param display
* @param fileName
* 
*/
public function Debug(display:Boolean, fileName:String): void {
_displayDebug = display;
_incomingClass = fileName;
}


/**
* Display a trace message 
* @param msg
* 
*/
public function log(msg:String) : void {
//override anything a debug passes in
if(_turnOffDebug) {
return;
}

if(!_displayDebug) {
return;
}

var logMessage:String = "["+ new Date() +"]" + _incomingClass + ": " + msg; 

trace(logMessage);
_logArray.push(logMessage);
}
}
}


Using the class is simple. First create an instance of the class and tell if wither you want it on and what the name of the script you're calling it from is named.
var debugObj:Debug = new Debug(true, 'main.mxml');


To turn off debugging for the script just set the first parameter to false. To turn it off for the whole project change the class variable _turnOffDebug to true;

Use the log method to display your statement in the debug area of flash or flex.
debugObj.log('debug statement');


This is a what the trace statement should look like.
[Fri Sep 25 15:03:21 GMT-0700 2009]main.mxml: debug statement

If you have any feedback please send me a message.

Tuesday, September 22, 2009

Snow Leopard (10.6): Show the month and day in the menu bar

Snow Leopard(10.6) has a new option for Date & Time in System Preferences. You can now have the day, month and day of the month show in the menu bar. You could do this before, but it required a bit of hacking in the International section.

Goto System Preferences and select Date & Time. Click the Clock tab and check "Show the day of the week".




Your menu bar should look something like this now.



Saturday, September 19, 2009

PHP: Simple register_globals workaround

Working with an old php4 project in php5 can expose some bad programming practices and create bugs. The first problem is relying on register_globals. I don't want to turn this on because it injects variables into the page scope. I also don't want to update the whole project to not rely on it.

The simple way around this is to write something that injects the variables into the project scope. This function will read all the variables from the url and inject them into the project scope. You should never rely on register_globals, but if you don't want to update old code this is an easy workaround.

function register_globals()
{
  //if register_globals is on then return
  if(ini_get("register_globals")) return;

  //inject URL vars into scope
  foreach($_REQUEST as $key=>$item)
  {
    $GLOBALS[$key] = $item;
  }
}

MAMP (Pro): Making changes to php.ini

I'm using MAMP Pro and trying to get an old project built in PHP4 up and running. The project depends on register_globals to be turned on. I tried to update the php.ini file located in MAMP/conf/php4/php.ini, but nothing would change when I looked at the phpinfo() output.

After banging my head against the wall for awhile I turned to the forums at mamp.info. There is an importance difference between MAMP and MAMP PRO. If you want to update any of the ini file settings while using MAMP PRO goto File => Edit Template and select the ini you want to update.

The full forum post can be found here.

Friday, September 18, 2009

Flash / ActionScript: String padding (leading zero)

I was working on a date/time format in Flash and needed a way to pad values out so they always took up the same amount of space. For example making sure a month always has two digits. Making sure it displays a "05" instead of "5". I couldn't find anything built into AS2 or AS3 to do this so I wrote something that would. It allows you to pass in a value and pad either the left or right side up to a given amount of characters.

/**
* This function will pad the left or right side of any variable passed in
* elem [AS object]
* padChar: String
* finalLength: Number
* dir: String
*
* return String
*/
function padValue(elem, padChar, finalLength, dir)
{
  //make sure the direction is in lowercase
  dir = dir.toLowerCase();

  //store the elem length
  var elemLen = elem.toString().length;

  //check the length for escape clause
  if(elemLen >= finalLength)
  {
    return elem;
  }

  //pad the value
  switch(dir)
  {
    default:
    case 'l':
      return padValue(padChar + elem, padChar, finalLength, dir);
      break;
    case 'r':
      return padValue(elem + padChar, padChar, finalLength, dir);
      break;
  }
}


This function accepts an object that can be converted to a string with the toString method, the character you want to use for padding, the final length of the string and wither you want it padded on the left or right side using the character "l" or "r".

For example if you have a number you want padded with three 0 so the final outcome will look like "0005" you would call the function like this.
var exampleNumber:Number = 5;
padValue(exampleNumber, "0", 4, 'l');


If you want to use this in FLEX you might want to type the parameters on the function and give it a return value.

Friday, August 28, 2009

Actionscript/Flex: Number Formatting (prefix a leading zero)

I was looking for a simple way to prefix a single digit number with a zero. I thought NumberFormatter would be able to do it, but turns out it can't. There is a project hosted on google for a bunch of tools that aren't included in Flex or Actionscript 3.

http://code.google.com/p/as3corelib/

One of these tools allows you to prefix a number with a zero. It's in com.adobe.utils.NumberFormatter. The method is addLeadingZero(). It's kind of confusing having two NumberFormatter classes, but I didn't write it so there you go.

There's a lot of good stuff in the project, so if you're looking for something Flex doesn't do it might be in there.


I also wrote my own string padding function that can be used in Flex, AS2 or 3. Please see this post for more details.

Thursday, August 20, 2009

Flex: Using the Tasks window

I've been using Zend Studio for awhile and became very used to the TODO area that lets you track notes you've placed in code. I've wanted something similar for FLEX but there wasn't anything built in.

Turns out there is a plugin for this very thing! You can read more about it here.

Wednesday, August 12, 2009

Flex: Working with LinkBar viewstates

I've started experimenting with the LinkBar component for some navigation elements. I didn't want to use ViewStates because I'm loading and unloading items in a main window. I wanted to use it to capture navigation changes.

You can capture clicks on each part of a LinkBar and then do what you want from there. This is the code I used.


<![CDATA[
import mx.events.ItemClickEvent;
import mx.collections.ArrayCollection;

private var links:Array = [{label:'Browse', id:'browseLink'},{label:'Search', id:'searchLink'}];

[Bindable]
public var linkBarDataProvider:ArrayCollection = new ArrayCollection(links);

private function init() : void {
linkBar.addEventListener(ItemClickEvent.ITEM_CLICK, handleLinkBar);
}

private function handleLinkBar(event:ItemClickEvent) : void {
trace('item clicked: ' + event.item.id);
}
]]>




I created an Array with each navigation item I wanted and gave it a identifier. An event listener was set on the LinkBar to watch when items inside are clicked. The triggered event is ItemClickEvent.ITEM_CLICK. The event is passed to a function that will then look at the property called item. item is a reference to the element from the Array it used to create the navigation element. After I know which link was clicked I can load or unload the next item in the display.

The example was based on the post I found here.

Monday, August 10, 2009

Flex: using mxml files as classes

Another thing I learned while working with Flex is that each MXML file can be treated like a class. You can import them and call the functions defined within like a method. This can be very useful when loading element into the stage.

It's also important to note that methods and properties are available once you've created the object. If you have defined something to run on creationComplete it won't run until the object is added to the stage with addChild.

main.mxml




import util.Example;
private function init() : void {
var example:Example = new Example;

//run function from external MXML file
example.example_function();

//add the mxml file to the stage
addChild(example);
}
]]>




util/Example.mxml




public function example_function() : void {
trace('running function example');
}

private function init() : void {
trace('now all the elements inside are available');
}
]]>



Flex: setTimeout and setInterval replacement

One of the things I learned while moving from AS2 to AS3 is that setTimeout no longer exists. It's been replaced with a Timer class. It can be used like setTimeout or setInterval.

This is how you would use Timer as a setTimeout. The variable tTimer is set to launch 500 ms after start() is run. It will run once and then stop.

import flash.events.TimerEvent;
import flash.utils.Timer;

private function Timer_example()
{
var tTimer:Timer = new Timer(500, 1);
tTimer.addEventListener(TimerEvent.TIMER, onTimer);
tTimer.start();
}
private function onTimer(event:TimerEvent)
{
trace('callback event has run');
}


Timer can also function like setInterval. The second parameter tells timer how many times it should run. So if you want something to run 100 times then set timer will look like this.

var tTimer:Timer = new Timer(500, 100);

If you want it to run forever then set the interval to 0. If you do this make sure the timer is a global variable so you can run .stop() when it no longer needs to run.

Thursday, August 6, 2009

Flex: Passing a reference from a mxml component to a method or function

I ran into a situation where I needed to pass a reference from a mxml component to a function. It's easy if you have an ID assigned to the component, but if it's in an itemRenderer that makes it tougher because you don't want duplicate ID's.

You can pass a reference from a component to a function using the createComplete event.







You can also see another example at this blog post.

Monday, August 3, 2009

Flex: Event Listeners and Array Collections

While working with some code I ran into a situation where I needed to know when an ArrayCollection was updated. Normally an event is triggered when using addItem, but I needed to know when it was set to another ArrayCollection. It's not very obvious, but it is possible.

ArrayCollection is really a wrapper for an Array. You can access the "real" array in an ArrayCollection by using ".source". When you set the source property an event called "listChanged" is triggered. You can watch for this event and then do whatever you need.

So this

var newAC1:ArrayCollection = new ArrayCollection;
var newAC2:ArrayCollection = new ArrayCollection;
newAC1 = newAC2;


Is the same as this, but with an event trigger.

var newAC1:ArrayCollection = new ArrayCollection;
var newAC2:ArrayCollection = new ArrayCollection;

newAC1.addEventListener('listChanged', function(event:Event){trace('changed');});

newAC1.source = newAC2.source;

Thursday, July 23, 2009

Flex and dataProviders

Most seasoned Flex coders probably know this, but as always I'm still learning. When creating a dataProvider for a List or TileList it's best to use a ArrayCollection instead of an Array.

Arrays will work if you set them as a dataProvider, but sometimes they can act weird. I just spent the last hour trying to get a TileList to update that had a Array dataProvider. Once I changed it to an ArrayCollection it worked without a problem.

So learn from my mistake. Don't use Arrays for dataProviders.

Wednesday, July 22, 2009

PHP: Error logging

Work with other languages has exposed me to new ways of logging errors and/or debugging code on web pages. I'm not sure how most php developers log errors or debug code so I can only guess it was similar to the way I would do it. By that I mean using echo in the middle of some HTML. It gets the job done, but it's kinda ugly.

I've since started using a cleaner method of logging errors. It's not as robust as a class, but it's better than throwing code out on a page. I've started using the error_log function wrapped in another function to control when it should output the error to a log.


function debug($allow_debug, $msg)
{
if($allow_debug)
{
error_log($msg."\n", 3, '/path/to/phperror.log');
}
}

When the function is used I pass a boolean that states wither I want the error passed out to the log. Typically I would set a variable at the top of the script and pass it into each instance of debug.

error_log takes three parameters. The first is the message that I want to pass out to the log. The important part on this input is the line return. That way each error starts on a new line. The second is the type of message I'm logging. The third is the location of the log file. Make sure it has the correct permissions so PHP can write to it.

You can view more information on error_log here.

Thursday, June 25, 2009

Flex: Multiple Application MXML files

At a point in a project I'm currently working on we had to intergrate with another application. That means creating a new Application MXML file and degrading the current Application MXML file. Creating the new Applicaion was simple, but Flex was confused as to which file it should use to launch the project. This can be updated in the project properties.

1) Right-click the project and goto Properties
2) Goto the "Flex Applications". There you will see all the files that are marked as Applications.
3) Select the new Applicaion file and click "Set as Default". When you click "Run" or "Debug" it will use this file to launch your project.
4) Click on the old Applicaion file and click "Remove". This won't delete the file.

Hope this makes transitioning to a new project easier.

Also remember to remove any styleName properties from your old Application tag.

Wednesday, June 24, 2009

Flex: Switching the debug default browser

I've started working in Flex quite a bit now. One of things that has bothered me is Flex always launches a debug window in Internet Explorer. I've been having some problems with the browser and would like to use something different, but couldn't figure out how to switch it. Someone showed me how this morning.

1) Goto Window => Preferences
2) Goto General => Web Browser
3) Select the browser you want to launch in the "External Web browsers" window.

Now your debug session should launch in your browser of choice.