Author Archive

Using Twig library with Codeigniter

Posted: September 18, 2013 by abhijeetgk in Uncategorized

Quite few days back worked on TWIG the template engine for PHP and tried if can be used in my existing codeigniter setup

Want to share following quick steps which may be useful for using with codeigniter

Step 1

Create Twig cache directory under “application / cache ” folder and make sure its writable..

Step 2

Download the TWIG library HERE and put in libraries folder so it will follow following directory structure

application/libraries/Twig
|-- Error
|-- Extension
|-- Filter
|-- Function
|-- Loader
|-- Node
|   `-- Expression
|       |-- Binary
|       `-- Unary
|-- NodeVisitor
|-- Sandbox
|-- Test
`-- TokenParser

Now create Library files

File 1=> application/libraries/Twig.php

################################################

<?php if (!defined(‘BASEPATH’)) {exit(‘No direct script access allowed’);}
class Twig
{
private $CI;
private $_twig;
private $_template_dir;
private $_cache_dir;
/**
* Constructor
*
*/
function __construct($debug = false)
{
$this->CI =& get_instance();
$this->CI->config->load(‘twig’);
ini_set(‘include_path’,
ini_get(‘include_path’) . PATH_SEPARATOR . APPPATH . ‘libraries/Twig’);
require_once (string) “Autoloader” . EXT;
log_message(‘debug’, “Twig Autoloader Loaded”);
Twig_Autoloader::register();
$this->_template_dir = $this->CI->config->item(‘template_dir’);
$this->_cache_dir = $this->CI->config->item(‘cache_dir’);
$loader = new Twig_Loader_Filesystem($this->_template_dir);
$this->_twig = new Twig_Environment($loader, array(
                ‘cache’ => $this->_cache_dir,
                ‘debug’ => $debug,
));
foreach(get_defined_functions() as $functions) {
             foreach($functions as $function) {
                 $this->_twig->addFunction($function, new Twig_Function_Function($function));
             }
         }
}
public function add_function($name)
{
$this->_twig->addFunction($name, new Twig_Function_Function($name));
}
public function render($template, $data = array())
{
$template = $this->_twig->loadTemplate($template);
return $template->render($data);
}
public function display($template, $data = array())
{
$template = $this->_twig->loadTemplate($template);
/* elapsed_time and memory_usage */
$data['elapsed_time'] = $this->CI->benchmark->elapsed_time(‘total_execution_time_start’, ‘total_execution_time_end’);
$memory = (!function_exists(‘memory_get_usage’)) ? ’0′ : round(memory_get_usage()/1024/1024, 2) . ‘MB’;
$data['memory_usage'] = $memory;
$template->display($data);
}
}
###########################################

File 2 application/config/twig.php

##############################################
<?php if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
$config['template_dir'] = APPPATH.’views’;
$config['cache_dir'] = APPPATH.’cache/twig’;
###################################3

Step 3 USAGE

Put in you controller
$this->load->library('twig');

$data['title'] = "twig loaded";

$this->twig->display('view.html', $data);


simple huh…..

 

reference 

Even though we are having more  experience then too at some expert level we too do some beginner level mistakes, for me this is 100% true

 

Found one post on google reader from NetTuts+ want to share it for viewers. Please note that its not mine but sharing as liked it.

 

Learn from our mistakes; don’t do these things!

 


JavaScript Tips

1 - Unnecessary DOM Manipulation

The DOM is slow. Limiting your interaction with it will greatly increase your code’s performance. Consider the following (bad) code:

// anti-pattern
for (var i = 0; i < 100; i++){
	var li = $("<li>").html("This is list item #" + (i+1));
	$("#someUL").append(li);
}

This code actually modifies the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! A more correct approach would be to either use a document fragment, or build up a string that contains the 100 <li/> elements, and then appends that HTML to the containing element. That way, you jump into the DOM a total of once. Here’s an example:

var liststring = "";
for (var i = 100; i > 0; i--){
	liststring += "<li>This is list item #" + (99- i);
}
document.getElementById("someUL").innerHTML(liststring);

As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string. There’s a different way that we could approach this, using arrays.

var liststring = "<li>"
var lis = [];
for (var i = 100; i > 0; i--){
	lis.push("This is list item #" + (99- i));
}
liststring += lis.join("</li><li>") + "</li>";
document.getElementById("someUL").innerHTML(liststring);

When building large strings, storing each piece of the string as an item within an array element and calling join() is more efficient than string concatenation. This is one of the fastest and easiest ways to build repetitive HTML in JavaScript without using a template library or framework.

2 - Inconsistent Variable & Function Names in JavaScript

This next item isn’t a performance issue, but is extremely important – especially if you are working on code that other people work on, as well. Keep your identifiers (variable and function names) consistent. Consider the following variables as an example:

var foo = "bar";
var plant = "green";
var car = "red";

It wouldn’t make sense to add another variable, called Something. This introduces inconsistency in your variable naming pattern, causing your brain to cognitively flag this variable as being different or special. This is why constants in most languages are traditionally defined with all caps.

You can take this a step further by maintaining similar length, grammatical structure, and explanatory nature when naming functions. For example, consider the following contrived function:

function subtractFive(number){
	return number - 5;
}

Naming a function that adds five to a given number should follow the same pattern, shown here:

function addFive(number){
	return number + 5;
}

Sometimes, you might name a function to indicate its return value. For instance, you might name a function that returns an HTML stringgetTweetHTML(). You might also prepend a function’s name with do, if the function simply performs an operation and doesn’t return a value, eg:doFetchTweets().

Constructor functions typically follow the tradition of classes in other languages, capitalizing the first letter:

function Dog(color){
	this.color = color;
}

As a general rule of thumb, you should be descriptive when naming your identifiers. Classify them together with other similar identifiers by maintaining a naming pattern that is readable and offers hints to the nature of a variable or function’s purpose.

3 - Use hasOwnProperty() in for...in Loops

JavaScript’s arrays are not associative; trying to use them as such is frowned upon by the community. Objects, on the other hand, can be treated as hash tables, and you can iterate over an object’s properties by using the for...inloop, like so:

for (var prop in someObject) {
    alert(someObject[prop]); // alert's value of property
}

The problem, however, is that the for...in loop iterates over every enumerable property on the object’s prototype chain. This can be problematic if you only want to use the properties that exist on the actual object.

You can solve this issue by using the hasOwnProperty() method. Here’s an example:

for (var prop in someObject) {
    if (someObject.hasOwnProperty(prop)) {
        alert(someObject[prop]); // alert's value of property
    }
}

This version only alerts the values of the properties that directly reside onsomeObject.

4 - Comparing Boolean Values

Comparing boolean values in a condition is a waste of computation time. Take a look at the following for an example:

if (foo == true) {
    // do something for true
} else {
    // do something for false
}

Notice the condition: foo == true. The comparison of foo and true is unnecessary because foo is already a boolean value (or it’s a truthy or falsey one). Instead of comparing foo, simply use it as the condition, like this:

if (foo) {
    // do something for true
} else {
    // do something for false
}

To test for false, use the logical NOT operator, as shown below:

if (!foo) {
    // do something if foo is false
} else {
    // do something if foo is true
}

5 - Event Binding

Events are a complicated subject in JavaScript. Gone are the days of inlineonclick event handlers (except in some very rare “splash page” cases). Instead, use event bubbling and delegation.

Let’s imagine that you have a grid of pictures that need to launch a modal lightbox window. Here’s what you shouldn’t do. Note: we’re using jQuery here, assuming you are using a similar library. If not, the same bubbling principles also apply to vanilla JavaScript.

The relevant HTML:

<div id="grid-container">
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	...
</div>

The (bad) JavaScript:

$('a').on('click', function() {
	callLightbox(this);
});

This code assumes that calling the lightbox involves passing an anchor element that references the full size image. Instead of binding to each anchor element, bind to the #grid-container element instead.

$("#grid-container").on("click", "a", function(event) {
	callLightbox(event.target);
});

In this code, both this and event.target refer to the anchor element. You can use this same technique with any parent element. Just make sure to define the element that should be the event’s target.

6 - Avoid Ternary Redundancy

The overuse of ternary statements is quite common both in JavaScript and PHP.

// javascript
return foo.toString() !== "" ? true : false;

// php
return (something()) ? true : false;

A condition expression always returns a true or false value, meaning you don’t need to explicitly add true/false as ternary values. Instead, you could simply return the condition:

// javascript
return foo.toString() !== "";

// php
return something();

PHP Tips

7 - Use Ternary When Appropriate

if...else statements are a central part of most languages. But doing something simple, such as assigning a value to a variable based upon a condition – well, they can junk up your code. Consider the following code:

if ($greeting)
{
    $post->message = 'Hello';
}
else
{
    $post->message = 'Goodbye';
}

This code can be reduced to one line, while still maintaining readability by using the ternary operator, like this:

$post->message = $greeting ? 'Hello' : 'Goodbye';

It’s clear, concise, and gives you the functionality you need.

As useful as the ternary operator is, the most important guideline is not to over-use it! The goal of coding is not to cramp your logic into as few lines as possible.

8 - Throw Exceptions Instead of Inception-Style Nesting

Let’s face it: many levels of nesting is ugly and difficult to maintain/read. The following code is a relatively simplified example, but they get much worse over time:

// anti-pattern
$error_message = null;
if ($this->form_validation->run())
{
	if ($this->upload->do_upload())
	{
		$image = $this->upload->get_info();
		if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
		{
			$error_message = 'There was an error creating the thumbnail.';
		}
	}
	else
	{
		$error_message = 'There was an error uploading the image.';
	}
}
else
{
	$error_message = $this->form_validation->error_string();
}
// Show error messages
if ($error_message !== null)
{
	$this->load->view('form', array(
		'error' => $error_message,
	));
}
// Save the page
else
{
	$some_data['image'] = $image['file_name'];
	$this->some_model->save($some_data);
}

That’s some nasty code, but you can make it drastically cleaner by using exceptions, like so:

try
{
	if ( ! $this->form_validation->run())
	{
		throw new Exception($this->form_validation->error_string());
	}
	if ( ! $this->upload->do_upload())
	{
		throw new Exception('There was an error uploading the image.');
	}
	$image = $this->upload->get_info();
	if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
	{
		throw new Exception('There was an error creating the thumbnail.');
	}
}
// Show error messages
catch (Exception $e)
{
	$this->load->view('form', array(
		'error' => $e->getMessage(),
	));
	// Stop method execution with return, or use exit
	return;
}
// Got this far, must not have any trouble
$some_data['image'] = $image['file_name'];
$this->some_model->save($some_data);

It might be the same number of lines, but it allows for considerably more readable and maintainable code. It also avoids those difficult debugging sessions, where you’ve missed a possible path through the if statement. Keep it simple!

9 - False-Happy Methods

Being exception-happy is far more advantageous than being false-happy.

Ruby or Python developers are used to watching for trivial exceptions. While that sound tedious, it’s actually quite a good thing. If anything goes wrong, an exception is thrown, and you instantly know where the problem is.

In PHP – and especially when using older frameworks, such as CodeIgniter – you get what I refer to as “false-happy code” (as opposed to exception-happy). Instead of having an exception get all up in your face, it just returns a falsevalue and assigns the error string to some other property. This forces you to fish it out of the class using a get_error(); method.

Being exception-happy is far more advantageous than being false-happy. If an error occurs within your code (eg: could not connect to S3 to upload an image, or a value is empty, etc.), then throw an exception. You can also throw specific types of exceptions by extending the Exception class, like so:

class CustomException extends Exception {}

Throwing a custom exception makes debugging considerably easier.

Tip 10 - Use Guard Clauses

It’s common to use if statements to control a function or method’s execution path. It’s tempting to test a condition and execute a lot of code when the condition results in true, only to simply return in the else statement. For example:

function someFunction($param) {
    if ($param == 'OK') {
       $this->doSomething();
       return true;
    } else {
       return false;
    }
}

This kind of solution, however, represents a potential for spaghetti code. You can make this code easier to read by reversing the condition. Here’s the better version:

function someFunction($param) {
    if ($param != 'OK') return false;
    $this->doSomething();
    return true;
}

Isn’t that easier to read? It’s a simple change that makes a drastic difference in the readability of your code.

Tip 11 – Use while for Simple Iterations

The for loop is commonly used when you need, for example, a counter. Here’s a simple for loop:

for (var i = 0; i < x; i++) {
    ...
}

There are some very good reasons to use a for loop, but a while loop may be better if you just need something simple, like this:

var i = x;
while (i--) {
    ...
}

It doesn’t work in every situation, but it is an alternative.

Tip 12 – Keep Methods Maintainable

This is easily one of the most frequent mistakes made by newcomers.

A method is an object’s unit of work, and limiting your methods to a maintainable size makes your code easier to read and maintain. Take a look at the following monster method:

class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this->goAndDressUp();
			$this->washYourTeeth();
			$this->cleanYourWeapon();
			$this->takeYourHelmet();
			if($this->helmetDoesNotFit())
				$this->takeAHat();
			else
				$this->installHelmet();
			$this->chekcYourKnife();
			if($this->myAirplain() == "F22")
				$this->goToArmyAirport();
			else
				$this->goToCivilianAirport();
			$this->aim();
			$this->prepare();
			$this->fire();
		}
	}
}

Consider breaking this monster method into smaller, descriptive chunks, each being responsible for performing one well-abstracted action. This is easily one of the most frequent mistakes made by newcomers.

class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this->prepareYourself();
			$this->tryHelmet();
			$this->findYourAirport();
			$this->fightEnemy();
		}
	}
	private function prepareYourself() {
		$this->goAndDressUp();
		$this->washYourTeeth();
		$this->cleanYourWeapon();
		$this->chekcYourKnife();
	}
	private function tryHelmet() {
		$this->takeYourHelmet();
		if($this->helmetDoesNotFit())
			$this->takeAHat();
		else
			$this->installHelmet();
	}
	private function findYourAirport() {
		if($this->myAirplain() == "F22")
			$this->goToArmyAirport();
		else
			$this->goToCivilianAirport();
	}
	private function fightEnemy() {
		$this->aim();
		$this->prepare();
		$this->fire();
	}
}

There we go: cleaner, and easier to debug!

Step 13 - Avoid Deep Nesting

Too many levels of nesting makes code difficult to read and maintain. Consider the following:

function doSomething() {
    if ($someCondition) {
        if ($someOtherCondition) {
            if ($yetSomeOtherCondition) {
                doSomethingSpecial();
            }
            doSomethingElse();
        }
    }
}

You can refer to Tip #10 to make this code easier to read by reversing some of the conditions.

function doSomething() {
    if (!$someCondition) {
        return false;
    }
    if (!$someOtherCondition) {
        return false;
    }
    if ($yetSomeOtherCondition) {
        doSomethingSpecial();
    }
    doSomethingElse();
}

This code is considerably cleaner and produces the same results as before.

When you find yourself with nested if statements, closely examine your code; your method may be performing more than one task. Here’s an example:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		if($anotherThing)
			$this->doSomethingElse();
	}
}

In these cases, extract the nested methods into their own method:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		$this->doAnotherThing($anotherThing);
	}
}
private doAnotherThing($anotherThing) {
	if($anotherThing)
		$this->doSomethingElse();
}

Tip 14 – Avoid Magic Numbers and Strings

Magic numbers and strings are evil. Define variables or constants with the values you want to use in your code.

Instead of this:

function someFunct() {
	$this->order->set(23);
	$this->order->addProduct('superComputer');
	$this->shoppingList->add('superComputer');
}

Specify what those numbers and strings mean, and assign them to a variable with a meaningful name, like this:

function someFunct() {
	$orderId = 23;
	$selectedProductName = 'superComputer';
	$this->order->set($orderId);
	$this->order->addProduct($selectedProductName);
	$this->shoppingList->add($selectedProductName);
}

While some might argue that we’re needlessly creating variables, the performance hit is negligible. Readability always takes priority. Remember: don’t optimize for performance until you can describe why it’s necessary.

Step 15 - Use Built-In Array Functions

Use the built-in array functions instead of foreach().

Not Ideal:

foreach (&$myArray as $key =>$element) {
   if ($element > 5) unset ($myArray[$key]);
}

Better:

$myArray = array_filter($myArray, function ($element) { return $element <= 5;});

PHP offers a variety of array methods. They’re confusing at first, but take a day and try to learn as many as possible.

Tip 16 - Don’t Overuse Variables

It’s easy to overuse variables, but remember that variables are stored in memory. For every variable you create, the system needs to allocate memory for that variable. Look at this code:

public function get_posts() {
	$query = $this->db->get('posts');
	$result = $query->result();
	return $result;
}

The $result variable isn’t necessary. The following code omits that variable:

public function get_posts() {
	$query = $this->db->get('posts');
	return $query->result();
}

The difference is subtle, but we were able to improve this simple example. We kept the $query variable because it relates to the database, while $resultrelated more to our logic.


General Programming Recommendations

Tip 17 - Rely on the Database Engine

Anything less is a code smell.

A database is designed for working with data; use its tools and abilities to make your application more efficient.

For example, you can avoid redundant database queries in many circumstances. Most plug-and-play user management scripts use two queries for user registration: one to check whether the e-mail/username already exists and another to actually add it to the database. A much better approach is to set the username field to UNIQUE. You can then use native MySQL functions to check whether or not the record was added to the database.

Tip 18: Properly Name Your Variables

The days of naming your variables xyz are over (unless, of course, you’re dealing with a coordinate system). A variable represents an important part of your logic. Don’t want to type a long name? Get a better IDE. Modern IDEs auto-complete variable names in a blink of an eye.

Always be coding for six months from now. Are you certain that you’ll remember what that $sut variables refers to a year from now? Likely not: be descriptive. Anything less is a code smell.

Tip 19 - Methods Represent Actions

Mistakes happen; the key is to learn from them.

Name your methods with verbs representing the action they perform. The main concept is the exact opposite of the variable naming scheme. Use a short, but descriptive, name in a large scope (ie: public methods), and use a longer and more detailed name in a short scope (ie: private / protected methods). This helps make your code read like well written prose.

Also avoid any language other than English, when naming your methods. It’s annoying to read function names like 做些什麼() or делатьчтото() in your project. It may be impossible for other programmers to understand your intent. While it might seem arrogant, for better or worse, English is the adopted language of code. Try to use it, if we’re working on a large team.

Tip 20: Structure Recommendations

Finally, code structure is just as important to readability and maintainability as anything else we’ve talked about today. Here are two recommendations:

  • Indent with four or two space-width tabs. Anything more, such as eight spaces, is too much and will make your code difficult to read.
  • Set a reasonable line-width and respect it. Forty characters in a line? We’re not in the ’70s any more; set your limit to 120 characters, put a mark on the screen, and force yourself or your IDE to respect that limit. 120 characters gives you a nice width without making you scroll.

Conclusion

“I’ve never made a stupid programming mistake.” — No one, ever.

Mistakes happen; the key is to learn from them. We at Nettuts+ have made, and will continue to make, mistakes. Our hope is that you learn from our mistakes so that you can avoid them in the future. But, to be honest, the best way to learn best practices is to make the mistakes yourself!

Thanks for reading!

Getting started with PHP PDO and SQLITE

Posted: August 23, 2012 by abhijeetgk in PHP, SQLITE
Tags: , , ,

In android i used to have sqlite db which is light weight and sufficiently smart for smaller operations

PHP too supports the SQLITE db operations so i searched for some time and found certain code to make use of the SQLITE in php

 

First thing i tried to create the db file, on php.net site I got following code snippet

<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) { 
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result)); 
} else {
    die($sqliteerror);
}
?>

After I executed the code with sample values and some data, when i checked in SQLite db browser, it gave me version issue then i came across fact that This function only support database of SQLite 2 or below. For SQLite 3, you must use PDO.

So i started searching on SQLite with PDO

Finally some sort of working code I got which can create the db file execute some statements and finally that can be browsed via the sqlite browser below is the code with comments in between.. so

Enjoy

In following code explanation given for how to create sqlite db, create some tables, insert data, drop table, access the data.. and so on

The inline commenting is good enough to understand the code, so not writing here in much detail…

 

<?php
 try {
 // Create (connect to) SQLite database in file
 $file_db = new PDO('sqlite:users.sqlite3');
 // Set errormode to exceptions
 $file_db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 /**************************************
 * Create tables *
 **************************************/
 // Create table users with two colums firstname and last name
 $file_db->exec("CREATE TABLE IF NOT EXISTS tbl_users (
 id INTEGER PRIMARY KEY, 
 firstname TEXT, 
 lastname TEXT 
 )");
 
 /**************************************
 * Set initial data *
 **************************************/
 // Array with some test data to insert to database 
 $users = array(
 array('firstname' => 'Abhijeet',
 'lastname' => 'K'),
 array('firstname' => 'Testing firstname',
 'lastname' => 'Testing lastname'),
 array('firstname' => 'Dinesh',
 'lastname' => 'Patil')
 );
 // Prepare INSERT statement to SQLite3 file db
 $insert = "INSERT INTO tbl_users (firstname, lastname) 
 VALUES (:firstname, :lastname)";
 $stmt = $file_db->prepare($insert);
 
 // Bind parameters to statement variables
 $stmt->bindParam(':firstname', $firstname);
 $stmt->bindParam(':lastname', $lastname);
 
 
 // Loop thru all users data and execute prepared insert statement
 foreach ($users as $u) {
 // Set values to bound variables
 $firstname = $u['firstname'];
 $lastname = $u['lastname'];
 // Execute statement
 $stmt->execute();
 }
 
 // Select all data from users tabel and display 
 $result = $file_db->query('SELECT * FROM tbl_users');
 
 foreach($result as $row) {
 echo "Firstname: " . $row['firstname'] . "&nbsp;";
 echo "Lastname: " . $row['lastname'] . "<br>";
 
 echo "<br>";
 }
 
 
 /**************************************
 * Drop tables *
 **************************************/
 
 // Drop table users from file db
 $file_db->exec("DROP TABLE tbl_users");
 // Close file db connection
 $file_db = null;
 
 }
 catch(PDOException $e) {
 // Print PDOException message
 echo $e->getMessage();
 }
?>

In this series so far I explained to set up basic PHP application and use of RDS for relational databases.

For the same couple of times we faced the issue that somehow the instance health check url returned false and as a result our instance got terminated, so we need to again re upload the entire data associate elastic ip etc that is somewhat hectic process

So we googled for the solution and came to know that if instance got restarted the local file system will be lost and you cant retain the data, the solution is to use the persistent storage so even in case of failure the data should remain.

Couple of options are available, some suggested to use bucket and some advised to use the EBS volumes.

I followed the EBS volumes

An informative guide can be found HERE 

Actually its pretty straight forward if you have some advanced linux knowledge for filesystems.

First i created the empty EBS volume, make sure for the availability zone as one volume may not available to other zones.

Ater that you need to associate the volume to your instance use between the range sdc to sdp as sda and sdb are already in use

After assigning to specific instance you can ssh to your instance and see its attached.

Before mounting for first time you need to format the ebs volume by following command

sudo mkfs.xfs /dev/sdc

Where “sdc” is the point of attachment at the time of attaching to instance

After create an empty directory to mount volume with  mkdir command

And final step is to actually mount it

mount /dev/xvdp /wb1

wb1 is the directory created to mount the drive

 


									

The most important thing is you need your valid amazon login details

Login with the credentials and you will land on the home screen, dont get confused with various options to setup working php mysql application you need a few options.

The first most important thing is to generate a ssh key and import in the console A good guide on how to generate can be found HERE

Once imported name the key you can remember say php or mykey etc I use php.

Next you can go to Elastic Beanstalk section, select launch new environment.

Choose the required parameters the most important is container type

Select the one which suits you for your php mysql I selected 32 bit amazon linux running php 5.3

Check the parameters for most of columns dont change any but to keep the default one

After filling all the details your environment is can be seen on the same screen, wait for the color or environment to change to green which indicates ALL IS WELL…

You are now almost 50% done till this step.

Go to environment url to check the sample code working, some welcome app or sample application screen

If not then there is something wrong and you can check the environment logs or events to check status.

Next go to EC2 section and your newly created instance is waiting for you.

Its now time to access the newly created instance to upload some files.

Allocate one Elastic Ip from the EC2->Elastic IP section to your instance.

In the instance details you can now see the IP allocated. Just to confirm type that IP address in browser and you should see the same app page that was there while checking the environment url.

Next step is set up putty to access the instance.

Convert the generated key in first step to PPK (Putty Private Key) format. An illustrative guide can be found HERE.

For a Quick revision we followed steps as

  1. Generated key pair
  2. Created instance with default environment
  3.  Imported keys to ec2  environment
  4.  Edited instance to allocate the IP to allow SSH
Next step is to actually ssh your newly created instanceGo to instance section under EC2->instances and click on your instance and note down the elastic IP associated.
Now Open the Puty for SSH connection
In connection details put your elastic IP and under SSH -> Auth section browse the ppk file you created.
When prompted enter user name as ec2-user and password as what you selected while creating your key.

Bingo…….

If  ALL IS WELL you can see the favorite black screen for linux console.. Its now your play ground.. and now time to do some settings.
Check for php version and apache version for curiosity, Its not necessary but to start with or to brush your knowledge if you are accessing it after long time like me.
The default apache location is /etc/httpd/
and default webroot will be /var/www/html
Edit some files or create a new one..using VI editor and check on front end..

Database Access Wrapper In Java

Posted: July 1, 2012 by abhijeetgk in JAVA

Recently started doing some homework for java, I started with few simple concepts like JSP and servlets,

Having experience in PHP the web concepts are clear. Now its time to check whether the same concepts can work in JSP and Servlets or not

I started with simple JSP and Servlet Application for a common functionality forums.

(Github repo is created will commit on regular basis as i move ahead )

I first decided to do one db access class, that will hold the connection and some common functions so each time i dont need to write those repeat lines for open connection and close.

I did some R n D and come up with the following file

DBAccess.java

And sample implementation can be found here

CommonFunctions.java

 

I know I am somewhat fresher to this concept but trying to improve my knowledge in the concepts.

 

If you have any better ideas then please do share with me by putting comments or by dropping the email at abhijeetgk@gmail.com

 

This is new series where in I will explain step by step configuration of the amazon cloud servers to host and run php mysql applications

 

In this session I will first explain to use ARDS (Amazon Relational Database Service) and then binding the ARDS instance to get accessible from your app.

 

The main requirement is you should have AWS account.  Login with your credentials and go ahead to create your first ARDS db

First select RDS tab from the top menu

Then select launch new instance

Select available instances like mysql,oracle,MSSQL etc

Fill in the necessary details like instance class, storage, db identifier, username, password etc

 

 

Once selected all the necessary options the DB instance is now seen on RDS dashboard.

Next Step is to authorize access to your database

Select the db security group from the left hand side options

Possible select the default security group and grant access for application or the specific IP to access the same.

After authorized access you can now access your database

Note the EndPoint url username and password

With this credentials and security settings you can now connect to your db instance.

Fancy Gradient Buttons for Android

Posted: June 19, 2012 by abhijeetgk in ANDROID, Technology
Tags: ,

Design elements for android is some what complex task in the beginning, but as you explore the internet you will find
Default buttons for android code not so cool so I decided to use the image button instead of regular buttons, then too for some low end devices that is not looking good

After searching for internet I got concept to use the Stylesheet properties for buttons HERE

Its pretty simple and straight forward

First you need to define the xml for color gradient effect. I choose Red color first

File 1 res/drawable/btn_red.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#ef4444" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#ef4444"
                android:endColor="#992f2f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

After this file you need to define the style resources for button text

Include following style tag in res/values/strings.xml

<style name="ButtonText">
 <item name="android:layout_width">fill_parent</item>
 <item name="android:layout_height">wrap_content</item>
 <item name="android:textColor">#ffffff</item>
 <item name="android:gravity">center</item>
 <item name="android:layout_margin">3dp</item>
 <item name="android:textSize">30dp</item>
 <item name="android:textStyle">bold</item>
 <item name="android:shadowColor">#000000</item>
 <item name="android:shadowDx">1</item>
 <item name="android:shadowDy">1</item>
 <item name="android:shadowRadius">2</item>
</style>

Finally Include the button code where you want the fancy gradient button to appear as follows

<Button
 android:id="@+id/button1"
 style="@style/ButtonText"
 android:layout_width="match_parent"
 android:background="@drawable/btn_red"
 android:text="RedButton" >
</Button>

Note the background attribute and style attribute .

To have php run on GAE you need Quercus, though the name appears some difficult the process is much simple than expected, you just need to add few jar files change some settings and thats it..you will have your php code running on google app engine

The biggest problem during the whole process is to get the exact jar files

Google helped me find a SVN repo out there that had the 3 jars I needed, and  after loading them into the correct folder. Eclipse stopped throwing errors.  If you’re looking for the files I used, you can find them here:http://lportal.svn.sourceforge.net/viewvc/lportal/portal/trunk/lib/development/.  I determined that quercus.jar, resin_util.jar, and script-10.jar were needed for Quercus to do its thing correctly… at least that’s what I think.  Drop them in the WEB_INF/lib folder and you should be all set.

Now the actual process starts.

Step -1 Edit Web.xml file to have following lines of code

<servlet>
<servlet-name>Quercus Servlet</servlet-name>
<servlet-class>com.caucho.quercus.servlet.QuercusServlet</servlet-class>
<init-param>
<param-name>ini-file</param-name>
<param-value>WEB-INF/php.ini</param-value>
</init-param>
</servlet>

and

<servlet-mapping>
<servlet-name>Quercus Servlet</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>

I don’t know if any order is important here, but I put the php servlet first, followed by the default servlet, followed by the php servlet-mapping, followed by the default servlet-mapping.

Next on the list is appengine-web.xml. Add the following code right after closing of system-properties tag

<static-files>
<exclude path="/*.php" />
</static-files>
<resource-files>
<include path="/**.php" />
</resource-files>

Next to create one php.ini file in war/WEB-INF folder. Currently i kept it blank.

Now the final step is to create some php files to check. I created simple file that echo phpinfo to check php running fine at location war/index.php

Initially when I tested this out I was getting a strange error about org.mortbay.util.ajax.Continuation not found.  I don’t know what that is, but its included in the jetty-util-6.1.0.jar file, which I found here.  I’m unsure if this is specific to the development platform or required by Quercus

Now that’s it  I included that jar and my php started working on local instance of GAE application

I deployed on app engine, and there too it started smoothly.

Live Example

Github Hosted Project

Couple of days I am searching for the solution to get the local instance of google app engine to my android app on emulator. This is required as every time you cant deploy the GAE app version to check as its time consuming and not advisable.

To set up this its assumed that you have setup google app engine local instance and your android application

If you are trying, from your Android application through the Android emulator, to access an external service on the same computer (such as your own Google App Engine site) by using the host name localhost or the IP-address 127.0.0.1, you might get a java.net.ConnectException: localhost/127.0.0.1:8888 – Connection refused error – even though you can perfectly well access the service outside the Android application.

 

The reason why a ConnectException occurs is because localhost or 127.0.0.1 inside the Android emulator is the emulator’s own loopback interface, meaning all request sent to the destination will be looped backed to the emulator and won’t actually be sent to your local machine.
To by pass this, simply replace localhost with the IP-address 10.0.2.2as this is a special address towards the real local host.
thats it  and you can now access the your local GAE instance with Android app.