Thursday, November 21, 2013

Test Credit Card Numbers for Payment Gateways

Notes to Myself
MIGS (ANZ Bank, Bendigo Bank, Suncorp Bank, Commonwealth Bank CommWeb)
Card TypeNumberExpiry DateCCV
MasterCard512345678901234605/17123
MasterCard531358100012343005/17123
VISA400555000000000105/17123
VISA455701234567890205/17123
AMEX34567890123456405/171234
Bankcard (Australian Domestic)561090123456789905/17123
Diners Club3012345678901905/17123

Saturday, January 19, 2013

Magento - How to switch Base URLs without modifying the Database

As Magento keeps its base URL in database, there is no easy way of accessing the same database from two different URLs(dev/ staging) or moving the same database to staging environment from development without updating core_config_data table.

After fiddling around with Magento core, I found that getBaseUrl() is responsible of retrieving base URL. So If we could override getBaseUrl() method to get the base URL from dev or staging environments without depending on the database, then we could keep database records with live settings.

Below code will explain how I achieved this task and the code itself is explainable.

1. app/etc/modules/My_Configurator.xml

    
        
            true
            local
        
    


2. app/code/local/My/Configurator/etc/config.xml

    
        
            
                
                    My_Configurator_Model_Store
                
            
        
    


3. app/code/local/My/Configurator/Model/Store.php


Note: Make sure you disable this extension from production server as we want to run getBaseUrl() method from the Core.

Happy Coding..

Wednesday, December 19, 2012

Symfony2 - Load different templates based on user agent

If you want to load different templates for different user agents while keeping the same backend code base, you can accomplish this simply in 2 ways.

  1.  Responsive Template
  2. Load different templates against user agents.
In this blog post I'm trying to demonstrate the option 2 (load different templates against user agents)

The trick is to use RequestFormat in symfony

1. Create a Request Listener

php app/console generate:bundle --namespace=Acme/RequestListenerBundle --format=yml


Note: You don't need Controller, Tests directories

Past the below code to AcmeRequestListnerBundle.php

getRequest();

        if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $request->headers->get('user-agent')))
        {
            $request->setRequestFormat('mobile', 'text/html');
        }else {
            $request->setRequestFormat('html', 'text/html');
        }
    }

    private function setFormat (\Symfony\Component\HttpFoundation\Request $request, $format='html') {
        $request->setRequestFormat($format, 'text/html');
    }
}

2. Create a test action in your controller

Action 

    /**
     * @Route("/test", name="_demo_test")
     * @Template()
     */
    public function testAction()
    {
        return array(
            'name' => 'Thilanga Pitigala',
        );
    }

Note: Run
php app/console router:debug | grep _demo_test
and verify the newly created action and the router

Template
Create the template for newly created action

Acme/DemoBundle/Resources/views/Demo/test.html.twig

{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block title "Hello " %}

{% block content %}
    

Hello Desktop !

{% endblock %}

2. Create a Service using RequestListener

Add below code to config.yml

services:
    acme.listener.request:
        class: Acme\RequestListenerBundle\AcmeRequestListenerBundle
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Note: run
php app/console container:debug | grep acme.listener.request
  and That will output the newly created service

2. Test RequestListener service

Try visiting the web applications from mobile device. It will throw an error complaining about missing test.mobile.twig file.

Create the test.mobile.twig file in Acme/DemoBundle/Resources/views/Demo/test.html.twig as we created the test.html.twig template.

Now you will be able to see the mobile template from mobile devices while desktop template load for desktop agents.

By that way we can load different templates for different agents without doing any responsive templates.

Happy Coding..

Monday, December 17, 2012

Symfony2 - Setup an Application in a minute

1. Download

Download the Symfony Standard Edition from http://symfony.com/download (at the moment of writing this post latest stable version is 2.1)

cd /home/user/Downloads/
wget --content-disposition 'http://symfony.com/download?v=Symfony_Standard_Vendors_2.1.4.tgz'
tar -zxvf Symfony_Standard_Vendors_2.1.4.tgz
mv Symfony /var/www/symfony

Then Point /var/www/symfony/web directory to the your web server

2. Configuration


Now We are going to use app.php as the main index file instead of playing with app_dev.php within the development enviroment.

vim web/app.php

Replace your app.php with the below code


// Make group permissions stick in cache/log dirs
umask(0002);

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

$env = 'prod';

if (isset($_SERVER['HTTP_HOST'])) {
    if (preg_match('/(localhost|local\.)/', $_SERVER['HTTP_HOST'])) {
        $env = 'dev';
    }
}

$kernel = new AppKernel($env, $env == 'dev');
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Load your Symfony site by typing http://localhost/symfony in your web browser
Now you can access Symfony Development environment without visiting to app_dev.php.





Wednesday, October 24, 2012

Why Symfony2?

With the PHP5 there was a big hype in PHP frameworks and MVC pattern. As a result, lots of developers got lost within frameworks while trying to figure out the best.

I was one of them.

When it comes to PHP frameworks, ZEND, CodeIgniter were my favourites.  I used CodeIgniter for simple applications and ZEND framework was the giant who saved my good hours. But I never enjoyed PHP with frameworks. Frameworks are good for just get things done.

After I joined with August I got chance to work with Symfony. Not just Symfony, It's Symfony2 :)

Symfony2 is one of a kind framework, it is not a MVC framework. If you look at the Symfony2 architecture, you could find controllers, views but no models. It has been developed as a HTTP framework.

That is how the web works.

The biggest concern in Symfony2 is decoupling and from the core it has given reusable set of standalone components to use. Simply it has provided a set of tools to develop applications as we want.

At the beginning, I was really frustrated because it seems to be complicated and over engineered. however after few days of work I started liking how it works.

The most impressive part in Symfony2 is the 'Bundle' concept. If you write a Symfony2 bundle, simply you can run it within any Symfony2 project without a hassle.  A bundle contains it's own configurations, routing rules, actions, templates and business logic codes.

Dependency injection is another powerful feature which we can commonly see in JAVA developments. That means Symfony2 has adopted lots of best things from other languages without trying to reinvent the wheel.

According the the Symfony2 documentation, it contains 21 standalone libraries which we can use for day-to-day developments.
  1. DependencyInjection
  2. EventDispatcher
  3. HttpFoundation
  4. DomCrawler
  5. ClassLoader
  6. CssSelector
  7. HttpKernel
  8. BrowserKit
  9. Templating
  10. Translation
  11. Serializer
  12. Validator
  13. Security
  14. Routing
  15. Console
  16. Process
  17. Config
  18. Finder
  19. Locale
  20. Yaml
  21. Form

It is not an easy task to explain the awesomeness of Symfony2 in a single blog post :)

This is going to be the very first of many blog posts about Symfony2. I'll be writing some tutorials specially for beginners who are willing to use Symfony2 in their next projects.


Monday, March 12, 2012

How to setup an ultra-fast CDN using Nginx and Varnish

If your website takes more than 3 seconds to load, there is a big chance to loose your site visitors and that is a risk we are dealing with today due to the big competition in the industry.

There are lots of reasons which effects on the site's speed. 
  1. Large multimedia contents
  2. DNS look up issue
  3. Server response time 
  4. Multiple redirects
are few from a lengthy list.

If you are using a good CDNs to serve contents, then that will give a good boost while loading the site. Last month I had to setup up Our own CDN for WSO2 Oxygentank Developer Portal and i'm trying to summaries steps that I followed.

Installing Nginx and varnish

  1. apt-get install nginx
  2. apt-get install varnish
Nginx Config

  • (/etc/nginx/sites-enabled/default)server {
           open_file_cache_valid 20m;
            listen 81;
            server_name mydomain.com;
            access_log   /var/log/cdn/mydomain.com/logs/access.log;
            root   /cdn_document_path/;

            location ~* \.(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|css|mp3|swf|ico|flv)$ {
                            open_file_cache_valid 120m;
                            expires 7d;
                            open_file_cache max=1000 inactive=20s
            }
           
             location = /50x.html {
                            root   /var/www/nginx-default;
            }

            # No access to .htaccess files.
            location ~ /\.ht {
                deny  all;
            }
    }


Varnish Config

  • (/etc/default/varnish)START=yes
    NFILES=131072
    MEMLOCK=82000
    INSTANCE=$(uname -n)
    DAEMON_OPTS="-a :80 \
                 -T localhost:6082 \
                 -f /etc/varnish/default.vcl \
                 -S /etc/varnish/secret \
                 -s file,/var/lib/varnish/$INSTANCE/varnish_storage.bin,1G"
  • (/etc/varnish/default.vcl)backend default {
        .host = "127.0.0.1";
        .port = "81";
    }

    sub vcl_recv {
    if (req.url ~ “\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$”) {
    return (lookup);
    }
    }

    sub vcl_fetch {
    if (req.url ~ “\.(js|css|jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf)$”) {
    unset obj.http.set-cookie;
    }
    }
Start Nginx and Varnish
  1. /etc/init.d/nginx start
  2. /etc/init.d/varnish restart
Once you start Nginx and Varnish. Varnish will start to server port 80 web traffic. If it is a static content varnish will server and nginx will look after all dynamic contents.

Friday, December 30, 2011

How to Setup smstools in debian

3G dongle is the only bandwidth service I have when i'm home. (If my neighbor didn't turn on his WIFI connection ). Due to heavy usage of mobile broadband, my 3g Dongle frequently get caught to service disruptions by exceeding the reserved data bundle, Most of the time I had to call 3G service provider to get the connection temporary to do an online payment.

Normally service provider send a SMS when reaching the reserved quota (Probably when reaching 75%). But as I can't use Mobile Partner software in linux, I always missed those SMSs, if I didn't connect my dongle in to a Windows powered machine (As I hardly use Windows OS, most of the time I was in trouble).

As a solution I installed and configured smstools to avoid this mess and getting alone without the Internet.

Install smstools
  1. sudo apt-get install smstools (Install smstools)
  2. dmesg | grep usb (get the device. ex: /dev/ttyUSB0)
  3. sudo vim /etc/smsd.conf (smstools config file)
  4. sudo /etc/init.d/smstools start (Start smstools after changing configurations)
  5. cd  /var/spool/sms/incoming (to see incoming sms)

Configuration  (/etc/smsd.conf)

devices = GSM1
outgoing = /var/spool/sms/outgoing
checked = /var/spool/sms/checked
incoming = /var/spool/sms/incoming
logfile = /var/log/smstools/smsd.log
infofile = /var/run/smstools/smsd.working
pidfile = /var/run/smstools/smsd.pid
outgoing = /var/spool/sms/outgoing
checked = /var/spool/sms/checked
failed = /var/spool/sms/failed
incoming = /var/spool/sms/incoming
sent = /var/spool/sms/sent
receive_before_send = no
autosplit = 3

[GSM1]
device = /dev/ttyUSB0
incoming = yes
baudrate = 19200
memory_start = 1

If you configured the smstools properly you will get sms to  /var/spool/sms/incoming

Test your settings.
  1. Send a test sms to your 3G Dongle from a mobile phone
  2. then ls /var/spool/sms/incoming (if the dongle received the sms, you will see a file, name is slimier to GSM1.AuvV6s  )
  3. vim  /var/spool/sms/incoming/$filename to read the sms
Debug your setings
  1. sudo tail -f /var/log/smstools/smsd.log
Note: I didn't test sms sending through the 3G dongle as my service provider has blocked the facility.