Thursday, August 8, 2013

CakePHP: Accessing database.php values

$fields = get_class_vars('DATABASE_CONFIG')

print_r($fields['default']);
or you can use; 
 
App::Import('ConnectionManager');
$ds = ConnectionManager::getDataSource('default');
$dsc = $ds->config;

print_r($dsc);
Will output like this:
Array
(
    [persistent] => 
    [host] => localhost
    [login] => root
    [password] => 
    [database] => db_name
    [port] => 3306
    [driver] => mysql
    [prefix] => 
) 

Extjs combobox:How to set user selected value as the default selected value

 /* Date store */
var dataStore = new Ext.data.JsonStore({
    proxy: new Ext.data.HttpProxy({
        url: Ext.SERVER_URL + 'get_data',
        method: 'post'
    }),
    listeners :{
        load:function() {
            /**
            /* The code block at the end labeled
            /* 'And select a value after load store' can be written here.
            */
        }
    },
    fields: ['id',  'name'],
    totalProperty: 'totalCount',
    root: 'data'
});

/* Suppose data returned as */
{totalCount: 2, data:  [{"id":1,"name":"First Item"},{"id":2,"name":"Second Item"}] }

/* Combobox initialize */
{
    xtype: 'combo',
    id: "domId",
    fieldLabel: 'Data Name',
    hiddenName: 'cb_data',
    store: dataStore,
    displayField: 'name',
    labelSeparator :'',
    valueField: 'id',
    typeAhead: true,
    autoSelect: true,
    mode: 'local',
    triggerAction: 'all',
    selectOnFocus: true,
    allowBlank: true,
    blankText: 'Select status',
    editable: false
}

/* And select a value after load store */
var combo = Ext.getCmp("domId");
combo.getStore().on(
    "load",function() {
        var value = 2;
        /* Set your value to select in combobox */
        /* This will select with id = 2 and label = 'Second Item'.
        if(value == 0) { /* Default selection */
            var recordSelected = combo.getStore().getAt(0);
            combo.setValue(recordSelected.get('id'));
        } else {
            combo.setValue(value);
        }
    },
    this,
    {
        single: true
    }
); 

jQuery check a checkbox without firing a change event

You should suspend events before set the value and resume events after this. For example:
myCheckBox.suspendEvents(false); // Stop all events. 
//Be careful with it. Dont forget resume events!
myCheckBox.setValue(!myCheckBox.getValue()); // invert value
myCheckBox.resumeEvents(); // resume events

Wednesday, August 7, 2013

Refund transaction using php api using eWay account

/* Refund using eWay */
function refund_using_eway()
{
    $testUrl = "https://www.eway.com.au/gateway/xmltest/refund_test.asp";
    $liveUrl = "https://www.eway.com.au/gateway/xmlpaymentrefund.asp";

    $eWaySOAPActionURL = "https://www.eway.com.au/gateway/managedpayment";
    $eWayCustomerId = "87654321";
    $eWayTotalAmount = 100;
    $directXML = "<ewaygateway>" .
        "<ewayCustomerID>" . $eWayCustomerId . "</ewayCustomerID>" .
        "<ewayOriginalTrxnNumber>20488</ewayOriginalTrxnNumber>" .
        "<ewayTotalAmount>" . $eWayTotalAmount . "</ewayTotalAmount>" .
        "<ewayCardExpiryMonth>01</ewayCardExpiryMonth>" .
        "<ewayCardExpiryYear>2015</ewayCardExpiryYear>" .
        "<ewayOption1></ewayOption1>" .
        "<ewayOption2></ewayOption2>" .
        "<ewayOption3></ewayOption3>" .
        "<ewayRefundPassword>test123</ewayRefundPassword>" .
        "</ewaygateway>";

    $result = makeCurlCall(
        $testUrl, /* CURL URL */
        "POST", /* CURL CALL METHOD */
        array( /* CURL HEADERS */
            "Content-Type: text/xml; charset=utf-8",
            "Accept: text/xml",
            "Pragma: no-cache",
            "SOAPAction: " . $eWaySOAPActionURL,
            "Content_length: " . strlen(trim($directXML))
        ),
        null, /* CURL GET PARAMETERS */
        $directXML /* CURL POST PARAMETERS AS XML */
    );

    if ($result != null && isset($result["response"])) {
        $response = new SimpleXMLElement($result["response"]);
        $response = simpleXMLToArray($response);
        print_r2($response);
    }
    die("");
}

/* makeCurlCall */
function makeCurlCall($url, $method = "GET", $headers = null, $gets = null, $posts = null) {
    $ch = curl_init();
    if($gets != null)
    {
        $url.="?".(http_build_query($gets));
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    if($posts != null)
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    }
    if($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
    } else if($method == "PUT") {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    } else if($method == "HEAD") {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }
    if($headers != null && is_array($headers))
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

    curl_close($ch);
    return array(
        "code" => $code,
        "response" => $response
    );
}

/* Response */
Array
(
    [ewayTrxnStatus] => Array
        (
            [__cdata] => False
        )

    [ewayTrxnNumber] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption1] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption2] => Array
        (
            [__cdata] =>
        )

    [ewayTrxnOption3] => Array
        (
            [__cdata] =>
        )

    [ewayAuthCode] => Array
        (
            [__cdata] =>
        )

    [ewayReturnAmount] => Array
        (
            [__cdata] => 100
        )

    [ewayTrxnError] => Array
        (
            [__cdata] => Error: Invalid Original Transaction Number. Your credit card has not been billed for this transaction.
        )

)

/* Dont worry about ewayTrxnError, when you refund live it will work */

Grails bean/service initialization dynamically to handle circular dependency

Suppose you have a service named OneService and another service named TwoService;
Now if you try to initiate TwoService in OneService and OneService in TwoService then you have some error regarding circular depency.

class OneService {
    def twoService;
}

class TwoService {
    def oneService;
}
To handle this you may need some trick.
First create a private static variable myTwoService and then initiate it when call it.

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA

class OneService {
    def ctx
    private static TwoService myTwoService;

    def getTwoService() {
        if(!ctx) {
            ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        }
        if(!myTwoService) {
            myTwoService = ctx.getBean("twoService");
        }
        return myTwoService;
    }

    def someFunction = {
        def str = twoService.callSomeFunction();  
        /* it actually call getTwoService */
    }
}
And change you TwoService to call OneService such this way.

How do I get an instance of a Grails service programmatically

The Grails documentation describes a way to get a service when in a servlet. This might be useful, if you can obtain the same objects in your context:

ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello("Some String!");

Sunday, August 4, 2013

Image Data URIs with JavaScript

<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>


You will need to create a canvas element with the correct dimensions and copy the image data with thedrawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL();

    return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "data:image/png;base64,BASE_64_IMAGE_DATA";