NVL() function in Postgre SQL

August 25, 2009 8 comments

Do Postgre have any function that equals to NVL() of Oracle? of course, it do have the same function but with different name. Below is the systax:

coalesce(expr1, expr2, expr3,....)

this function’ll returns the first non-null expression that is passed to it.

Ex:  
SELECT coalesce(<column name 1>, <New value>), <Column name 2> 
FROM <Table name> 
WHERE <Some Condition>

If <Column name 1> is NULL, it’ll be replaced by <New value>

Advertisements
Categories: PostgreSQL Tags:

Simple login form with Flex and XML as database

August 17, 2009 3 comments

I want to create a simple login form to learn how to work with Validation and XML database (based on E4X) in Flex.

login

Fist we need an XML file which contains our login information, i call it [data.xml]. We have two [user] elements (but you can add as much as you want), each element contains one user’s data includes user id and password. This file must be put at the same folder as the compiled source file. To learn more about XML, visit the W3Schools’ XML Tutorial at http://w3schools.com/xml/.

<?xml version=”1.0″ encoding=”utf-8″ ?>
   <data>
      <user>
         <userid>UI0001</userid>
         <password>123</password>
         <username>Nguyen Van A</username>
      </user>
      <user>
         <userid>UI0002</userid>
         <password>456</password>
         <username>Tran Van B</username>
      </user>
</data>

The next step is to create an mxml file called login.mxml. This file is used to control login form’s layout and handle event. The controls do not have anything paticularly complex. We start with a panel , inside it we add two Textinput controls for user id, password and a button to submit data. Finally, we have two StringValidators used for [Required], [MinLength], [MaxLength] validation.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”  layout=”absolute”>
   <!-- Validation -->
   <mx:StringValidator id=”useridValidator” required=”true”
          minLength=”6” maxLength=”25″
          source=”{userid}” property=”text”
          trigger=”{btnLogin}” triggerEvent=”click” />

   <mx:StringValidator id=”passwordValidator” required=”true”
          minLength=”6” maxLength=”25″
          source=”{password}” property=”text”
          trigger=”{btnLogin}” triggerEvent=”click” />

   <!-- Main form controls -->
   <mx:Panel title=”Login Form” horizontalCenter=”0″ verticalCenter=”0″>
      <mx:Form>
         <mx:FormItem label=”User ID”>
            <mx:TextInput id=”userid” />
         </mx:FormItem>
         <mx:FormItem label=”Password”>
            <mx:TextInput id=”password” displayAsPassword=”true” />
         </mx:FormItem>
         <mx:FormItem>
            <mx:Button id=”btnLogin” label=”Login”  />
         </mx:FormItem>
      </mx:Form>
   </mx:Panel>
</mx:Application>

We finished the layout. Now we’re going to start building the action script to hanle screen related events. At the initialization stage, we’ll add two validators into an array for later validation. (Remember to add creationComplete=”init()” into <mx:Application>)

[Bindable]
private var validatorArr:Array;

/**
* Initialization method
*/
public function init():void {
   // Add validators to array for validating all at one time
   validatorArr = new Array();
   validatorArr.push(useridValidator);
   validatorArr.push(passwordValidator);
}

then when user click on [Login] button we must call the inserted validators to validate user’s inputted data. If the result is valid, start loading data from XML and loop through it to find if the inputted data exist.

/**
* User's information checking
* based on the inputted data
*/
public function loginCheck():void  {
   // Starting to validate
   var errorArr:Array = Validator.validateAll(validatorArr)
   // if the error array contain any data, =&gt; error
   var isValid:Boolean = errorArr.length == 0;

   if (isValid) {
      // Load user data
      doLogin();
   }
}

private function doLogin():void {
   // Point to the data file's path
   var request:URLRequest = new URLRequest("data.xml");

   loader = new URLLoader();
   try {
      loader.load(request);
   } catch (error:SecurityError) {
      trace("A SecurityError has occurred.");
   }

   // If error, go to errorHandler function
   loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
   // once the load action was complated, go to loaderCompleteHandler() for
   // checking user information
   loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
}

private function loaderCompleteHandler(event:Event):void {
   var logged:Boolean = false;
   try {
      // Convert data into E4X class for easy access to elements
      externalXML = new XML(loader.data);

      // Loop through the user list to check
      // if the inputted user id and password are valid
      for each (var user:XML in externalXML.elements()) {
         if (user.userid == userid.text && user.password == password.text) {
            // user has an valid account
            logged = true;
            // Don't need to continue
            break;
         }
      }
      if (logged) {
         Alert.show('Congratulation, you logged in!', 'Information');
         // you could redirect user to main form here
      } else {
         Alert.show('User ID or Password is not correct, please try again!', 'Error');
      }

   } catch (e:TypeError) {
      trace("Could not parse the XML file.");
   }
}
private function errorHandler(e:IOErrorEvent):void {
   Alert.show("Had problem loading the XML File.");
}

The final step is to add click event for Login button [click=”loginCheck()”].

Reference resources

Working with XML in Flex 3 and Java-part1
URLLoader

Hope this help!

※All comments or improve ideas will always be appreciated.

In the next article, I’ll show you how to make login form using Flex and AMFPHP (a remote object access method)

Categories: Adobe Flex/Air Tags:

Error: unable to resolve ‘image name’ for transcoding

August 14, 2009 3 comments

i needed to find some sample about how to customize default flex PreLoader and found two great tutorials

Custom Flex 3 Lightweight Preloader with source code
Flex Custom Preloader

When i tried to add into my project and built it, the [Error: unable to resolve ‘image name’ for transcoding] was thrown. Because i’m using FlashDevelop so it might be a little difference from Flex Builder. Maybe the image path cannot be regconized. The original source code as below:

[Embed("Assets/Pathfinder_Logo_Blue.png") ]
[Bindable] public var Logo:Class;

To handle the error, the solution is kind of simple. Just add [/] before the path that points to the image.

[Embed("/Assets/Pathfinder_Logo_Blue.png") ]
[Bindable] public var Logo:Class;
Categories: Adobe Flex/Air Tags: ,

Convert Westen datetime to Japanese calendar

August 11, 2009 Leave a comment
using System;
using System.Globalization;

class WarekiSample1 {
   static void Main() {
      DateTime 日付 = new DateTime(2003, 7, 1, 12, 34, 56);
      JapaneseCalendar カレンダー = new JapaneseCalendar();
      Console.WriteLine(カレンダー.GetEra(日付));
      // 出力:4
      string [] 元号名 = { "明治", "大正", "昭和", "平成" };
      Console.WriteLine(元号名[カレンダー.GetEra(日付) - 1]);
      // 出力:平成
      Console.WriteLine(カレンダー.GetYear(日付));
      // 出力:15
   }
}
Categories: Visual C# Tags:

Add auto increment column in PostgreSQL

August 10, 2009 13 comments

In PostgreSQL, we cannot just add an column and mark it as auto increment like in MySQL or SQL Server. Instead, we have to create an sequence and link it to the specified column.

1. Assume that we have a table called [testtbl] with an unique column called [id]

2. Generate sequence

CREATE SEQUENCE <Sequence name>

=>

CREATE SEQUENCE <testtbl_id_seq>

※After the sequence’s already created, we can call NEXTVAL(‘<Sequence name>’) to generate a new value automatically.


3. Link the sequence to the unique column

ALTER TABLE <Table name>
ALTER COLUMN <Column name>
SET DEFAULT NEXTVAL(<Created sequence name>);

=>

ALTER TABLE testtbl
ALTER COLUMN id
SET DEFAULT NEXTVAL('testtbl_id_seq');

That’s all what we have to do.

Categories: PostgreSQL Tags:

Flex custom Alert message

August 6, 2009 4 comments

How do you feel about the default Flex Alert box? i think it’s kind of simple, don’t you?

Udayms give us an amazing customize of it from here. His example works fine except with Confirm message. Even if yes or no is selected, nothing seem to happen. I don’t know if i missed something but after trying to look around finally i figured it out.

public static function confirm(message:String, parent:Sprite=null, closehandler:Function=null):void{
   //show(message, "Confirmation", Alert.YES | Alert.NO, null, closehandler, iconConfirm);
   show(message,  'Confirmation',  Alert.OK| Alert.CANCEL, null,  closehandler,  iconConfirm, Alert.OK);
}

By replacing Alert.YES/Alert.No by Alert.OK/Alert.CANCEL it seems work in my case.

Information
Confirmation
Error
Click here to download source code.

Categories: Adobe Flex/Air Tags:

HTTPService result remains previous loaded data

August 6, 2009 Leave a comment

I have a form with a Datagrid and an add new button (Original from http://learn.adobe.com/wiki/display/Flex/CRUD+-+Dynamic). When this form is launched, it’ll load all data and display on grid. After first call, although i tried to add new records to database, the display content of Datagrid is still the same as before.

This problem took me a lot of time before i figured out how to solve. It seems that the HTTP response had been cached by IE because the request URL remains the same each time the form is loaded.

So the key is how to change the request content when a request is launched? The answer is that we can use timestamp as a request parameter. This’s because the value of timestamp keep changing each time we have a request, so it’ll always be different.

<mx:HTTPService
   id="employeesService"
   url="http://localhost/flex/php/1/employees.php?{new Date().toDateString() + new Date().toTimeString()}"
   resultFormat="e4x"
   useProxy="false" />
Categories: Adobe Flex/Air Tags: