Saturday, December 24, 2011

Flex: Changing the color of the background color of your Pop Ups

I have encountered situations when there's a need to have more than 1 type of background color in your Flex Application. Some Popups might need a black background with 50% opacity some might requires a background with 0% opacity, etc. One of the easiest way to change the background color of the popup will be the step of changing the global styles, but as your Flex Application gets more and more complex, manipulating with the global styles wouldn't be a recommended way of doing things. Hence, I'm going to show you another way of manipulating the background color of your popup today.

The following would be the source code of my main Application.


 
 
  global{
   modalTransparency:0;
   modalTransparencyBlur:0;
   modalTransparencyColor:0;
   modalTransparencyDuration:100;
  }
 
 
 


View that contains some buttons


 
 
  
 
 
 
 


Here comes the important part.
This would be my class that acts like a Pop Up background.
package com.popup
{
 import mx.containers.Canvas;
 import mx.core.Application;
 
 //This class acts as the background in the PopUpManager CLass
 public class PopUpBackground extends Canvas
 {
  public function PopUpBackground()
  {
   super();
   this.height = Application.application.height;
   this.width = Application.application.width;
   this.validateNow();
  }
 }
}

This would be my main class that will be replacing the use of PopUpManager.
package com.popup
{
 import flash.display.DisplayObject;
 
 import mx.collections.ArrayCollection;
 import mx.core.Application;
 import mx.core.IFlexDisplayObject;
 import mx.managers.PopUpManager;

 public class PopUpOverlay
 {
  /** Only one instance of the PopUpOverlay allowed **/
  private static var instance:PopUpOverlay;
  //This is used to store the various Pop Ups
  private var arrayPopupList:ArrayCollection = new ArrayCollection();
  
  public function PopUpOverlay(singletonEnforcer:SingletonEnforcer)
  {
  }
  
  public static function getInstance():PopUpOverlay
  {
   //Create an instance of PopUpOverlay
   if(instance == null) { 
    instance = new PopUpOverlay(new SingletonEnforcer()); 
   } 
   return instance; 
  }
  
  public function createPopUp(parent:DisplayObject, className:Class
    , modal:Boolean = true, backgroundColor:uint = 0xFFFFFF
    , alpha:Number = 0.5):Object
  {
   //If a parent view is not specified, create the 
   //popup on the main Application
   if(parent == null)
   {
    parent = Application.application as DisplayObject;
   }
   //Create the background of the Pop Up using PopUpBackground first
   var tempDisplayObject:* = PopUpManager.createPopUp(parent,PopUpBackground,modal);
   tempDisplayObject.setStyle("backgroundColor", backgroundColor);
   tempDisplayObject.setStyle("backgroundAlpha", alpha);
   this.arrayPopupList.addItem(tempDisplayObject);
   
   //Next, Create the real Pop Up specified by the className
   tempDisplayObject = PopUpManager.createPopUp(parent,className,modal);
   PopUpManager.centerPopUp(tempDisplayObject);
   this.arrayPopupList.addItem(tempDisplayObject);
   return tempDisplayObject;
  }
  
  public function removePopUp():void
  {
   //Remove the create Pop Up View first
   if(this.arrayPopupList.length > 0)
   {
    var tempDisplayObject:IFlexDisplayObject = this.arrayPopupList.removeItemAt(this.arrayPopupList.length - 1) as IFlexDisplayObject;
    PopUpManager.removePopUp(tempDisplayObject);
   }
   //Followed by the background
   if(this.arrayPopupList.length > 0)
   {
    tempDisplayObject = this.arrayPopupList.removeItemAt(this.arrayPopupList.length - 1) as IFlexDisplayObject;
    PopUpManager.removePopUp(tempDisplayObject);
   }
  }
 } 
}
class SingletonEnforcer{};   

* Click here to view the demo of this example.
^ Click here for the source files of this demo.

Friday, December 16, 2011

Flash: Playing with preloaders

I remember the days where I was trying to work around preloaders and trying to force them to display a numerical status of 0 - 100%. Especially, when you are using a in-house server and it just happens that your server is using the same connection as your laptop your desktop, you will never get to see your preloader running. Especially when there are more and more flash sites out there with interesting interactive preloaders, it would be nice to have a COOL preloader up and running. By the way, here's my solution to tackle around and ensure that you will be getting a preloader all the time.

By the way I will be working base on my demos a few weeks ago.

Here's the source file for the preloader.
package com.stretchingDemo
{
 import com.util.preloader.*;
 
 import flash.display.MovieClip;
 import flash.events.Event;
 
 public class Index extends MovieClip
 {
  //To preload your preloader file, which is this file.
  private var tempMainPreloader:MainPreloader;
  //To preload your content file
  private var tempSectionPreloader:SectionPreloader;
  private var _preloader_mc:MovieClip;
  
  //Variable to store your current preloading status 
  private var _preloadNum:Number = 0;
  //Variable to store the highest numerical number to display
  private var _maxPreloadNum:Number = 0;
  
  public function Index():void
  {
   //Start preloading this file
   tempMainPreloader = new MainPreloader(this,5);
   _preloader_mc = this.getChildByName("preloader_mc") as MovieClip;
   this.addEventListener(Event.ENTER_FRAME, progress0Handler);
  }
  
  //function executed when the preloader had finish loading
  private function progress0Handler(event:Event):void
  {   
   var str:String = String((tempMainPreloader.currentProgress)); 
   //Update your text field to display the loading status
   this._preloader_mc.preloader_txt.text = str;
   
   if(tempMainPreloader.currentProgress == tempMainPreloader.maxProgress){ 
    this.removeEventListener(Event.ENTER_FRAME, progress0Handler); 
    loadSubContent(); 
   }
  } 
  
  //function to load the main swf
  public function loadSubContent():void
  {
   //Grab the main swf that you want to load.
   //Usually I will call the prelaoder file 'load_XXX' 
   //where 'XXX' will be the filename of the main swf file. 
   //On top of this, this will help you to structure your 
   //folders properly too. As you can see will my swf files
   //are in the swf folder and my html file is on the root folder.
   var tempStr = String(this.root.loaderInfo.loaderURL).replace(/%5F/gi,"_");
   var tempArray = tempStr.split("load_");
   this.addEventListener(Event.ENTER_FRAME, preloadContentEvent);   
   tempSectionPreloader = new SectionPreloader(tempArray[0] + tempArray[1] ,95);
   tempSectionPreloader.addEventListener(
SectionPreloader.SectionContentLoading, progressHandler2);
  }
  
  //function to update the numerical count on the preloader field
  //And show the main content when the numerical count reaches 100
  private function preloadContentEvent(event:Event):void
  {
   if(_preloadNum < _maxPreloadNum)
   {
    _preloadNum ++;
   }
   this._preloader_mc.preloader_txt.text = Number(_preloadNum + tempMainPreloader.currentProgress);
   if(_preloadNum == _maxPreloadNum && _maxPreloadNum == tempSectionPreloader.maxProgress && tempSectionPreloader.getContent() != null){ 
    tempSectionPreloader.removeEventListener(
SectionPreloader.SectionContentLoading, progressHandler2);
    this.removeEventListener(Event.ENTER_FRAME, preloadContentEvent);  
    this.removeChild(_preloader_mc);
    this.addChild(tempSectionPreloader);
   } 
  }
  
  //function that will be called to update the progress of the loading 
  //of the file when the main file was loading and finish loading
  private function progressHandler2(evt:Event){ 
   _maxPreloadNum = tempSectionPreloader.currentProgress;
  }  
 }
}
* Click here to view the previous example.
^ Click here to view the demo of this example.
~ Click here for the source files of this demo.

Thursday, December 8, 2011

Flash: Disabling default scaling of your flash file

I was browsing through my previous post and I was looking at the demo that I had created. There seems to be something amiss in the example that I had created. After taking a good look at it, I realised that there were white borders appearing on the left and right side of my flash file. and on top of it, the text of the Google Map Component appears to be very blur. I also realise that all of the above were caused by the default property of scaling the flash file. Hence, I have thrown in a fix to it and everything looks much better now. :)

I only make a minor change into the html file and the following would be the source file for the html file.
<html>
 <head>
<style type="text/css">
<!--
html{height:100%}
body {margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px;}
#flashContent {width:100%;height:100%;}
-->
</style>
    
   <!-- Include support librarys first -->  
  <script type="text/javascript" src="jsScript/swfobject.js"></script>
  <script type="text/javascript" src="jsScript/swfforcesize.js"></script>      
  <script type="text/javascript" src="jsScript/swfaddress.js?tracker=null"></script>    


  </head>
  <body>
    <div id="fb-root"></div>
    <table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
    <tr><td align="center">
    <div id="flashContent">
         <h1>You need at least Flash Player 10.0 to view this page.</h1>
                <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>
    </div>
  <script type="text/javascript">
   function createSWF(){
    var now=new Date();
    now = Date.UTC(now.getYear(),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds());
    var swfURL = "swf/Main.swf?date=" + now;
    var flashvars = {};
    //Remove default scaling of the flash file
    var params = {scale :"noscale"};
    var attributes = {};
    attributes.name = "flashContent";
    swfobject.embedSWF(swfURL, "flashContent", "100%", "100%", "10.0.2", null, flashvars, params, attributes);    
    swfobject.addLoadEvent(function(){
     var obj = document.getElementById("flashContent");
     if(obj){
      var forcesize = new SWFForceSize(obj, 800, 600);
      forcesize.onLoadDiv();
     }
    })
   }
   createSWF();
  </script>    
     </td></tr></table>  
</body>
</html>
* Click here to view the previous example.
^ Click here to view the demo of this example.
~ Click here for the source files of this demo.

By the way, if you are adding or embedding a Flash file into a webpage or website, I would highly recommend you to use the Javascript classes known as SWFObject to add or embed your Flash file into a webpage or website.

- Click here to find out more about SWFObject.

Wednesday, November 30, 2011

Changing the color scheme of the map of Google Maps Component

If you have seen websites like Volkswagen "Think Blue." Road Trip before, you would probably have seen the Google Map that was in Blue color. So how do you actually do that in Flash? That would be my main objective of sharing this post today. :)


The following would be the source codes of my Flash File.
package com.TintGoogleMap
{
 //Import the classes required for Google Maps
 import com.google.maps.LatLng;
 import com.google.maps.Map;
 import com.google.maps.MapEvent;
 import com.google.maps.MapType;
 import com.google.maps.controls.MapTypeControl;
 import com.google.maps.controls.PositionControl;
 import com.google.maps.controls.ZoomControl;
 
 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.filters.ColorMatrixFilter;
 import flash.geom.Point;
 
 //Import the Component Class for Numeric Stepper
 import fl.controls.NumericStepper;
 
 public class Main extends Sprite
 {
  private var myMap:Map;
  //Set the base width and height of the Flash File
  private var baseWidth:Number = 800;
  private var baseHeight:Number = 600;
  private var _mcMap:MovieClip;
  private var _mcColorControls:MovieClip;
  
  public function Main()
  {
   //execute the function 'addToStageEvent' when the flash file
   //have been added to stage.
   this.addEventListener(Event.ADDED_TO_STAGE, addToStageEvent); 
  }
  
  private function resizeEvent(event:Event):void
  {
   //Move the holder of the Map to the top left corner
   //of the flash file
   _mcMap.x = (stage.stageWidth - baseWidth) / -2;
   _mcMap.y = (stage.stageHeight - baseHeight) / -2;
   
   //Move the controls to the bottom right of the flash file
   _mcColorControls.x = baseWidth + 
    (stage.stageWidth - baseWidth) / 2;
   _mcColorControls.y = baseHeight + 
    (stage.stageHeight - baseHeight) / 2;
   
   //Resize the Google Map Component to fill up the flash file
   myMap.setSize(new Point(stage.stageWidth, stage.stageHeight));
  }
  
  private function addToStageEvent(event:Event):void
  {
   _mcMap = this.getChildByName("mcMap") as MovieClip;
   _mcColorControls = this.getChildByName("mcColorControls") as MovieClip;
   setupStepperControls();
   
   //setup the Google Map Component and add it to the map holder
   myMap = new Map();
   myMap.key = "your_api_key";
   myMap.sensor = "false";
   //execute the function 'onMapReady' when the map is ready 
   //or created success
   myMap.addEventListener(MapEvent.MAP_READY, onMapReady);
   resizeEvent(null);
   _mcMap.addChild(myMap);
   
   //execute the function 'resizeEvent' when the flash file
   //have been resized
   stage.addEventListener(Event.RESIZE, resizeEvent);
   resizeEvent(null);
  }
  
  private function onMapReady(event:Event):void {
   //add the respective Google Map Component controls
   myMap.addControl(new ZoomControl());
   myMap.addControl(new PositionControl());
   myMap.addControl(new MapTypeControl());
   updateColorScheme();
  }  
  
  private function setupStepperControls():void
  {
   var tempSelector:NumericStepper;
   for (var i:int = 0; i < (_mcColorControls.numChildren - 1); i ++)
   {
    tempSelector = _mcColorControls.getChildAt(i) as NumericStepper;
    
    //execute the function 'updateColorScheme' when the 
    //values of the NumericStepper have been changed
    if(tempSelector)
     tempSelector.addEventListener(Event.CHANGE, updateColorScheme);
   }
  }
  
  public function updateColorScheme(event:Event = null):void  
  {  
   var matrix:Array = new Array();
   var colorArray:Array = ["R","G","B","A"];
   var tempSelector:NumericStepper;
   //Create a fake matrix(Array) based on the values of the
   //NumericStepper on the bottom right of the screen
   for(var i:int = 0; i < colorArray.length; i ++)
   {
    for(var j:int = 0; j < 5; j ++)
    {
     tempSelector = _mcColorControls.getChildByName("mc" + 
      colorArray[i] + "" + j) as NumericStepper;
     matrix.push(tempSelector.value);
    }
   }
   
   _mcColorControls.txtOutput.text = "[" + matrix.toString() + "]";
   
   //Create a Color Matrix Filter and apply the filter to the
   //Google Map Component
   var CMF:ColorMatrixFilter = new ColorMatrixFilter(matrix);  
   mapArea.filters = [CMF];  
  }  
  
  //getter function to get the main map which will be used in
  //changing the colors
  public function get mapArea():*  
  {  
   var mapPart:* = myMap.getChildAt(1);  
   return mapPart.getChildAt(0);  
  }  
 }
}
* Click here to view the demo of this example.
^ Click here for the source files of this demo.

** Click here for the website of Volkswagon Singapore "Think Blue" Road Trip.
^^ Click here for the blog of JActionScripters, that have taught me about
   the secret behind this.
-- Click here to learn more about Color Matrix Filter in Flash.
~~ Click here to learn more about the Class ColorMatrixFilter in Flash.

Sunday, November 27, 2011

Saving Private Data

Have you encountered the following situation before? Hard Disk just crashed and you need to retrieve important data from the Hard Disk... Let's face it. No one is prefect and it is impossible for you to make a backup of all your data all the time.

Probably I'm a clumsy user or probably it's my luck. Seems that my Hard Disk drive are getting spoilt pretty easily. Ex: drop my external hard disk once... Game Over..., CPU suddenly... Game Over... etc.
And Hard Disk data retrieval services are super expensive and time consuming.
On top of that... Unreliable... I don't think anyone want to ended up like Hong Kong artiste E*****. Sending a hard disk to unknown personal may caused important data to be leaked.
Ex: you bank info, accounts like Facebook, Gmail, etc.

Hence after experiencing a few instance of facing the issue of Hard Disk Failure, I can conclude that there are some softwares that turn out to be pretty handy in data retrieval.


Image taken from Quetek Consulting Corporation,
which is the company behind File Scavenger

File Scavenger
Simple UI and probably one of the fastest data retrieval software.
If File Scavenger can't detect your Hard Disk, the problem might be
caused by components of the Hard Disk itself.


Image taken from Recover My Files

Recover My Files
Provides a lot of options to the type of Data that you want retrieve
and the data source. The drawback would be ... recommended for
professional users only. I find the UI quite confusing sometimes.

Oh and on top of the softwares listed in the above, you should try the following
steps before moving on to the step of data retrieval.

Try checking the following first:
  • Power have been transmitted to the Hard Disk
  • Hard Disk doesn't give out a loud 'Tick' sound after a few minutes of seconds
If you have encountered any one of the above, probably one of the components of your Hard Disk is spoilt. (You can try sending it to the respective Hard Disk Manufactures but...)

* Click here for the website of Quetek.
^ Click here for the website of Recover My Files.

Nightmare on File Comparison...

Being a developer, have you ever encountered the problem of making a major change in your files and suddenly the whole program or website was not working at all? If you have been making consistently making backups using a SVN or you have been consistently creating you own build for backups, you can always use the following software to do a file or folder comparison to easily identify or rollback your changes.



Image taken from the website of WinMerge

Although the above application only works on a Windows, it doesn't mean that there isn't similar softwares in a Mac or a Linux. For a Mac, there's always FileMerge and on a Linux, you can always try softwares like Meld.

Biggest similarity between the softwares mentioned in the above - all of them are FREE tools to install and try.
Yes, I am a Cheapo/Cheapskate...... :P

* Click here for the website of WinMerge.
* Click here for the website of Apple Developer Tools, that contains FileMerge as part of
  the toolkit.
* Click here for the website of Meld.

Sunday, November 20, 2011

Secret to display nicely formatted programming codes in your blogs/websites

If you have been following this blog for a short period of time, you probably would ask the question of how do I display programming codes in such a nicely formatted manner? I remembered the day that I had the same doubt as you do and there's a secret to it. Introducing... SyntaxHighlighter.


So what can SyntaxHighlighter do?
Click here for the demo of SyntaxHighlighter.

Isn't it interesting? On top of that, SyntaxHighlighter support programming language like as3, xml, php, C++, Javascript, etc... Isn't that nice?
Click here for a more precise list of programming language that SyntaxHighlighter supports.

So how do I configure it?
You just need to copy and paste the following codes into the <head> tag of your HTML Template of your blog.

<link href='http://alexgorbatchev.com/pub/sh/2.1.382/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.1.382/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shAutoloader.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushAS3.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushPlain.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.382/scripts/shBrushXml.js' type='text/javascript'/>
<script type='text/javascript'>
     SyntaxHighlighter.all()
</script>
</head>

and and a <pre> tage like the following example will do.
<pre class="brush: js">
    /**
     * SyntaxHighlighter
     */
    function foo()
    {
        if (counter <= 10)
            return;
        // it works!
    }
</pre>

Click here for a more detailed explanation on how to setup SyntaxHighlighter in your blog.

Saturday, November 12, 2011

A year has past and here comes......

SiteX 2011. This was probably the biggest and the last IT show of the year 2011. So if you want to grab all the fantastic IT products of the year, this is probably your last chance.


Image taken from the website of SiteX 2011.

Note: it seems that Google Nexus might be launching at SiteX. So if you want to try of get one, you probably might want to visit SiteX which will be held at Singapore Expo starting from November 24 - 27.

* Click here for the website of SiteX.

Saturday, November 5, 2011

Simple PHP demo for file uploading (II)

I have shown you how to create a simple PHP file that will help you to upload a file into a server a few weeks ago. But if you take a look at the post a few weeks ago, you will realise that the output that you are getting after a successful upload isn't very useful at all. Hence, I have made some minor changes to the PHP file so that you will be getting an output in xml format.

This demo will start from a simple html file.
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
And a simple PHP file that will handle all the uploading...
<?php  
//Header for xml file
header ("Content-Type:text/xml");  

//Maximum filesize that can be uploaded through this file
$filesize = 1000;
//The folder that all the uploads will be place in
$folderName = "uploads/";

$output = "";

// detect slash/backslash nomenclature dirname
$path = dirname( __FILE__ );
$slash = '/'; strpos( $path, $slash ) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . "/" );
$dirPath = BASE_DIR . $folderName;   // folder path
//If the filesize of the file is smaller than the maximum filesize
if ($_FILES["file"]["size"] < $filesize)
{
 //If there is an error
 if ($_FILES["file"]["error"] > 0)
 {
  //Create a xml node with the name of 'error' and write the type of error into the node
  $output = createDataXMLNode("error",$_FILES["file"]["error"]);
 }else{
  //Display more info about the uploaded file
  //Create a xml node with the name of 'name' and write the file name into the node
  $output = createDataXMLNode("name",$_FILES["file"]["name"]);
  //Create a xml node with the name of 'type' and write the file type into the node
  $output .= createDataXMLNode("type",$_FILES["file"]["type"]);
  //Create a xml node with the name of 'size' and write the file size into the node
  $output .= createDataXMLNode("size",($_FILES["file"]["size"] / 1024) . " Kb");
  //We don't need the info of the temp file.
  //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
  //If the folder hasn't been created yet, create it now
  if(!is_dir($dirPath))
   mkdir($dirPath,0777);
  //If the file already exist
  if (file_exists($dirPath . $_FILES["file"]["name"]))
  {
   //Create a xml node with the name of 'error' and indicate that a similar file has exists into the node
   $output = createDataXMLNode("error",$_FILES["file"]["name"]." file exist");
  }else{
   //Copy the uploaded file into the specified folder
   move_uploaded_file($_FILES["file"]["tmp_name"],
   $dirPath . $_FILES["file"]["name"]);
   //Create a xml node with the name of 'path' and write the file path into the node
   $output .= createDataXMLNode("path", removeFileName(). $folderName . $_FILES["file"]["name"]);
  }
 }
}else{
 //Create a xml node with the name of 'error' and write 'Invalid file' into the node
 $output = createDataXMLNode("error","Invalid file");
}
//Create a xml node with the name of 'file' and write all the values of $output into the node
echo createNormalXMLNode("file",$output);

//Function for creating a Generic XML node
function createNormalXMLNode($name,$value){
 return "<" . $name . ">" . $value . "</" . $name . ">";
}

//Function for creating a normal XML node that contains some values that might have illegal characters
function createDataXMLNode($name,$value){
 return "<" . $name . "><![CDATA[" . $value . "]]></" . $name . ">";
}

//Function to get the url of the current page
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["HTTP_HOST"].":";
  $pageURL .= $_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

//Function to get the url of the current page and remove the filename of this page
function removeFileName(){
 $pageURL = curPageURL();
 $pieces = explode("/", $pageURL);
 $piecesLength = count($pieces);
 $pageURL = "";
 for ( $counter = 0; $counter < ($piecesLength - 1); $counter ++) {
  $pageURL = $pageURL. $pieces[$counter]."/";
 }
 return $pageURL;
}
?>

Note: after you have uploaded a file, you will realise that the output looks kinda strange. This is because I'm using a free web hosting services and it is adding some extra lines of codes to my output. But if you look at my source codes, you can easily find a neatly formatted xml in the output.

* Click here to view the demo of this example:
^ Click here for the source files of this demo.

~ Click here for the posts related to PHP Simple file upload.

Sunday, October 30, 2011

Creating your own Screen Saver is as easy as ABC

Are you getting bored with the default screen savers that comes with your personal computers? Have you heard of an interactive screen saver before? Or a screen saver that works is a game like snake, pac-man, etc? Or ever had a dream of creating or customizing a screen saver yourself? This seems to be a dream but you can now have your dreams fulfilled by using...


The above logo was taken from the website of Screentime Media.
Screentime Media.

So why do are my reasons for recommending Screentime Media?
  • Supports OS like Windows and Mac
  • Gives you an option of creating a screensaver that can only be closed either by a mouse movement or a keyboard input
  • Allows the screensaver to detects for the existence of an internet connection
  • Customizable installation settings like preview window, installer window, settings window, etc
  • and much much more...

* Click here for the website of Screentime Media.

Saturday, October 22, 2011

An exciting new Android phone which is a the collaboration between Google and Samsung

Ever since the 'Nexus One' phone that was released close to 2 years ago, this was the first time I was so excited about a new phone. The name of the phone would be ...


(Image taken from the Official website of Nexus Galaxy.)
the 'Nexus Galaxy' phone from Google and Samsung.

One would ask what makes the phone so exciting?
Well, this is because...
  • Looking at how good 'Nexus One' was back then, I don't see why one could resist Nexus Galaxy
  • 'Nexus One' comes with pure Android UI, which is a plus and you don't need to spend time playing with the UI that Samsung had created.
  • First priority in getting all the latest Android version
  • Conclusion... this is definitely a Geek's best friend

* Click here to access the website of 'Galaxy Nexus'.
^ Click here to access the website of 'Nexus One'.

Simple PHP demo for file uploading

Uploading of files can be very useful from time to time. This time round, I am going to show you how to upload a file into the server using PHP.

This demo will start from a simple html file.
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

And a simple PHP file that will handle all the uploading...
<?php

//Maximum filesize that can be uploaded through this file
$filesize = 1000;
//The folder that all the uploads will be place in
$folderName = "uploads/";

// detect slash/backslash nomenclature dirname
$path = dirname( __FILE__ );
$slash = '/'; strpos( $path, $slash ) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . "/" );
$dirPath = BASE_DIR . $folderName;   // folder path
//If the filesize of the file is smaller than the maximum filesize
if ($_FILES["file"]["size"] < $filesize)
{
 //If there is an error
 if ($_FILES["file"]["error"] > 0)
 {
  echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
 }else{
  //Display more info about the uploaded file
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
  //If the folder hasn't been created yet, create it now
  if(!is_dir($dirPath))
   mkdir($dirPath,0777);
  //If the file already exist
  if (file_exists($dirPath . $_FILES["file"]["name"]))
  {
   echo $_FILES["file"]["name"]." file exist". "<br />";
  }else{
   //Copy the uploaded file into the specified folder
   move_uploaded_file($_FILES["file"]["tmp_name"],
   $dirPath . $_FILES["file"]["name"]);
   echo "Stored in: " . $dirPath . $_FILES["file"]["name"]. "<br />";
  }
  echo "The URL of the file would be:<a href='";
  echo removeFileName(). $folderName . $_FILES["file"]["name"]."'>here</a>";
 }
}else{
 echo "Invalid file";
}

//Function to get the url of the current page
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":";
  $pageURL .= $_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

//Function to get the url of the current page and remove the filename of this page
function removeFileName(){
 $pageURL = curPageURL();
 $pieces = explode("/", $pageURL);
 $piecesLength = count($pieces);
 $pageURL = "";
 for ( $counter = 0; $counter < ($piecesLength - 1); $counter ++) {
  $pageURL = $pageURL. $pieces[$counter]."/";
 }
 return $pageURL;
}
?>
... okay the file isn't so easy after all...

Some additional Notes:
  • Remember to set the write permission into the folder that you have placed the php files
  • My example currently only allows files that are lesser than 1000 bytes, but you can change the maximum file size by increasing it in the php file.


* Click here to view the demo of this example:
^ Click here for the source files of this demo.

Saturday, October 15, 2011

A paradise for Geeks?

Sim Lim Square would probably be the best place to source for all the computer parts and accessories that a Geek would need. Besides for all the computer related products, they also have 3 levels of shops selling all sorts of electronic products ranging from tv to music/video players to cameras, you can find all these electronics products in one building. Isn't that convenient?

Pictures of Sim Lim Square.


Some info:
  • Try to ask around for the price of the same product first before making an purchase
  • Try not to go there as an individual (Chances that you get con can be pretty high, unless you know the shop owners pretty well)
  • Sometimes, Cash payment can help you to get more discounts

* Click here for the website of 'Sim Lim Square'.
^ Click here for the location of 'Sim Lim Square'.

Friday, October 14, 2011

Playing with LinkList (2)

I had introduced the use of LinkList in my previous post. So what can you do with a LinkList? And how can it help you?

Let us take a look at a simple example.
If you are staying in a house with many rooms and each room have a few cupboards or shelves fully occupied with books, you probably will have a list like the following.
Click here for the list.

I have created a simple flex application to sort all the data in a orderly manner.
Buy let us take a look at some parts of the codes first.

On top of the CustomLinkList class that I had introduced in the previous post, I had build a room class on top of the CustomLinkList class.
package List
{
 public class RoomsList extends CustomLinkList
 {
  public function RoomsList()
  {
   super();
  }
  
  //Override the add Value function in the CustomLinkList class
  override public function addValue(tempValue:*):void{
   var newNode:Node = new RoomNode(tempValue);
   var baseNode:Node = head;
   var tempNode:Node;
   if(baseNode == null){
    head = newNode;
   }else{
    var hasCheck:Boolean = false;
    while(hasCheck == false){
     //While moving from one node to the next,
     //do a comparison between the nodes
     //and find the best place to place the new node
     if(compareRoomName(baseNode, newNode)){
      hasCheck = true;
      if(baseNode.prev == null){
       head = newNode;
      }
      tempNode = baseNode.prev;
      if(tempNode != null){
       tempNode.next = newNode;
      }
      newNode.prev = baseNode.prev;
      newNode.next = baseNode;
      baseNode.prev = newNode;
     }else{
      if(baseNode.next == null){
       baseNode.next = newNode;
       newNode.prev = baseNode;
       hasCheck = true;
      }else{
       baseNode = baseNode.next;
      }
     }
    }
   }
   count ++;
  }
  
  //Function to compare 2 node and if the new node that was pass into
  //this function had a smaller value, it will return true, else false 
  //We are going to sort the room by their room_name value
  public function compareRoomName(tempNode1:Node, tempNode2:Node):Boolean{
   var name1:String = String(tempNode1.value.room_name).toLowerCase();
   var name2:String = String(tempNode2.value.room_name).toLowerCase();
   var tempArray:Array = new Array();
   tempArray.push(name1);
   tempArray.push(name2);
   tempArray.sort();
   if(name2 == tempArray[0]){
    return true;
   }else{
    return false;
   }
   return false;
  }
 }
}

And a RoomNode class that builds on top of the Node class.
package List
{
 public class RoomNode extends Node
 {
  private var shelvesList:ShelvesList = new ShelvesList();
  //After passing in the value of this node for room,
  //Pass in all the relevant data for creating the 
  //respective shelves
  public function RoomNode(tempValue:*):void {
   // constructor code
   super(tempValue);
   for(var i:int = 0; i < this.value.shelfs.shelf.length(); i ++){
    shelvesList.addValue(this.value.shelfs.shelf[i]);
   }
  }
  
  public function get roomContents():ShelvesList{
   return shelvesList;
  }
 }
}
And this would be my main application class.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute"
    width="100%"
    height="100%"
     creationComplete="creationCompleteHandler(event)">
 <mx:Style>
  VBox{
   paddingTop:5;
   paddingBottom:5;
   paddingLeft:5;
   paddingRight:5;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import List.*;
   
   import mx.events.FlexEvent;
   
   //Embed a xml file that contents data
   [Embed(source="xml/booksData.xml")]
   private var dataXml:Class;
   
   //Create a list for rooms
   private var tempRoomList:RoomsList = new RoomsList();
   
   protected function creationCompleteHandler(event:FlexEvent):void{
    var strOutput:String = "";
    var tempDataXML:XML = dataXml.data as XML;
    //Pass all the data into the list for rooms
    for(var i:int = 0; i < tempDataXML.room.length(); i ++){
     tempRoomList.addValue(tempDataXML.room[i]);
    }
    var roomObject:RoomNode;
    var shelfObject:ShelfNode;
    //Display all the contents in the list for rooms
    for(i = 0; i < tempRoomList.length(); i ++){
     roomObject = tempRoomList.getNodeAt(i);
     strOutput += "Room Name = " + 
      String(roomObject.value.room_name);
     strOutput += "\n";
     for(var j:int = 0; j < roomObject.roomContents.length(); j ++){
      shelfObject = roomObject.roomContents.getNodeAt(j);
      strOutput += "-> Shelf Name = " + 
       String(shelfObject.value.shelf_name);
      strOutput += "\n";
      for(var k:int = 0; k < shelfObject.shelfContents.length(); k ++){
       strOutput += "   -> Book Title = " + 
        String(shelfObject.shelfContents.getNodeAt(k).value.book_title);
       strOutput += ", Written By " + 
        String(shelfObject.shelfContents.getNodeAt(k).value.author);
       strOutput += "\n";
      }
     }
    }
    txtMessage.text = strOutput;
   }
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" height="100%">
  <mx:TextArea id="txtMessage" width="100%" height="100%"/>
 </mx:VBox> 
</mx:Application>
* Click here to view the demo in this post.
^ Click here for the source files of the demo
` Click here to follow the other post on LinkList.

Sunday, October 9, 2011

Playing with LinkList

In most of the older Programming language that I had used before or played before requires the developer to enter a value for the number of items that you are going to store in a Array. This can be quite a nuisance sometimes, but luckily there is something known as a Link List in the programming world. :D With the help of a Link List, it had definitely solved a lot of length issues in various Programming Language.

This is a simple example that I had created for Flex but the classes were also usable in Flash Professional Projects.
This is the source file for the main Application - LinkList.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="100%" height="100%"
    creationComplete="creationCompleteHandler(event)">
 <mx:Style>
  VBox{
   paddingTop:5;
   paddingBottom:5;
   paddingLeft:5;
   paddingRight:5;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import List.*;
   
   import mx.events.FlexEvent;
   
   private var tempObject:Object = {x:100,y:100};
   private var dataArray:Array = new Array("Data",12345,3.14,tempObject);
   
   private var tempList:CustomLinkList = new CustomLinkList();
   
   protected function creationCompleteHandler(event:FlexEvent):void
   {
    var strOutput:String = "";
    //Adding values to the List
    for(var i:int = 0; i < dataArray.length; i ++)
    {
     tempList.addValue(dataArray[i]);
    }
    strOutput = "Show Contents of List";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    //Display the objects in the List
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    strOutput += "\nRemove Item number 3";
    //Method to remove an object of a particular position
    strOutput += "\n" + String(tempList.removeValueAt(2)) +
     " have been removed.";
    strOutput += "\nShow Contents of List Again";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    //Display the objects in the List
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    strOutput += "\nRemove All Items";
    while(tempList.length() != 0)
    {
     strOutput += "\n" + String(tempList.removeValueAt(0)) +
      " have been removed.";
    }
    strOutput += "\nShow Contents of List Again";
    strOutput += "\nList has " + tempList.length() + " items.";
    strOutput += "\n";
    for(i = 0; i < tempList.length(); i ++)
    {
     strOutput += String(tempList.getValueAt(i)) + " ";
    }
    txtMessage.text = strOutput;
   }
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" height="100%">
  <mx:TextArea id="txtMessage" width="100%" height="100%"/>
 </mx:VBox> 
</mx:Application>

This is a basic Link List class that I had written
package List{
 public class CustomLinkList {
  private var _head:Node;
  private var _count:int;
  public function CustomLinkList() {
   // constructor code
   head = null;
   count = 0;
  }
  
  //count = number of items Getters and Setters
  protected function get count():int
  {
   return _count;
  }

  protected function set count(value:int):void
  {
   _count = value;
  }

  //Start of the Node
  protected function get head():Node
  {
   return _head;
  }

  protected function set head(value:Node):void
  {
   _head = value;
  }

  //Creating and adding a new Node
  //And connect the 2 way Link List properly
  public function addValue(tempValue:*):void{
   var newNode:Node = new Node(tempValue);
   var currNode:Node = head;
   if(currNode == null){
    head = newNode;
   }else{
    while(currNode.next != null){
     currNode = currNode.next;
    }
    currNode.next = newNode;
    newNode.prev = currNode;
   }
   count ++;
  }
  
  //Removing a node and returning 
  //the value of the Node at the same time
  //And connect the 2 way Link List properly
  public function removeValueAt(tempInt:int):*
  {
   var i:int = 0;
   var currNode:Node = head;
   if(tempInt < count)
   {
    var nextNode:Node;
    var prevNode:Node;
    while(i != tempInt){
     currNode = currNode.next;
     i ++;
    }
    if(currNode)
    {
     nextNode = currNode.next;
     prevNode = currNode.prev;
     if(nextNode)
      nextNode.prev = prevNode;
     if(prevNode)
      prevNode.next = nextNode;
     if(currNode == head)
     {
      head = nextNode;
     }
    }
    if(count > 0)
     count --;
    return currNode.value;
   }else{
    return null;
   }
  }
  
  //Get the value of a Node of a particular position
  public function getValueAt(tempInt:int):*{
   var i:int = 0;
   var currNode:Node = head;
   if(tempInt < count)
   {
    while(i != tempInt){
     currNode = currNode.next;
     i ++;
    }
    return currNode.value;
   }else{
    return null;
   }
  }
  
  //Returns the length of the LinkList
  public function length():int{
   return count;
  }
 }
}
This is a simple Node class
package List{
 public class Node {
  protected var _value:* = null;
  protected var _next:Node;
  protected var _prev:Node;
  public function Node(tempValue:*) {
   // constructor code
   _value = tempValue;
   _next = null;
   _prev = null;
  }
  
  //Previous Node Getters and Setters
  public function get prev():Node
  {
   return _prev;
  }

  public function set prev(value:Node):void
  {
   _prev = value;
  }
  
  //Next Node Getters and Setters
  public function get next():Node
  {
   return _next;
  }

  public function set next(value:Node):void
  {
   _next = value;
  }
  
  //Previous Content of the Node
  public function set value(tempValue:*):void{
   _value = tempValue;
  }
  
  public function get value():*{
   return _value;
  }
 }
}
* Click here to view the demo in this post. ^ Click here for the source files of the demo

Sunday, October 2, 2011

One of Windows OS missing component - Partitioning Your Hard Disk

Being a Windows user for more than 10 years, I have encounter numerous situations where I have bought a PC or Laptop from a Vendor and there was only one partition in the System. As I have been using Windows XP since a few years ago, I would use 'Partition Magic' to solve all these partition issues. Especially when the default Windows Disk Management Utility was pretty slow and step intensive. (Especially, when a user was required to sit in front of the monitor to wait for the completion of one step before he can move on and select the next step...) As for Partition Magic, an user can create a series of task and let them run at one go. Isn't it useful?


But with the discontinuation of supplying the number of updates to 'Partition Magic' and the uprising of Windows Vista and Windows 7, an user cannot use 'Partition Magic' any more, which is kinda sad. :(

Although, its pretty sad that we cannot use 'Partition Magic' any more, there seems to be some other potential alternatives to 'Partition Magic'.
For Example:

Image taken from Arconis Website
Click the above image or here to access the website of Acronis Disk Manager.


Image taken from Aomei Website
Click the above image or here to access the website of Aomei Partition Assistant.

* Click here to find out more about 'Partition Magic'

Sunday, September 25, 2011

Flash/Flex: Changing the colors of the hyperlinks of a body text

I had figured out a simple solution for changing the colors of your hyperlinks in a body text a few weeks ago. Hence I decided to share it in the post. On top of that, the demos that I had shown in this post also demonstrate the use of the TextEvent.LINK Event which can be very useful also. :D

Here's a simple AS3 Actionscript Class file that contains a simple Stylesheet for setting the properties of the default and the hover state of the hyperlinks. I have created this file so that I can reuse it in Flex and Flash.

package
{
 import flash.text.StyleSheet;

 public class SimpleStylingClass
 {
  private var _ss:StyleSheet = new StyleSheet();
  
  public function get ss():StyleSheet
  {
   return _ss;
  }
  
  public function set ss(value:StyleSheet):void
  {
   _ss = value;
  }
  
  public function SimpleStylingClass()
  {
   var aHover:Object = new Object();
   aHover.color = '#FF0000';
   aHover.fontWeight = 'bold';
   aHover.textDecoration = 'none';
   
   var aNorm:Object = new Object();
   aNorm.color = '#0000FF';
   aNorm.textDecoration = 'underline';
   
   ss.setStyle("a", aNorm);
   ss.setStyle("a:hover", aHover);
  }

 }
}

The following would be the source file for the flex file.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="100%" height="100%" >
 <mx:Style>
  HBox{
   paddingLeft: 10;
   paddingRight:10;
   paddingTop:10;
   paddingBottom:10;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   import mx.events.FlexEvent;
   import mx.controls.Alert;
   
   //Bindable String to be used by the text area below.
   [Bindable]
   private var _bodyText:String = "I have some body text here. It " +
    "contains a few clickable URLs. For example: <a href='" +
    "event:http://www.google.com' target='_blank'>Google.com" +
    "</a>, <a href='event:http://www.msn.com' " +
    "target='_blank'>msn.com</a> and <a target='_blank' " +
    "href='http://nekyouto-tech.blogspot.com'>My Tech Blog</a>.";
   
   /*
    When the user clicks on such a link (href='event:...', 
    I will show a Alert box indicating the URL that the 
    user have click and a simple message.
   */
   protected function txtAreaBody_linkHandler(event:TextEvent):void
   {
    // TODO Auto-generated method stub
    Alert.show(event.text + " have been block by this site"
     , "Alert",Alert.OK);
   }
   
  ]]>
 </mx:Script>
 <mx:HBox width="100%" height="100%">
  <!-- 
   I have pointed the htmlText value to the Bindable String in the 
   above.I have also added the Stylesheet for the text area and 
   also theListener for hyperlinks in the body text. It will keep 
   a lookout for href='event:..... pattern in a hyperlink text. 
  -->
  <mx:TextArea id="txtAreaBody" width="100%" height="100%" 
      htmlText="{_bodyText}" link="txtAreaBody_linkHandler(event)"
      styleSheet="{new SimpleStylingClass().ss}" fontSize="24" />
 </mx:HBox>
</mx:Application>


And the following would be the main class for the Flash file
package
{
 import flash.display.Sprite;
 import flash.events.TextEvent;
 import flash.text.TextField;
 import flash.external.ExternalInterface;
 
 public class StylingHyperlinksMainClass extends Sprite
 {
  //Text to be displayed in the textfield
  private var _bodyText:String = "I have some body text here. It " +
   "contains a few clickable URLs. For example: Google.com" +
   ", " +
   "msn.com and My Tech Blog.";
  private var _txtBodyText:TextField;
  
  public function StylingHyperlinksMainClass()
  {
   super();
   _txtBodyText = this.getChildByName("txtBodyText") as TextField;
   _txtBodyText.htmlText = _bodyText;
   //Setting the stylesheet of the Textfield
   _txtBodyText.styleSheet = new SimpleStylingClass().ss;
   //Adding the listener for href that starts with event:...
   _txtBodyText.addEventListener(TextEvent.LINK, textLinkEvent);
  }
  
  /*
  Shows a Javascript Alert box when the user clicks on the
  URL that starts with event:...
  */
  private function textLinkEvent(event:TextEvent):void
  {
   ExternalInterface.call("alert", event.text + " have been block" +
    " by this site.");
  }
 }
}

* Click here to view the Flex demo.
# Click here to view the Flash demo.
^ Click here to download the source file of the above demos.

Sunday, September 18, 2011

A work around for the Blogger Images Overlay and your Lightbox Overlay

As I have just started creating my Blogs a few months ago and I was putting a lot of effort creating and updating it... Something crazy had happened suddenly...


Image shows a mixture of Blogger Image Overlay and Spicebox Overlay...

In order to stop the above from happening any further, I have done the following steps:
  1. In your Blogger dashboard click Design > Edit Html
  2. Find the keyword Spicebox and replace it with something else in the code of your blogs and you are done.

But I do hope that Blogger will provide an option so that I can turn the current black overlay for images and have my Overlay effect back again.

* Click here for the Spicebox overlay effect for Blogger.

Flex: Playing with text that contains HTML Entity

I was working and debugging projects with a bunch of test that contains HTML entities the other day and I realise that if you were given a bunch of copy that contains common HTML entities characters like '>', '<', '€', ... etc you might encounter problems like bold text not rendered correctly. And if you are going to filter or detect a special character in the body text, you might ended up checking for characters that contains &#...; if which quite troublesome and not so user friendly. Hence after looking around the web for some time, here is one of the derived solutions for some of the common special characters.


Here's the source file for the demo that I'm going to show in this post.


 
  
 
 
  
   
   
  
  
  
  
  
   
   
    
   
  
  
   
   
    
   
  
  
  
  
   
   
    
   
  
  
   
   
    
   
  
 


* Click here for the demo I have created.
^ Click here to download the source files for the demo.
# Click here for more information on HTML Entities.
! Click here for a better solution if you need a better and more complete class for replacing these HTML entities.

Thursday, September 8, 2011

Quick solutions to sending emails with PHP

I'm writing this post because there are things that I wouldn't want to forget. Even though PHP is a free and easy to use technology but I'm pretty sure that from time to time, there would be a need to generate and send out emails from your website. Therefore, this is one of the most useful solution that I had encountered before.


Introducing...

PHPMailer supports the following:
  • PHP 4,5,6
  • plain text and html encoded email messages... etc
  • Click here to find out more about the features that PHPMailer supports

Note: initially, I wanted to post a demo here but because most of the domains that I own were mainly free hosting domains... it makes it very troublesome to show a demo... Trust me, it will be much easier if you 'play' with PHPMailer on your personal php server. :)

* Click here for the website of PHPMailer.

Wednesday, August 31, 2011

Dynamic meta Description, meta Keywords and Title using PHP

Changing your the meta description, meta keywords and title of a php page.This is a follow up of a post that I had posted here a few weeks back.


I only make some changes to the header.php file and the header.php file will handle the value of $section and change the title, the meta description and meta keywords of the webpage.
<?
	//Conditional Statement to change the title, meta description and meta keywords.
	if ($section == "home"){
		$title = "Unique title for home page";
		$description = "A Unique description for 'Home' Section";
		$keyword = "Home";
	}else if ($section == "profile"){
		$title = "Special title for profile page";
		$description = "A Special description for 'Profile' Section";
		$keyword = "Profile";
	}else if ($section == "product"){
		//Another Conditional Statement to change the title, meta description and meta keywords base on the productID.
		$productID = $_REQUEST["productID"];
		if($productID == "x"){
			$title = "Product page for X";
			$description = "A description for 'Product X'";
			$keyword = "Product X";
		}else if($productID == "y"){
			$title = "Product page for Y";
			$description = "A description for 'Product Y'";
			$keyword = "Product Y";
		}else if($productID == "z"){
			$title = "Product page for Z";
			$description = "A description for 'Product Z'";
			$keyword = "Product Z";
		}else{
			$title = "A title for product page";
			$description = "A description for 'Product' Section";
			$keyword = "Product X, Product Y, Product Z";
		}
	}else if ($section == "contact"){
		$title = "Contact me now";
		$description = "Form for contact me";
		$keyword = "Conact me, form";
	}
	//Write the title, meta description and meta keywords into a header html tag
	echo "<header>";
	echo "<title>".$title."</title>";
	echo "<meta name='description' content='".$description."'>";
	echo "<meta name='keywords' content='".$keyword."' />"; 
	echo "</header>";
	//Create a table and base on the value os $section, toggle the state of the selected button.
	echo "<table cellpadding='0' cellspacing='0' border='0' width='100%' ><tr>";
	//If $section == home, make the text 'Home' unclickable else makt it into a clickable hyperlink
	if ($section != "home"){
		echo "<td align='center'><a href='home.php'>Home</a></td>";
	}else{
		echo "<td align='center'><b>Home</b></td>";
	}
	//If $section == profile, make the text 'Profile' unclickable else makt it into a clickable hyperlink
	if ($section != "profile"){
		echo "<td align='center'><a href='profile.php'>Profile</a></td>";
	}else{
		echo "<td align='center'><b>Profile</b></td>";
	}
	//If $section == product, make the text 'Product' unclickable else makt it into a clickable hyperlink
	if ($section != "product"){
		echo "<td align='center'><a href='product.php'>Product</a></td>";
	}else{
		echo "<td align='center'><b>Product</b></td>";
	}
	//If $section == contact, make the text 'Contact Us' unclickable else makt it into a clickable hyperlink
	if ($section != "contact"){
		echo "<td align='center'><a href='contact.php'>Contact Us</a></td>";
	}else{
		echo "<td align='center'><b>Contact Us</b></td>";
	}
	echo "</tr></table>";
	echo "<br>";
?>

Click here for the example that I had created for the post.
Try click and copying the following URL1 and URL2 into Facebook and you will see how useful php can be.
Click here for the source codes of the example that I had created.

Friday, August 26, 2011

COMEX 2011

It's time to get ready for COMEX 2011. Time to catch a glimpse of the latest gadgets and at the same time get all the gadget at a promotional price. :P



Image taken form the COMEX website.

Details of COMEX 2011:
  • Venue: Level 1,2,3,4 and 6, Suntec City Convention Hall, Singapore
  • Date: 1st - 4th September 2011
  • Opening hours: 12noon - 9pm

* Click here for the website of COMEX 2011.

Wednesday, August 24, 2011

Flex: Measuring width of text of a Label

I have encounter a few situations in Flex where you need to position 2 labels side by side and the one on the left always ended up to be a dynamic label. If this is Flash, you can always use a .textWidth / .textHeight to solve the problem but in Flex, some of these properties were not available hence here's a workaround for it.



	
	
		Label{
			font-Size:20;
		}
	
	
		
	
	
	
		
		
			
		
		
			
		
		
			
		
		
			
		
		
		
			
			
		
	


Click here to view the demo.
Click here to download the source file of the demo.

Monday, August 22, 2011

Google Plus - Games Notification

Google Plus+ just added a new section for 'Games' recently. And as compared to the way how Facebook had organised the way game notifications were displayed, I love the way Google is displaying all the game notifications.


This is how Google Plus+ is doing it and I like it. Rather then messing up the feeds of my friends, they have created a seperate section for all these annoying 'Games Notifications'. This my friend is a +1 indeed. Though I still want a -1 button from Google Plus+. Can anyone help me to pass the message to Google asking them for a -1 button?

* Click here to access Google Plus+ website.
^ Click here to access Facebook.

Sunday, August 14, 2011

Flash / Flex AS3: Finding the difference between 2 dates

I have encounter numerous situation where there is a need to compare 2 different dates. I have created a simple example to demonstrate how to find out the difference between 2 dates.



	
		Days: " + tempArray[0] + "";
				outputTxt.htmlText += "
Hours: " + tempArray[1] + ""; outputTxt.htmlText += "
Minutes: " + tempArray[2] + ""; outputTxt.htmlText += "
Seconds: " + tempArray[3] + ""; outputTxt.htmlText += "
MilliSeconds: " + tempArray[4] + ""; } ]]>

package
{
	import mx.controls.DateField;
	import mx.controls.TextArea;

	public class TimeDifferenceMain
	{
		public function TimeDifferenceMain()
		{
		}
		
		public function compareDate(tempDate:Date):Array
		{
			//2 dates object: 1 is today's date, the other 1
			//is the selected date
			var now:Date = new Date();
			var selectedDate:Date = tempDate;
			
			//to store the difference of both dates in numerical value
			var remainder:Number;	
			
			//Store the number of milliseconds of both date since 1970
			var nowNum:Number = now.getTime();
			var selectedDateNum:Number = selectedDate.getTime();
			
			//Numbers to store number of milliseconds in eash day, 
			//each hour, each minute and each second
			var dayValue:Number = 24 * 60 * 60 * 1000;
			var hrValue:Number = 60 * 60 * 1000;
			var minValue:Number = 60 * 1000;
			var secValue:Number = 1000;
			
			//Compare which date is bigger and find the difference
			if(nowNum > selectedDateNum)
			{
				remainder = nowNum - selectedDateNum;	
			}else{
				remainder = selectedDateNum - nowNum;
			}
			
			//Modulas play a big role here as it is used to find
			//out the remainder of the next smaller unit
			var hrLeft:int = remainder % dayValue;
			dayValue = (remainder - hrLeft)/dayValue;
			var minLeft:int = hrLeft % hrValue;
			hrValue = (hrLeft - minLeft)/hrValue;
			var secLeft:int = minLeft % minValue;
			minValue = (minLeft - secLeft)/minValue;
			var milliSecLeft:int = secLeft % secValue;
			secValue = (secLeft - milliSecLeft)/secValue;
			
			//Create a array and store the output into the array
			var resultArray:Array = new Array();
			resultArray.push(dayValue);
			resultArray.push(hrValue);
			resultArray.push(minValue);
			resultArray.push(secValue);
			resultArray.push(milliSecLeft);
			return resultArray;
		}
	}
}

Click here to view the demo.
Click here to download the source file of the demo.

Sunday, August 7, 2011

Facebook: Changing the description of your websites / blogs

This happen to me quite often in the past. I was building a website or after I had written a new post on one of my blogs, I would immediately copy and paste the URL of the website onto my Facebook wall. Upon doing that, Facebook will show you the title, the description and a series of thumbnail for you to select of the URL that you have pasted. You realise that some parts of the copy were missing due to some illegal characters or you suddenly decided to change the thumbnail of the website. After making that minor change, Facebook will still reflect the same contents as per what you had before you make the minor change. What to do? How to work around this issue?

As long as the same URL have not been shared by any other users, you will still have a way to ask Facebook to update to the latest content.

Click here to move to one of the developer tools that Facebook had created.

Copy and paste the URL that you want to share into the text field and click on the 'Lint' button located next to the text field.

Now, the updated content should be appearing on this webpage and you can start sharing your URL with the correct set of contents now. :)

Note:
  • This method will not work after someone had already started sharing the same URL that you are sharing.
  • If this method doesn't work, create a separate server script scripting file and do a redirect from that file. And share the new URL. :D

Sunday, July 31, 2011

Why choose PHP?

There were many types of server side scripting environment out there. For example: there's php, asp, asp.net etc. But I choose php most of the time because its free and it's easy to use.


Let's look at the scripts below:
I am using a flash file to communicate to the server side script.
package com.phppostget
{
 import com.zcs.net.NetConnect;
 
 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.events.MouseEvent;
 import flash.net.NetConnection;
 import flash.net.URLVariables;
 import flash.text.TextField;
 
 public class Main extends Sprite
 {
  //This is a class that I had written to simplify 
  //the connection to a server side script
  private var tempConnect:NetConnect;
  //Create pointers to the movieclips and textfield on Stage
  public var _send_mc:MovieClip = new MovieClip();
  public var _btn_mc:MovieClip = new MovieClip();
  public var _value1_txt:TextField = new TextField();
  public var _value2_txt:TextField = new TextField();
  public var _value3_txt:TextField = new TextField();
  public var _input1_txt:TextField = new TextField();
  public var _input2_txt:TextField = new TextField();
  public var _input3_txt:TextField = new TextField();
  public var _url_txt:TextField = new TextField();
  public var _result_txt:TextField = new TextField();
  
  public function Main(){
   //Setup all the pointers to the respective movieclips and textfields
   //and setup the listeners to all these Movieclips and buttons
   _btn_mc = this.getChildByName("btn_mc");
   _btn_mc.gotoAndStop(1);
   _btn_mc.addEventListener(MouseEvent.CLICK, changeMethodEvent);
   _send_mc = this.getChildByName("send_mc");
   _send_mc.addEventListener(MouseEvent.CLICK, sendDataEvent);
   _value1_txt = this.getChildByName("value1_txt") as TextField;
   _value2_txt = this.getChildByName("value2_txt") as TextField;
   _value3_txt = this.getChildByName("value3_txt") as TextField;
   _input1_txt = this.getChildByName("input1_txt") as TextField;
   _input2_txt = this.getChildByName("input2_txt") as TextField;
   _input3_txt = this.getChildByName("input3_txt") as TextField;
   _url_txt = this.getChildByName("url_txt") as TextField; 
   _result_txt = this.getChildByName("result_txt") as TextField; 
  }
  
  //Simple listner to toggle the POST and GET state 
  //upon clicking on the Movieclip
  private function changeMethodEvent(event:Event):void{
   if(_btn_mc.currentFrame == 1){
    _btn_mc.gotoAndStop(2);
   }else{
    _btn_mc.gotoAndStop(1);
   }
  }
  
  //Sending the values to the server side script
  //upon clicking on the Send button
  private function sendDataEvent(event:Event):void{
   var tempXMLStr:String = "<"+_input1_txt.text+">" + _value1_txt.text + "";
   tempXMLStr += "<"+_input2_txt.text+">" + _value2_txt.text + "";
   tempXMLStr += "<"+_input3_txt.text+">" + _value3_txt.text + "";
   var tempXML:XML = new XML(tempXMLStr);
   
   tempConnect = new NetConnect(_url_txt.text, tempXML, Number(_btn_mc.currentFrame));
   tempConnect.addEventListener(NetConnect.PARSE_NET_OK, showResultEvent);
  }
  
  //When the server side script returns a result, show it on the result textfield
  private function showResultEvent(event:Event):void{
   if(_btn_mc.currentFrame == 1){
    _result_txt.text = "POST: ";
   }else{
    _result_txt.text = "GET: ";
   }
   var urlVar:URLVariables = new URLVariables(tempConnect.getResult());
   _result_txt.appendText(urlVar.msg);
  }
 }
}

Look at the source code of this php file. I don't need to bother about the calls to this php using a POST or a GET method. $_REQUEST will handle both POST and GET method calls. Isn't that great?
<?php
  //Regardless of POST or GET, grab the values that 
  //were send to this php files
  $name = $_REQUEST["name"];
  $desc = $_REQUEST["desc"];
  $info = $_REQUEST["info"];
  //output a simple message with the values that were 
  //pass into this php file
  echo "msg=Hello ".$name.", the following are your description:".$desc." and here are your info.".$info."&misc=";
?>

Click here for the demo of this post.
Click here for the source files of this post.

One of Windows OS missing component

Being a Windows User for more than 10 years, I always felt that the OS could improve further. Rather than making all the cosmetic changes to the Environment, I would prefer them to add useful utility and components to help the users to increase their productivity.

'TeraCopy' was definitely one of the best components that I would strongly encourage all the Windows User to install. This is because the original Windows Copy and Paste could only provide basic information like how much percentage of the total files had been copied and how long does it take to finish copying all the files. Although these were useful information to a user, but if you are copying files from different folders and an error occurred suddenly, you will need to copy all the files again as the default Windows File Copying System does not provide enough information to tell you what are the files that had been copied. This is a tedious job especially when you are copying a large volume of files.

With the help of 'TeraCopy', one will be provided with all the important information that the default Windows File copying system were lacking. Trust me, try installing the software for a few days and you were never ever want to use the default Windows File copying system again.

Click here to find out more about 'TeraCopy'.

Sunday, July 24, 2011

Flash / Flex AS3: Bubbling Events

In AS3, there will be numerous situation where you would encounter the word bubble in the creation of a new Event. So what does "bubble" means? This is how I would interpret the term "bubble". "Bubble" means that you will allow the dispatch event to move from the lowest position of a interface to move all the way to the stage.

Still confused? No worries, I have created a simple project to demo the uses of a 'Bubble' event.



 
  
 
 
  
 
 
 



 
 
  VBox{
   paddingLeft:10;
   paddingRight:10;
   backgroundAlpha:0.2;
   backgroundColor:#00FF00;
  }
 
 
  
 
 
 
  
  
   
   
    
    
     
     
      
      
       
       
      
     
    
   
  
 


Click here to view the demo.
Click here to download the source file of the demo.

Note: if you want the event to be capture by all the levels, comment away the following line of code "event.stopPropagation();".

Sunday, July 17, 2011

Flex AS3: Creating a Customized Tool Tip in Flex

Are you bored with the current look of the Tool Tip in Flex? I'm getting a bit sick with the look of the Tool Tip and I have managed to find a few ways to work around the look of the Tool Tip. Here is one of the ways that I have been using.

Firstly, we would need to create a class to extends a Tool Tip Interface in flex.



 
 
  
 
 
  
 
 
 


After creating the class, this is the how you could use the customise tool tip in your Flex Application.


 
  
   
  
  
  
  
  
 

Click here to view the demo listed in the above.
Click here to grab the source files for this demo.