Archive for April, 2008

29th Apr 2008

Setting the Initial Sort for a Flex DataGrid Component

A client asked me recently to to have the data being displayed in a Data Grid be initially sorted by store name (See Creating an Image Reflection in Flex to view the project in question). The way you do this is by sorting the Datagrid’s data provider. To do this, you need to create a sort object, assign it some sort fields, set that sort object as the dataprovider’s sort object (so you have to be using some sort of sortable collection to do it this way) and refresh the collection. This looks something like this:

private var storesXMLCollection:XMLListCollection = new XMLListCollection();
private var initSort:Sort = new Sort();

/ /SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Boolean = false) so in this case companyName is the XML Node I am sorting on and the second parameter indicates that the sort should be case insensitive.

this.initSort.fields = [new SortField(“companyName”, true)];

this.storesXMLCollection.sort = this.initSort;

//once the sort object has been applied, refresh the collection.

this.storesXMLCollection.refresh();

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, Flex Comments No Comments »

29th Apr 2008

Nothing Left To Take Away

Recently I have bee reading this book
Beautiful Code : Leading Programmers Explain How They Think by Greg Wilson (Editor) , Andy Oram (Editor)

and I just got through a chapter entitled “The Most Beautiful Code I Never Wrote”. The main idea expressed in this chapter is that a project is not finished when there is nothing more to add, but rather when there is nothing left to take away.

This immediately struck me as true based on my own experience, but perhaps a bit counter intuitive.  It is easy to conceptualize a task in terms of what needs to be accomplished (added), but we may often forget that it is equally important to review what has already been done to see what can be improved or refined. Many times the first attempt at a project is just an attempt to get it done (normally under the constraints of an unrealistic deadline). Looking back now, most of my best projects (and most satisfying) are the ones I went back and reviewed and found simpler ways to accomplish what I had done.

In the world of tight deadlines, we do not always get the luxury of doing this, however, the sentiment of nothing left to take away is an important one and should at least be remembered if not always implemented.

Some notable quotes from the chapter:

  • Simplicity does not precede complexity, it follows it. (Perlis)
  • Make everything as simple as possible, but no simpler. (Einstein)
  • A designer knows he has achieved perfections not when there is nothing to add, but when there is nothing left to take away (Saint-Exupery)

And to sign off,

If I had more time, I would have written you a shorter letter. (Pascal)

Posted by Posted by Jeremy Wischusen under Filed under Application Design and Architecture, General Comments No Comments »

28th Apr 2008

Setting Up A Global Class Path In Flash

If you are just getting into using classes in Flash, chances are you are probably just creating your class (.as files) in the same directory as your FLA. This is simple, fast and works, but if I want to reuse a class from one Flash piece in another, I now have to copy over all of those class files into my new project directory. If I use that methodology, if I have to update something in one of my classes, I now have to update them in more than one location. This quickly turns into a maintenance nightmare and it turns out there is a simple solution.

Flash (as far back as mx 2007, not sure about older versions) will allow you to select a folder(s) where you can store classes that are used across multiple projects. This is commonly referred to as a class path. When you set up a class path and then do something like:


import com.mydomain.MyClass;
var myInstance:MyClass = new MyClass();

where MyClass is some custom class that you wrote, Flash will now look in your specified class path to see if it can find the corresponding class file (in this case MyClass.as). This means I am now free to use this class in any of my projects without having copy my class file into each project directory.

Please note that I am showing you how to set this for the program as a whole. You can also set this on a per document basis using the publishing settings

So how do we set this little piece of magic up?

  1. Got to the Edit menu and select Preferences.
  2. The following dialog box should appear:
    Flash Preferences
  3. Select ActionScript from the list on the left.
  4. Click the button entitled “ActionScript [version number] Settings” next to the Language label and the following dialog box should appear.
  5. Make sure to hit the + button resetting the entry that reads $(LocalData)/Classes will reset the default class path for Flash and Flash will no longer be able to find its built in classes. Clicking the + sign should make a blank line appear in the list.
  6. Click on the icon that looks like cross hair. This should bring up a file selection dialog box.
  7. Select the folder where you would like to store your classes.
  8. Keep clicking OK until all of the dialog boxes have closed.

Now you have your class path set up. This means that you can start storing you class files in this location. Please take note of the following:

  • Now that you have the class path set up, you can use import statements to bring in your classes just like you do with the standard Flash classes. For example import com.mydomain.MyClass; . Note a few things about the import statement.
    • The actual folder you selected is NOT included in the import statement (in my example C:\asclasses)
    • In import statements, dots = slashes. What I mean by this is that in our example, com.mydomain.MyClass is looking a file named MyClass.as in a folder mydomain that is a subfolder of com (i.e. /com/mydomain/MyClass.as). The beginning folder com in turn is actually a sub folder of the class path (i.e. C:\asclasses\com\mydomain\MyClass.as). Since we have setup C:\asclasses as a class path, Flash automatically looks in that location and we only have to specify the path using the dot syntax from that folder down. If you want to learn more about this dot syntax, do some research on the topic of packages in Flash.
    • As you may have noticed, you leave off the .as file extension.

Now that you have you class path set up, you can truly begin to start creating classes that are reusable across projects and only have to be maintained in one location.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 2, ActionScript 3, Flash, OOP Comments 2 Comments »

25th Apr 2008

Removing All Children From a DisplayObject

Just a quick one. The other day someone asked me about how to remove all sub clips from a movie clip in AS3. I happened to have created a function to do that for one of my projects.

private function removeAllChildren(displayObject:DisplayObjectContainer):void {
while (displayObject.numChildren > 0) {
displayObject.removeChildAt(0);
}
}

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3 Comments No Comments »

24th Apr 2008

DigitallyU Portfolio Software

So this may come off sounding like a bit of an advertisement, but this is one of the major projects I have worked on, so I thought I would mention it.

DigitallyU is the project where I got my start in Flash. We actually started creating it in Flash MX and the final product ended up being produced in Flash 8 (3 years of development in total). The major components of the system are XML, ActionScript, and MDM Script (the scripting language for ZINC, a program that allowed manipulation of the local file system long before Adobe AIR) .

The original idea started out as a method of allowing prospective college students to create multimedia  based portfolios for college admissions. This grew into the idea of portfolios for professionals and as people tested those versions for us they suggested that a generic version for building family media collections would be nice as well. Hence, we ended up with 3 versions; Scholarship, Professional and Scrapbook (the generic version).

The basic methodology of the program is that you select media files (images, sounds, videos and documents) from you local hard drive. For each portfolio the editor tracks the location of the selected files. When you are ready to publish your portfolio you choose from 40 or so templates designed to read exported output. Exporting (aka publishing) a portfolio assembles the selected files along with your selected template into a predefined web ready folder structure that can then be uploaded to the web, or put on some external media device.

The major difference between the version is how much we predefined what sections are in a portfolio. Scholarship includes predefined sections such as SAT scores, Professional mimics a resume and Scrapbook is a free for all. So we were not out simply to provide a generic portfolio tool, but also took into account the final audiences for the portfolios.

Currently, the software is in use at American University, Rutgers, University and the Worchester Preparatory School. We have been told that several students have taken their portfolios to admissions interviews and the response has been very good.

If you would like to play with it, trial version are available on the website http://www.digiallyu.com .

Posted by Posted by Jeremy Wischusen under Filed under Flash, General Comments No Comments »

20th Apr 2008

Creating an Image Reflection in Flex

One of my clients asked me if we could do an image reflection in Flex. Now as far as Flex goes, I am more on the code side so I had no idea how to do this. Luckily, this guy (Ben Stucki) did.

His original version was set to redraw the object using the enterFrame event with the idea that any changes in what was being reflected, would be updated in the reflection. My need was a little simpler than this. I just needed to reflect an image once it had loaded, so there was no need to keep redrawing the image reflection once the load had completed. However, I ran into a little challenge in that even though I was only triggering the reflection code upon completion event of the image load, no reflection was showing up. It turned out that even thought the load had completed, the rendering had not. Hence the reflection had nothing to draw.

The solution I came up with was to give a slight delay between the load event and the reflection rendering using a timer.

Code Excerpt:

private var reflectionTimer:Timer = new Timer(100,1);
private function appInit():void{
storesService.send();
reflectionTimer.addEventListener(‘timer’, createReflection);
}
private function createReflection(e:TimerEvent = null):void{
reflection.drawReflection();

}

<mx:Image complete=”reflectionTimer.start();”

Here is what the final product looks like. This depends on data from an external site, so if something changes on that site, this may stop working. At the time of this witting, the first item in the data grid has an image and should show the reflection. Also, would like to give a shout out to this guy (Kimili) for creating the WordPress Plugin for displaying flash.

Posted by Posted by Jeremy Wischusen under Filed under Flex Comments 1 Comment »

20th Apr 2008

CSS Based Percentage Bar

For one of my projects I had to create a visual representation of two percentages being compared side by side. I decided to do this using divs and CSS. With this design, all I have to do is set a value in my PHP for the width of the div highlighted in bold below and the sizing takes care of itself.

Here is what I came up with:

HTML:

<div class=”scoreBars”>
<div class=”scoreDivider”></div>

<div style=”width: 42%; height: 22px;background-color: #99CC00; position:absolute; top:0px; left:0px”></div>

<div style=” width:100%;height: 22px; position: absolute; z-index: 2; top: 0px; left: 0px;”>
<div style=”float: left; margin-top: 3px; color: rgb(255, 255, 255); font-weight: bold;”> 42% </div>
<div style=”float: right; margin-top: 3px; color: rgb(255, 255, 255); font-weight: bold;”> 58% </div>
</div>
</div>

CSS:

.scoreBars{
position:relative;

width:100%;
border:1px solid #999999;
height:22px;

/*This sets the color representing the right had side of the bars. The left hand value set in the HTML about simply covers this background color, so all I have to do is set the width for the div covering this color.*/
background-color:#3366CC;
}

/*The divider is simply a div with a right border that divides over all length of the bars into halves giving us an indication where 50% is.*/
.scoreDivider{
position:absolute;
width:50%;
border:dashed #FFFFFF;
border-width:0px 1px 0px 0px;
height:22px;
top:0px;
left:0px;
}

Result:

CSS Percent Bars

Posted by Posted by Jeremy Wischusen under Filed under CSS, DHTML Comments 2 Comments »

16th Apr 2008

Sending XML DATA via the POST Method in PHP using CURL

One of the projects I worked on involved sending XML formated data to a remote server via the post method. To do this, we ended up using the PHP CURL extension. You will need this installed on your server for this example to work. You can find installation instructions here.

Sending Page:

The sending page is where we implement our CURL code:

<?php

/*Create a DOMDocument object to build the XML*/
$dom = new DOMDocument();
$dom->formatOutput = TRUE;
$root = $dom->appendChild($dom->createElement(‘request’));
$root->setAttribute(‘clientId’, ‘123’);
$root->setAttribute(‘clientKey’, ’32IFJ23OFIJIWR’);
$root->setAttribute(‘type’, ‘MESSAGE’);
$message = $root->appendChild($dom->createElement(‘message’));
$recipient = $message->appendChild($dom->createElement(‘recipient’));
$type = $recipient->appendChild($dom->createElement(‘type’, 5));
$id = $recipient->appendChild($dom->createElement(‘id’, ‘+16505551212’));
$text = $message->appendChild($dom->createElement(‘text’, ‘Yeah we can send XML’));
$sendXML = $dom->saveXML();

/*Initialize CURL. CURL works in a similar fashion to SESSION in that you have to initialize it and then close it */

/*Initialize CURL and pass it the URL of the page we are sending the data to*/
$curl =curl_init(‘http://localhost/dev/gateway.php’);

/*Set CURL Options. See this page for a description of the option constants.*/

/*In this case we are sending XML, so set the header type to XML*/
curl_setopt ($curl, CURLOPT_HTTPHEADER, Array(“Content-Type:text/xml”));
curl_setopt($curl,CURL_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendXML); // post the xml
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // set timeout in seconds
$xmlResponse = curl_exec ($curl);
curl_close ($curl);

/*Since we set the CURL_RETURNTRANSFER to a value that evaluates to true, the returned response from the page we sent the request to will be printed to the page*/
?>

The Receiving Page:

This example is incredibly simple since all I am trying to demonstrate is the communication of XML POST data between pages/servers. However, since the data is there on the recieving page, you can do with it as you like before returning a response. In this case, all we do is echo back out the passed XML.

<?php
header(‘content-type: text/xml’);

/*Because we passed the XML directly to curl_setopt($curl, CURLOPT_POSTFIELDS, $sendXML) in the sending page, we use HTTP_RAW_POST_DATA’ to access it. If we had done something like curl_setopt($curl, CURLOPT_POSTFIELDS, array (‘xmldata’=>$sendXML) ) , then we would access it via $_POST[‘xmldata’]*/

echo $GLOBALS[‘HTTP_RAW_POST_DATA’];
?>

Result:

The result of this process is the following:

<?xml version="1.0"?>
<request clientId="123" clientKey="32IFJ23OFIJIWR" type="MESSAGE">
  <message>
    <recipient>
      <type>5</type>
      <id>+16505551212</id>
    </recipient>
    <text>Yeah we can send XML</text>
  </message>
</request>

While this example is essentially a round about way of of echoing the XML that was built on the sending page, it is enough to demonstrate the concept of passing XML data via a post request. What you do with the data on the reciving page and what you return is entirely up to you and will depend on what you are trying to accomplish.

Posted by Posted by Jeremy Wischusen under Filed under PHP Comments No Comments »

15th Apr 2008

Using PHP’s DomDocument to Generate XML from an SQL Query

One of my side projects (well many of them now that I think of it) requires me to load data from a database on server into Flash. Back in the old days. and with simple data, I might have done something like:

echo ‘name=’.$name.’&email=’.$email;

… and so on and then load that string into a Flash LoadVars object, on in AS 3 a URLVariables via a URRequest.
This is ok for small simple data, but not so much for large amounts of data requiring a complicated string concatination.

Then one day it dawned on me that you can use the PHP DomDocument object to create a well formatted XML document and skip the whole string concatenation altogether. Furthermore, Flash makes loading external XML from a URL a very simple thing. Hence I could skip the whole LoadVars experience as well.

After doing this once or twice, I also realized that you could pretty much automate the whole process of generating the XML document inside the while loop for fetching the database rows. Essentially what I end up with is an XML document with tag names that match the column names of the table I am performing the query on with the node values matching the value for that row of the query.

Below is a sample of this and the output it produces with some of the more sensitive details removed:

PHP:

<?php
header (“content-type: text/xml”);

/*Create a DomDocument Object*/

$dom = new DomDocument(‘1.0’);
$dom->formatOutput = true;

/*Create a root element for the XML document*/

$root = $dom->createElement(‘stores’);

$dom->appendChild($root);
mysql_connect(‘localhost’,’username’,’password’) or die(‘Could not connect to db server’);
mysql_select_db(‘database_name’) or die(‘Could not select DB’);

$sql = ‘SELECT * FROM table_name’;

$call = mysql_query($sql);
while($row = mysql_fetch_assoc($call)){
/*For each row returned, create a node to represent that row*/

$store = $dom->createElement(‘store’);
$root->appendChild($store);

/*Loop through the returned row and create a node that matches the column name and use the value for the node’s value*/

foreach($row as $key=>$val){
$col = $dom->createElement($key,stripslashes($val));
$store->appendChild($col);
}
}
/*echo out the XML to the page*/

echo $dom->saveXML();
?>

Output (edited for sensitive data, but representative) :

<stores>
<store>
<companyName>Diamond Imports</companyName>
<companyDesc>
Diamond Imports is one of Australia’s largest diamond importers specializing in loose diamonds, certified diamonds, wholesale diamonds, excellent cut diamonds and ideal cut diamonds. Diamond Imports is 100% Australian owned and operated company based in Sydney.
</companyDesc>
<companyAddress>Bridge Street</companyAddress>
<suburb>Sydney</suburb>
<city>Sydney</city>
<state>NSW</state>
<AverageRatingGuarantee>5</AverageRatingGuarantee>
<AverageRatingSelection>5</AverageRatingSelection>
<AverageRatingHours>5</AverageRatingHours>
<AverageRatingService>5</AverageRatingService>
<AverageRatingAmbience>5</AverageRatingAmbience>
<AverageRatingCertification>5</AverageRatingCertification>
<AverageRatingKnowledge>5</AverageRatingKnowledge>
<AverageRatingImpression>5</AverageRatingImpression>
</store>
</stores>

To load this into flash or flex, all I do is point to the URL of the page that generates the XML:

var storeData:XML = new XML();

storeData.ignoreWhite = true;

storeData.load(“getStores.php”);

Posted by Posted by Jeremy Wischusen under Filed under Flash, PHP Comments 2 Comments »

15th Apr 2008

CSS jQuery Tree Menu

The other day I decided it was time to redesign (or rather clean up) my portfolio site. In its old incarnation, I used a tree menu component that I had found online for my samples page. Since I was in the redesigning mood, I thought I would try building my own tree menu from scratch.

I had been using jQuery for some time at work and decided I would use that in combination with CSS and the good old unordered list.

The tree menu loads files identified in the id attribute into a content div via ajax. It allows nesting of sub menus, toggling and closes all other menus on the same nesting level so that only one menu is open a time.

Here is the code:

The CSS File:

/* CSS Document */
#sideMenu h3{
margin-top:2px;
}

/*Position the menu absolutely so that it can appear above other content and does not impact the alignment of the content div. Optional*/
#sideMenu{
position:absolute;
top:0px;
left:0px;
font-weight:bold;
padding-left:5px;
}

/*Since we are not using actual links, mimic link behavior using the cursor style*/
#sideMenu li{
cursor:pointer;
list-style-image:url(../images/petal_li.png)
}

/*Make any node that actually displays content (has an id attribute) a different color*/
#sideMenu ul li[id]{
color:#00FF00;
}

/*General list styling, do with as you like*/

#sideMenu ul{
list-style-position:outside;
margin:15px;
padding:5px;
}

/*Set nested ULs (i.e. submenus) to display none so that they are closed on page load. To display the menu in an expanded state on page load, remove the display property*/

#sideMenu ul ul {
display:none;
margin:5px;
padding:2px 10px;
}

/*This is the div that content is loaded into. Style as you like*/

#sampleDisplay{
padding-top:5px;
width:100%;
}

The JavaScript File:

// JavaScript Document

/*Top level menus are identified by nesting the title in a DIV tag rather than assigning the event to the LI itself. This is because when the event was tied to the LI, clicking on any of the sub menus contained in the LI would trigger the event for the LI meaning that all you got was a menu that opened and closed rather than being able to trigger the loading function in the LIs children. */

$(“#sideMenu li div”).click(categoryClick)

/* Only elements that define a page path for content need to trigger the load function. Hence use the CSS attribute selector to find nodes that define an ID attribute and bind the load function to them. This has implications in that you cannot assign IDs to elements in the menu that you do not want to trigger the load event, but this could be easily modified if need be and I have found this implementation to be quite flexible in terms of styling and functionality*/

$(“#sideMenu li[id]”).click(loadSample)

/*When a top level category is clicked, show sub menus and hide all other menus on the same nesting level. /*
function categoryClick(){
$(this).siblings().toggle();
$(this).parent().siblings().children(‘ul’).hide();
}
/*Load a page into the specfied element (in this case a div with the ID sampleDisplay) as identified by the id attribute of the element that triggered the function*/

function loadSample(){
// alert(“Loading sample ” + this.id);
$(“#sampleDisplay”).load(this.id)
}

The HTML File:

<link href=”css/samples.css” rel=”stylesheet” type=”text/css” />
<div id=”sideMenu”>
<h3>Projects</h3>
<ul>
<li><div>Flash 8</div>
<ul>
<li><div>Media</div>
<ul>
<li id=”haverick_player.html”>Tabbed Video Player</li>
</ul>
</li>
<li><div>Components</div>
<ul>
<li id=”rte.html”>Rich Text Editor</li>
</ul>
</li>
<li><div>Widgets</div>
<ul>
<li id=”wwyd_widget.htm”>Advice Widget</li>
<li id=”burn_widget.htm”>Drawing Widget</li>
</ul>
</li>
</ul>
</li>
<li><div>Flash 9</div>
<ul>
<li id=”ad_rotator.html”>Ad Rotator</li>
</ul>
</li>
<li><div>Flex</div>
<ul>
<li id=”flex_video_player.htm”>Video Player</li>
<li id=”flickr.html”>Flickr Search</li>
</ul>
</li>
</ul>
</div>
<div id=”sampleDisplay”><div align=”center” style=”height:20px; margin:10%”>You can view samples of my work by clicking on the menus to the left. </div></div>
<script type=”text/javascript” src=”scripts/samples.js”></script>

And that’s pretty much it. I just put up the site redesign today so far this menu has been doing everything I expect of it. You can check out out on my portfolio site (see Blog Roll) under the samples section.

Posted by Posted by Jeremy Wischusen under Filed under DHTML Comments 1 Comment »