Monday, May 6, 2013

Get event click list item in J2ME

In midp a list is actually more like a menu with a selection of choices. You have to set a command on it, so that in your command action you can dispatch on this command, get the selection form the menu and set the next screen accordingly.

package com.pkm;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author User
 */
public class HelloMIDlet extends MIDlet implements javax.microedition.lcdui.CommandListener {
    private Display display;
    
    private Form form = new Form("Sign In Please");
    
    private Command submit = new Command("Submit", Command.SCREEN, 1);
    private Command exit = new Command("Exit", Command.EXIT, 1);
    private Command contactList = new Command("contactList", Command.OK, 1);
    private Command selection=new Command("Select", Command.ITEM, 1);
    
    List services;
    
    private TextField userName = new TextField("First Name:", "", 50, TextField.ANY);
    private TextField password = new TextField("Password", "", 30, TextField.PASSWORD);

    public HelloMIDlet() {
        display = Display.getDisplay(this);
        form.addCommand(submit);
        form.addCommand(exit);
        form.append(userName);
        form.append(password);
        form.setCommandListener(this);
    }

    public void startApp() {
        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == submit) {
            validateUser(userName.getString(), password.getString());
        } else if (command == exit) {
            destroyApp(false);
            notifyDestroyed();
        } else if (command == contactList) {
            ContactList contactList = new ContactList("Contact List", this);
            display.setCurrent(contactList);
        } else if (command == selection) {
            int index = services.getSelectedIndex();
            Alert alert = new Alert("Your selection",
            "You chose " + services.getString(index) + ".",
            null, AlertType.INFO);
            Display.getDisplay(this).setCurrent(alert, services);
        }
    }
    
    public void validateUser(String name, String password) {
        if (name.equals("a") && password.equals("a")) {
            menu();
        } else {
            tryAgain();
        }
    }
    
    public void menu() {
        services = new List("Choose one", List.IMPLICIT);
        services.append("Check Mail", null);
        services.append("Compose", null);
        services.append("Addresses", null);
        services.append("Options", null);
        services.append("Sign Out", null);
        services.setSelectCommand(selection);
        services.addCommand(contactList);
        services.setCommandListener(this);
        
        display.setCurrent(services);
    }

    public void tryAgain() {
        Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
        error.setTimeout(Alert.FOREVER);
        userName.setString("");
        password.setString("");
        display.setCurrent(error, form);
    }

    void displayMainMIDlet() {
        menu();
    }
}

Sunday, May 5, 2013

ExtJS: HtmlEditor command list

The following list of commands is presented in alphabetical order. The commands may be mixed case or whatever makes your code more readable.
command value explanation / behavior
backcolor ???? This command will set the background color of the document.
bold none If there is no selection, the insertion point will set bold for subsequently typed characters.

If there is a selection and all of the characters are already bold, the bold will be removed.  Otherwise, all selected characters will become bold.
contentReadOnly true
false
This command will make the editor readonly (true) or editable (false).  Anticipated usage is for temporarily disabling input while something else is occurring elsewhere in the web page.
copy none If there is a selection, this command will copy the selection to the clipboard.  If there isn't a selection, nothing will happen.

note: this command won't work without setting a pref or using signed JS.  See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-C) with or without the signed JS or any code on the page to handle it.
createlink url (href) This command will not do anything if no selection is made.  If there is a selection, a link will be inserted around the selection with the url parameter as the href of the link.
cut none If there is a selection, this command will copy the selection to the clipboard and remove the selection from the edit control.  If there isn't a selection, nothing will happen.

note: this command won't work without setting a pref or using signed JS.  See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-X) with or without the signed JS or any code on the page to handle it.
decreasefontsize none This command will add a <small> tag around selection or at insertion point.
delete none This command will delete all text and objects that are selected.
fontname ???? This command will set the fontface for a selection or at the insertion point if there is no selection.
fontsize ???? This command will set the fontsize for a selection or at the insertion point if there is no selection.
forecolor ???? This command will set the text color of the selection or at the insertion point.
formatblock <h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<pre>
<address>
<p>
p
[this list may not be complete]

heading <h1>
<h2>
<h3>
<h4>
<h5>
<h6>

hilitecolor ???? This command will set the hilite color of the selection or at the insertion point.  It only works with usecss enabled.
increasefontsize none This command will add a <big> tag around selection or at insertion point.
indent none Indent the block where the caret is located.
inserthorizontalrule none This command will insert a horizontal rule (line) at the insertion point.

Does it delete the selection?
inserthtml valid html string This command will insert the given html into the <body> in place of the current selection or at the caret location.
insertimage url (src) This command will insert an image (referenced by url) at the insertion point.

Does it delete the selection?
insertorderedlist none
insertunorderedlist none
insertparagraph none
italic none If there is no selection, the insertion point will set italic for subsequently typed characters.

If there is a selection and all of the characters are already italic, the italic will be removed.  Otherwise, all selected characters will become italic.
justifycenter none
justifyfull none
justifyleft none
justifyright none
outdent none Outdent the block where the caret is located.  If the block is not indented prior to calling outdent, nothing will happen.

note:  is an error thrown if no outdenting is done?
paste none This command will paste the contents of the clipboard at the location of the caret.  If there is a selection, it will be deleted prior to the insertion of the clipboard's contents.

note: this command won't work without setting a pref or using signed JS.
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess");

See: http://www.mozilla.org/editor/midasdemo/securityprefs.html

note:  the shortcut key will automatically trigger this command (typically accel-V) with or without the signed JS or any code on the page to handle it.
redo none This command will redo the previous undo action.  If undo was not the most recent action, this command will have no effect.

note:  the shortcut key will automatically trigger this command (typically accel-shift-Z)
removeformat none
selectall none This command will select all of the contents within the editable area.

note:  the shortcut key will automatically trigger this command (typically accel-A)
strikethrough none If there is no selection, the insertion point will set strikethrough for subsequently typed characters.

If there is a selection and all of the characters are already striked, the strikethrough will be removed. Otherwise, all selected characters will have a line drawn through them.
styleWithCSS true
false
This command is used for toggling the format of generated content.  By default (at least today), this is true.  An example of the differences is that the "bold" command will generate <b> if the styleWithCSS command is false and generate css style attribute if the styleWithCSS command is true.
subscript none If there is no selection, the insertion point will set subscript for subsequently typed characters.

If there is a selection and all of the characters are already subscripted, the subscript will be removed.  Otherwise, all selected characters will be drawn slightly lower than normal text.
superscript none If there is no selection, the insertion point will set superscript for subsequently typed characters.

If there is a selection and all of the characters are already superscripted, the superscript will be removed.  Otherwise, all selected characters will be drawn slightly higher than normal text.
underline none If there is no selection, the insertion point will set underline for subsequently typed characters.

If there is a selection and all of the characters are already underlined, the underline will be removed.  Otherwise, all selected characters will become underlined.
undo none This command will undo the previous action.  If no action has occurred in the document, then this command will have no effect.

note:  the shortcut key will automatically trigger this command (typically accel-Z)
unlink none

ExtJS: Add font family custom drop down in toolbar

ExtJS has some command to make it easy. ExtJS has some font names, but if you want more font then you
shoud make your own component. The following component override the existing font names with some
font name you provide, such I provide extra font name "Candara" here.
Some command in ExtJS HtmlEditor:
this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;');
this.execCmd('InsertText','\t');

this.execCmd('useCSS'true);

this.execCmd('styleWithCSS'false);


doc this.getDoc();

doc.queryCommandValue('FontName');
doc.queryCommandState('bold');

doc.queryCommandState('italic');

doc.queryCommandState('underline');

doc.queryCommandState('justifyleft');

doc.queryCommandState('justifycenter');

doc.queryCommandState('insertorderedlist');

doc.queryCommandState('insertunorderedlist');


this.insertAtCursor('<hr/>');



doc.selection.createRange();

r.collapse(true); r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus();


Ext.form.HtmlEditor.Font = Ext.extend(Ext.util.Observable, {
    init: function(cmp){
        this.cmp = cmp;
        this.cmp.on('render', this.onRender, this);
    },
    // private
    onRender: function(){
        var cmp = this.cmp;
        var fonts = function(){
            var fnts = [];
            Ext.each(cmp.fontFamilies, function(itm){
                fnts.push([itm.toLowerCase(),itm]);
            });
            fnts.push(["candara", "Candara"]);
            return fnts;
        }();
        var btn = this.cmp.getToolbar().addItem({
            xtype: 'combo',
            displayField: 'display',
            valueField: 'value',
            name: 'fontfamily',
            forceSelection: true,
            selectOnFocus: true,
            selected: "Candara",
            editable: false,
            mode: 'local',
            triggerAction: 'all',
            width: 80,
            emptyText: 'Font',
            tpl: '<tpl for="."><div class="x-combo-list-item" style="font-family:{value};">{display}</div></tpl>',
            store: {
                xtype: 'arraystore',
                autoDestroy: true,
                fields: ['value','display'],
                data: fonts
            },
            listeners: {
                'select': function(combo,rec){
                    cmp.relayCmd('FontName', rec.get('value'));
                },
                scope: cmp
            }
        });
    }
});

ExtJS: add button to htmleditor

I am using ExtJS and I have a htmleditor in my form. I would like to add a custom button to that element (for example after all other buttons like alignments, font weights, ...). This button should basically insert a standard template in the htmlfield. Being this template html, the behaviour of the button should be like this
  • Switch to HTML mode (like when pressing Source button)
  • Insert something
  • Switch back to WYSIWYG mode (like when pressing the Source button again)


Ext.ns('Ext.ux.form.HtmlEditor');

Ext.ux.form.HtmlEditor.HR = Ext.extend(Ext.util.Observable, {
    init: function(cmp){
        this.cmp = cmp;
        this.cmp.on('render', this.onRender, this);
    },
    onRender: function(){
        this.cmp.getToolbar().addButton([{
            iconCls: 'x-edit-custom', //your iconCls here
            handler: function(){
                this.cmp.insertAtCursor('<hr>');
            },
            scope: this,
            tooltip: 'horizontal ruler',
            overflowText: 'horizontal ruler'
        }]);
    }
});

var w = new Ext.Window({
    width: 550,
    layout: 'fit',
    items: [{
        xtype: 'htmleditor',
        plugins: [new Ext.ux.form.HtmlEditor.HR()]
    }]
});
w.show();

But I really recommend you to see the project HtmlEditor.Plugins at google code. There you can find a lot more about adding custom buttons, for instance, how to enable/disable the buttons when something is selected, put separators, etc.
https://docs.google.com/file/d/0B5nZNPW48dpFb0hJVmpVUEphZGc/edit?usp=sharing

Saturday, May 4, 2013

Yii Examples of Using CDbCriteria

Basic Usage
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Products = Product::model()->findAll($Criteria);
OR
//An example using the constructor to populate the properties.
$Criteria = new CDbCriteria(array('condition' => 'price > 30'));
$Products = Product::model()->findAll($Criteria);
Personally, I like to go with the first approach. I think it’s generally easier to read, but that’s just my personal preference.
Adding A Limit
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Products = Product::model()->findAll($Criteria);
Limit with Offset
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Products = Product::model()->findAll($Criteria);
Ordering Results
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Criteria->order = "name ASC";
$Products = Product::model()->findAll($Criteria);
Limiting Selected Fields
$Criteria = new CDbCriteria();
$Criteria->condition = "price > 30";
$Criteria->limit = 1;
$Criteria->offset = 1;
$Criteria->order = "name ASC";
$Criteria->select = "id, name";
$Products = Product::model()->findAll($Criteria);
Example relation with :
$criteria = new CDbCriteria;
/* You can use condition as first parameter and must one conditions,
which will make and conditions with other compare values  */
$criteria->conditions = 'is_user_deleted = 0 OR is_user_deleted = 2'; 
 
$criteria->with = array('groupGroup');
$criteria->together = true; // ADDED THIS
$criteria->compare( 'groupGroup.id', $this->group_id, true ); 
/* true means compare as like '% value %' */
$criteria->compare('first_name',$this->first_name,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->order = 'first_name ASC';
$criteria->limit = 10;
If two table has same column, then need to modify some code suppose-
1. $criteria->compare($this->getTableAlias().'.deleted','0',true);
Here both this table and 'group' table has same column named 'deleted', but now 
only compare with current tables 'deleted' field. 
And foreign table must be in relations...
public function relations() {
    return array(
         'groupGroup' => array(self::BELONGS_TO, 'Group', 'group_id')
        /* group_id is current models foreign key from 'group' table. */
     );
}

Thursday, May 2, 2013

Strip out html tags using php code


<?php
function strip_html_tags($text)
{
    $text = preg_replace(
        array(
            // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',
            // Add line breaks before and after blocks
            '@</?((address)|(blockquote)|(center)|(del))@iu',
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ), "", $text);
    return strip_tags($text);
}
?>

Wednesday, May 1, 2013

Rollback or Commit with PDO transaction using php and mysql

A transaction should end with either a rollback() or a commit(), (only one of them).
In case you are using MySQL, make sure you are not using MyISAM engine for tables, as it doesn't support transactions. It usually support InnoDB.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.


$dbh = null;
try {
    $dbh = new PDO("mysql:host=HOST_NAME;dbname=DB_NAME", "DB_USER_NAME", "DB_USER_PASSWORD");

    /*** Set the PDO error mode to exception (will throw exception if any error occurred) ***/
    /*** Follow the link for more info: http://php.net/manual/en/pdo.setattribute.php ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

    /*** Creating a test table if not exists ***/
    $table = "CREATE TABLE IF NOT EXISTS test_transaction ( " .
        "id MEDIUMINT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY, ".
        "name VARCHAR(25) NOT NULL, designation VARCHAR(25) NULL )";
    $dbh->exec($table);

    /*** Transaction block starting here ***/
    $dbh->beginTransaction();

    /*** Inserting some data ***/
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #1', '')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #2', '')");

    /*** The following query result 2 outputs ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    /*** Again inserting some more data ***/
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #1', 'Designation #1')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #2', 'Designation #2')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #3', 'Designation #3')");

    /*** The following query result 5 outputs ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    /*** Throwing an exception to test if transaction really works ***/
    throw new Exception("All data will be erased during this transaction");
}
catch(Exception $ex) {
    $dbh->rollback();

    /*** The following query result 0 outputs as transaction failed ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    echo "Exception: ".$ex->getMessage();
    die();
}


Output be as follows:

Array
(
    [0] => Array
        (
            [id] => 29
            [0] => 29
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => 
            [2] => 
        )

    [1] => Array
        (
            [id] => 30
            [0] => 30
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => 
            [2] => 
        )

)

Array
(
    [0] => Array
        (
            [id] => 29
            [0] => 29
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => 
            [2] => 
        )

    [1] => Array
        (
            [id] => 30
            [0] => 30
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => 
            [2] => 
        )

    [2] => Array
        (
            [id] => 31
            [0] => 31
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => Designation #1
            [2] => Designation #1
        )

    [3] => Array
        (
            [id] => 32
            [0] => 32
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => Designation #2
            [2] => Designation #2
        )

    [4] => Array
        (
            [id] => 33
            [0] => 33
            [name] => Pritom #3
            [1] => Pritom #3
            [designation] => Designation #3
            [2] => Designation #3
        )

)

Array
(
)

Exception: All data will be erased during this transaction