March 12, 2015

Build CRUD Application Demo in Yii Framework - Start Yii Step by Step

Posted by Unknown
3

Install Yii Framework in Ubuntu

Install with composer

Install PHP, MySQL, Apache2

$ sudo apt-get update
$ sudo apt-get apache2
$ sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
$ sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql

Install Yii

$ curl -s http://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
$ composer global require "fxp/composer-asset-plugin:1.0.0"
$ cd /path/to/webroot/
$ composer create-project --prefer-dist yiisoft/yii2-app-basic basic

Test installation

$ sudo service apache2 restart
Access to : http://localhost/basic/web/index.php

Screenshot

Other install

Refer to : http://www.yiiframework.com/doc-2.0/guide-start-installation.html

Database setup

Create database

$ mysql -u root -p
mysql > create database yii2basic;
mysql > use yii2basic;
CREATE TABLE `country` (
  `code` CHAR(2) NOT NULL PRIMARY KEY,
  `name` CHAR(52) NOT NULL,
  `population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `country` VALUES ('AU','Australia',18886000);
INSERT INTO `country` VALUES ('BR','Brazil',170115000);
INSERT INTO `country` VALUES ('CA','Canada',1147000);
INSERT INTO `country` VALUES ('CN','China',1277558000);
INSERT INTO `country` VALUES ('DE','Germany',82164700);
INSERT INTO `country` VALUES ('FR','France',59225700);
INSERT INTO `country` VALUES ('GB','United Kingdom',59623400);
INSERT INTO `country` VALUES ('IN','India',1013662000);
INSERT INTO `country` VALUES ('RU','Russia',146934000);
INSERT INTO `country` VALUES ('US','United States',278357000);

Config

Open basic/config/db.php

<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2basic',
    'username' => 'username',
    'password' => 'your_password',
    'charset' => 'utf8',
];

Test database setup

Create basic/models/Country.php
<?php

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord
{
}
 
Create basic/controllers/CountryController.php

<?php

namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
    public function actionIndex()
    {
        $query = Country::find();
        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);
        $countries = $query->orderBy('name')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        return $this->render('index', [
            'countries' => $countries,
            'pagination' => $pagination,
        ]);
    }
}
 
Create view file

<?php
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1 >Countries</h1 >
<ul >
<?php foreach ($countries as $country): ?>
    <li >
        <?= Html::encode("{$country->name} ({$country->code})") ?>:
        <?= $country->population ?>
    </li >
<?php endforeach; ?>
</ul >
<?= LinkPager::widget(['pagination' => $pagination]) ?>

Access to : http://localhost/basic/web/index.php?r=country/index

Create simple CRUD demo

Yii framework provides Gii module to allow programmers to create one code base quickly and easily. Gii allows for Models, Controllers, Modules, the extensions and CRUD with a few simple operations.

Check Gii installed Access: http://localhost/basic/web/index.php?r=gii

Screenshot

Create CRUD using Gii

Gii code generated automatically by the user www-data by default, so it is necessary to assign the right permission( write and read) to basic directory for this user. 

To be able to CRUD genetic code automatically, to create a table for the entity you want to create. 

In this example, the country table created earlier. The properties in the table will be automatically gen in the sample code. Table should have a primary key.

Screenshots

After you click the Preview button, will see the message files will be created if click the Generate button. 

If there are files that were created before it can notify you overwrote or not, click the button diff will see the difference of the original file with the file will be created. 

Click the Generate button will automatically execute. 

Finish.

Screenshots

References: http://www.yiiframework.com/doc-2.0/guide-index.html


March 11, 2015

Build CRUD App Demo in Zend Framework 2 - Create Read Update Show and Delete Album in Zend 2

Posted by Unknown
0

Install PHP, MySQL, Apache2

$ sudo apt-get update
$ sudo apt-get apache2
$ sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
$ sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
$ curl -s https://getcomposer.org/installer | php --
May be, install curl if dont have on your systems.

Clone ZendSkeletonApplication and install

$ cd
$ mkdir Workspace
$ cd Workspace
$ git clone git://github.com/zendframework/ZendSkeletonApplication.git
$ cd ZendSkeletonApplication
$ php composer.phar self-update
$ php composer.phar install

Web server setup (use PHP CLI for development env)

$ cd ZendSkeletonApplication
$ php -s 0.0.0.0:8080 -t public/ public/index.php

Then, open web browser and point to : http://localhost:8080

Create new module (Album module)

Create the directory structure for the album is as follows:

<?php
 
namespace Album;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
             //   __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

Create ZendSkeletonApplication/module/Album/config/module.config.php

<?php
return array(
    'controllers' => array(
        'invokables' => array(
            'Album\Controller\Album' => 'Album\Controller\AlbumController',
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);

Tell ZendSkeletonApplication that use modules Album Open ZendSkeletonApplication / config / application.config.php and add the line:

<?php
return array(
    'modules' => array(
        'Application',
        'Album',                  // <-- data-blogger-escaped-add="" data-blogger-escaped-line="" data-blogger-escaped-module_listener_options="" data-blogger-escaped-this=""> array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Create routes for controller and script views

Add following line to module.config.php

# ZendSkeletonApplication/module/Album/config/module.config.php

     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),

The code above will take on the module Album app with the default index.php page

Create controller

Create AlbumController.php in module/Album/src/Album/Controller/

<?php
 
namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
    public function indexAction()
    {
    }

    public function addAction()
    {
    }

    public function editAction()
    {
    }

    public function deleteAction()
    {
    }
}

Create views script for AlbumController

module/Album/view/album/album/index.phtml 
module/Album/view/album/album/add.phtml 
module/Album/view/album/album/edit.phtml 
module/Album/view/album/album/delete.phtml 

Test module setup

http://localhost:8080/album  => index page
http://localhost:8080/album/add  => add album page
http://localhost:8080/album/edit  => edit album page
http://localhost:8080/album/delete  => delete album page

Screenshots

Database setup

Create database (demo: zf2tutorial)

$ mysql -u root -p
mysql > create database zf2tutorial;
mysql > use zf2tutorial;
 CREATE TABLE album (
   id int(11) NOT NULL auto_increment,
   artist varchar(100) NOT NULL,
   title varchar(100) NOT NULL,
   PRIMARY KEY (id)
 );
 INSERT INTO album (artist, title)
     VALUES  ('The  Military  Wives',  'In  My  Dreams');
 INSERT INTO album (artist, title)
     VALUES  ('Adele',  '21');
 INSERT INTO album (artist, title)
     VALUES  ('Bruce  Springsteen',  'Wrecking Ball (Deluxe)');
 INSERT INTO album (artist, title)
     VALUES  ('Lana  Del  Rey',  'Born  To  Die');
 INSERT INTO album (artist, title)
     VALUES  ('Gotye',  'Making  Mirrors');

Create model files

Create model files in module/Album/src/Album/Model/

Create Album.php
<?php

namespace Album\Model;

 class Album
 {
     public $id;
     public $artist;
     public $title;

     public function exchangeArray($data)
     {
         $this->id     = (!empty($data['id'])) ? $data['id'] : null;
         $this->artist = (!empty($data['artist'])) ? $data['artist'] : null;
         $this->title  = (!empty($data['title'])) ? $data['title'] : null;
     }
 }

Create AlbumTable.php

<?php
namespace Album\Model;

use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function getAlbum($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveAlbum(Album $album)
    {
        $data = array(
            'artist' => $album->artist,
            'title'  => $album->title,
        );

        $id = (int) $album->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getAlbum($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Album id does not exist');
            }
        }
    }

    public function deleteAlbum($id)
    {
        $this->tableGateway->delete(array('id' => (int) $id));
    }
}

Using ServiceManager to configure the table gateway and inject into album table

<?php
namespace Album;

// Add these import statements:
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class Module
{
    // getAutoloaderConfig() and getConfig() methods here

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Album\Model\AlbumTable' =>  function($sm) {
                    $tableGateway = $sm->get('AlbumTableGateway');
                    $table = new AlbumTable($tableGateway);
                    return $table;
                },
                'AlbumTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Album());
                    return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }
}

Config for connect to database

Open ZendSkeletonApplication/config/autoload/global.php and edit:
 return array(
     'db' => array(
         'driver'         => 'Pdo',
         'dsn'            => 'mysql:dbname=zf2tutorial;host=localhost',
         'driver_options' => array(
             PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
         ),
     ),
     'service_manager' => array(
         'factories' => array(
             'Zend\Db\Adapter\Adapter'
                     => 'Zend\Db\Adapter\AdapterServiceFactory',
         ),
     ),
 );

Then, Create ZendSkeletonApplication/config/autoload/local.php and add:

<?php

return array(
    'db' => array(
        'username' => 'YOUR USERNAME HERE',
        'password' => 'YOUR PASSWORD HERE',
    ),
);

Open AlbumController.php and add getAlbumTable() function

 // module/Album/src/Album/Controller/AlbumController.php:
     public function getAlbumTable()
     {
         if (!$this->albumTable) {
             $sm = $this->getServiceLocator();
             $this->albumTable = $sm->get('Album\Model\AlbumTable');
         }
         return $this->albumTable;
     }

Edit indexAction() in AlbumController.php for listing all albums in database

 // module/Album/src/Album/Controller/AlbumController.php:
 // ...
     public function indexAction()
     {
         return new ViewModel(array(
             'albums' => $this->getAlbumTable()->fetchAll(),
         ));
     }
 // ...

Finally, show ra all album: index.phtml in view

<?php

 // module/Album/view/album/album/index.phtml:

 $title = 'My albums';
 $this->headTitle($title);
 ?>
 <h1><?php echo $this->escapeHtml($title); ?></h1>
 <p>
     <a href="<?php echo $this->url('album', array('action'=>'add'));?>">Add new album</a>
 </p>

 <table class="table">
 <tr>
     <th>Title</th>
     <th>Artist</th>
     <th>&nbsp;</th>
 </tr>
 <?php foreach ($albums as $album) : ?>
 <tr>
     <td><?php echo $this->escapeHtml($album->title);?></td>
     <td><?php echo $this->escapeHtml($album->artist);?></td>
     <td>
         <a href="<?php echo $this->url('album',
             array('action'=>'edit', 'id' => $album->id));?>">Edit</a>
         <a href="<?php echo $this->url('album',
             array('action'=>'delete', 'id' => $album->id));?>">Delete</a>
     </td>
 </tr>
 <?php endforeach; ?>
 </table>

Screenshots

CRUD for Album module

Show an album

Add viewAction($id) to AlbumController.php
<?php

// Some code , ex: namespace . .. 
class AlbumController extends AbstractActionController
{
 //  ...
 protected $id;
 // …
     public function viewAction($id)
     {
        $id = (int) $this->params()->fromRoute('id', 0);
        return array(
          'id'    => $id,
          'album' => $this->getAlbumTable()->getAlbum($id)
        );
     }
} 

Create module/Album/view/album/album/view.phtml

Then, access to: http://localhost:8080/album/view/1

Create new album

Create a file called AlbumForm.php in module/Album/src/Album/Form:
<?php

namespace Album\Form;

 use Zend\Form\Form;

 class AlbumForm extends Form
 {
     public function __construct($name = null)
     {
         // we want to ignore the name passed
         parent::__construct('album');

         $this->add(array(
             'name' => 'id',
             'type' => 'Hidden',
         ));
         $this->add(array(
             'name' => 'title',
             'type' => 'Text',
             'options' => array(
                 'label' => 'Title',
             ),
         ));
         $this->add(array(
             'name' => 'artist',
             'type' => 'Text',
             'options' => array(
                 'label' => 'Artist',
             ),
         ));
         $this->add(array(
             'name' => 'submit',
             'type' => 'Submit',
             'attributes' => array(
                 'value' => 'Go',
                 'id' => 'submitbutton',
             ),
         ));
     }
 }
Open Album.php file in module/Album/src/Album/Model:
<?php

namespace Album\Model;

 // Add these import statements
 use Zend\InputFilter\InputFilter;
 use Zend\InputFilter\InputFilterAwareInterface;
 use Zend\InputFilter\InputFilterInterface;

 class Album implements InputFilterAwareInterface
 {
     public $id;
     public $artist;
     public $title;
     protected $inputFilter;                       // <-- data-blogger-escaped-add="" data-blogger-escaped-data="" data-blogger-escaped-exchangearray="" data-blogger-escaped-function="" data-blogger-escaped-public="" data-blogger-escaped-this-="" data-blogger-escaped-this="" data-blogger-escaped-variable="">id     = (isset($data['id']))     ? $data['id']     : null;
         $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
         $this->title  = (isset($data['title']))  ? $data['title']  : null;
     }

     // Add content to these methods:
     public function setInputFilter(InputFilterInterface $inputFilter)
     {
         throw new \Exception("Not used");
     }

     public function getInputFilter()
     {
         if (!$this->inputFilter) {
             $inputFilter = new InputFilter();

             $inputFilter->add(array(
                 'name'     => 'id',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'Int'),
                 ),
             ));

             $inputFilter->add(array(
                 'name'     => 'artist',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'StripTags'),
                     array('name' => 'StringTrim'),
                 ),
                 'validators' => array(
                     array(
                         'name'    => 'StringLength',
                         'options' => array(
                             'encoding' => 'UTF-8',
                             'min'      => 1,
                             'max'      => 100,
                         ),
                     ),
                 ),
             ));

             $inputFilter->add(array(
                 'name'     => 'title',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'StripTags'),
                     array('name' => 'StringTrim'),
                 ),
                 'validators' => array(
                     array(
                         'name'    => 'StringLength',
                         'options' => array(
                             'encoding' => 'UTF-8',
                             'min'      => 1,
                             'max'      => 100,
                         ),
                     ),
                 ),
             ));

             $this->inputFilter = $inputFilter;
         }

         return $this->inputFilter;
     }
 }
Open AlbumController.php and add:
 // module/Album/src/Album/Controller/AlbumController.php:

 //...
 use Zend\Mvc\Controller\AbstractActionController;
 use Zend\View\Model\ViewModel;
 use Album\Model\Album;          // <-- data-blogger-escaped-add="" data-blogger-escaped-addaction="" data-blogger-escaped-album="" data-blogger-escaped-albumform="" data-blogger-escaped-content="" data-blogger-escaped-form-="" data-blogger-escaped-form="new" data-blogger-escaped-function="" data-blogger-escaped-import="" data-blogger-escaped-lbumform="" data-blogger-escaped-method:="" data-blogger-escaped-orm="" data-blogger-escaped-public="" data-blogger-escaped-this="" data-blogger-escaped-to="" data-blogger-escaped-use="">get('submit')->setValue('Add');

         $request = $this->getRequest();
         if ($request->isPost()) {
             $album = new Album();
             $form->setInputFilter($album->getInputFilter());
             $form->setData($request->getPost());

             if ($form->isValid()) {
                 $album->exchangeArray($form->getData());
                 $this->getAlbumTable()->saveAlbum($album);

                 // Redirect to list of albums
                 return $this->redirect()->toRoute('album');
             }
         }
         return array('form' => $form);
     }
Open add.phtml view script and edit:
 <?php
 // module/Album/view/album/album/add.phtml:

 $title = 'Add new album';
 $this->headTitle($title);
 ?>
 <h1><?php echo $this->escapeHtml($title); ?></h1>
 <?php
 $form->setAttribute('action', $this->url('album', array('action' => 'add')));
 $form->prepare();

 echo $this->form()->openTag($form);
 echo $this->formHidden($form->get('id'));
 echo $this->formRow($form->get('title'));
 echo $this->formRow($form->get('artist'));
 echo $this->formSubmit($form->get('submit'));
 echo $this->form()->closeTag();

More method edit, delete chi tiết xem tại : http://framework.zend.com

Screenshots


Zend Framework 2 - Install and Create New Module Zend 2 on Ubuntu

Posted by Unknown
0

Install PHP, MySQL, Apache2

$ sudo apt-get update
$ sudo apt-get apache2
$ sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
$ sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
$ curl -s https://getcomposer.org/installer | php --
May be, install curl if dont have on your systems.

Clone ZendSkeletonApplication and install

$ cd
$ mkdir Workspace
$ cd Workspace
$ git clone git://github.com/zendframework/ZendSkeletonApplication.git
$ cd ZendSkeletonApplication
$ php composer.phar self-update
$ php composer.phar install

Web server setup (use PHP CLI for development env)

$ cd ZendSkeletonApplication
$ php -s 0.0.0.0:8080 -t public/ public/index.php

Then, open web browser and point to : http://localhost:8080

Create new module (Album module)

Create the directory structure for the album is as follows:

<?php
 
namespace Album;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
             //   __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

Create ZendSkeletonApplication/module/Album/config/module.config.php

<?php
return array(
    'controllers' => array(
        'invokables' => array(
            'Album\Controller\Album' => 'Album\Controller\AlbumController',
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);

Tell ZendSkeletonApplication that use modules Album Open ZendSkeletonApplication / config / application.config.php and add the line:

<?php
return array(
    'modules' => array(
        'Application',
        'Album',                  // <-- data-blogger-escaped-add="" data-blogger-escaped-line="" data-blogger-escaped-module_listener_options="" data-blogger-escaped-this=""> array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Create routes for controller and script views

Add following line to module.config.php

# ZendSkeletonApplication/module/Album/config/module.config.php

     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),

The code above will take on the module Album app with the default index.php page

Create controller

Create AlbumController.php in module/Album/src/Album/Controller/

<?php
 
namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
    public function indexAction()
    {
    }

    public function addAction()
    {
    }

    public function editAction()
    {
    }

    public function deleteAction()
    {
    }
}

Create views script for AlbumController

module/Album/view/album/album/index.phtml 
module/Album/view/album/album/add.phtml 
module/Album/view/album/album/edit.phtml 
module/Album/view/album/album/delete.phtml 

Test module setup

http://localhost:8080/album  => index page
http://localhost:8080/album/add  => add album page
http://localhost:8080/album/edit  => edit album page
http://localhost:8080/album/delete  => delete album page

Screenshots


March 08, 2015

Basic Replication in Oracle - Sample Deploy Basic Replication

Posted by Unknown
0

Environments

On master database server

Global db name: orcl.example.com
SID = orcl
IP : 192.168.50.103 (Some IP you want)

On slave server

Global db name: orcl2.example.com
SID = orcl2
IP : 192.168.50.63

See more information: Global db name, SID if you forgot.

start -> run -> regedit -> Software -> Oracle

Folder and dir

  • <Home_database_oracle_dir>/NETWORK/ADMIN
  • listener.ora : This configuration file allows listening to replace certain database in server. Can listen to multiple databases in one summary report. Be construed as headphones Database Server.
  • sqlnet.ora : Contains declarations for the file listener.ora and tnsname.ora
  • tnsname.ora : This file contains declarations for the clients to have access to the database that the server is listening in the declaration in the listener.ora file.

Configuration database on two machines can communicate with each other:

  • On the master: Configure listener.ora file that listens for database orc1.example.com in 1521. default gateway can be configured using graphical tools (Net Configuration Assistants) or by writing directly to the listener.ora file.
  • Here is declared the master machine:

listener.ora

tnsname.ora

The same with slave server

Restart listener

start -> run -> cmd (admin)
> tsnrctl stop
> tsnrctl start

Check the connection between the two databases on master and slave server.

On slave server
start -> cmd (admin)
> tnsping orcl
On master server
> tnsping orcl2

Create user reptest / reptest and assign the necessary permissions on the 2 sides:

On master
On slave
  • Create db links
  • Create obj_1 table and add data to the table on the master machine. (Implementation by reptest users can perform with SQL Development graphical tool or by the following command.)
  • Create snapshot logs (only master server)
  • On slave server, create reptest user
  • Create a link to the master database and checking links.
  • Create snapshots, and perform sync (Snapshot, just perform the slave)

 Value sysdate: the current system date,
 At line 14, as shown above: The system will automatically synchronize the data from the master every 60 seconds (sysdate + 1/1440 = 60s <=> 24/01/60).
 Perform basic test replication, at the slave machine executes the query: SQL> select * from obj_1;
 If the result is successful, as shown below.

Perform check the updates added to the master:


Wait 1 minute, perform queries on the slave, the following results are successful.




March 07, 2015

Basic Replication in Oracle - (Read – only Materialized Views)

Posted by Unknown
0

A. Read – only Materialized Views

I. Overview

  • Clients can query data at the local machine without having to remote machines Master Database. Helps reduce query time and reduce the load for the Master Database server.
  • Clients only read the data on the local machine (Read - only Materialized Views) can not update, delete, ...
  • Only can update, delete, ... data on the master machine with the user account has the ability (eg, SYS, SYSTEM, or the user is granted the right ...).
  • Each table in the computer while updating the Master Database after 1 period (Do configuration), data change will automatically update to the machine Slave (Read - only Materialized Views

  • 1 read - only table snapshot: 1 copy table data from one or more other tables on the remote machine (master machine.), Along with the update logs.
  • Ex: From a table on master:
  • SQL> CREATE SNAPSHOT obj_1 AS  SELECT * FROM obj_1@orc1
    
    SQL> CREATE SNAPSHOT sales.orders AS   SELECT * FROM sales.orders@hq.acme.com o
    WHERE EXISTS
      ( SELECT c_id FROM sales.customers@hq.acme.com c
    WHERE o.c_id = c.c_id AND zip = 19555);
    
  • Snapshot logs: For each replicated table (taken back to the slave) to create one snapshot log (Made by the owner of the table). Snapshot logs table name:
  • table user_snapshot_log
    MLOG$_name_of_table_replicated
    
  • Snapshot Refreshes : Refresh snapshot than master.
  • Snapshot Refreshes Groups : Refresh groups in the Groups table snapshot.
  • Automatic Snapshot Refreshes: Automatically refresh. When you create a snapshot refresh group, the administrator should configure automatic refresh. However, it can refresh manually when necessary.


How To Install and Configure Oracle on Windows - Sign in to your account on local and remote machines

Posted by Unknown
0

Introduction, install, and configure Oracle on Windows.

Introduction to Database Management Oracle

  • Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is a database management object-relational, developed, delivered by Oracle Corporation.
  • Oracle as a database administrator large and widely used worldwide.
  • Oracle database management systems is a major management system, supporting a strong ability to manage data, data distribution over large information systems, decentralization.
  • unsurpassed strength of ORACLE 10g, 11g is the ability to manage data from remote data access, distributed, support for online analytical systems (OLAP).
  • Storage: Oracle stores data logically in tablespaces and files on the hard disk.
  • A DBA can impose quotas on maximum storage per user trong each tablespace.

Installation on Windows

  • Download Oracle Database version in https://oracle.com.
  • Open the folder download, unzip and run setup.exe, such as the first screen, uncheck the box in the 2nd and click Next.
  • At the next screen, click Create and select a configuration database.
  • Next screen, choose Desktop or Server class and then click Next.
  • next screen, choose the folder to install Oracle storage.
  • Name the original database. Name oracle database consists of two parts Database_Name.Domain_Database_Name
  • For example, we set the database name is orcl orcl.example.com the db_domain name is example.com (full name as on the Global Database Name is called - is the single global name defined in the whole database system system.)
  • Set the default password for the user in the system, such as SYS, SYSTEM, ...
  • Can be set for each user on the next pass.
  • next screen shows the options that the user has installed the user to summarize.
  • It is possible to save the file on the drive to forget the room when this information later.
The next screen is the confirmation process and start the installation, the installation can be up to 30 minutes, depending on the configuration of each computer.
The screen below is after successfully installing Oracle. Proceed logged into a database created by the installation Command Line fromt.

The necessary configuration information.

 To view the configuration information for the database is:
 Start -> run -> regedit -> browse to the directory in the Oracle Software and System.
 The directory contains the configuration files needed% Database_home% / NETWORK / ADMIN
 In the folder containing the file on as sqlnet.ora, listener.ora, tnsname.ora
 In addition, we can create the file init <SID_NAME> .ora and init.ora directory for information on configuration necessary.

Create and granted to the user. Sign in to your user account on the local and remote machines.

Create users, asign permission.

$ CREATE USER user_name IDENTIFIED BY password
$ GRANT role1, role 2, ... TO user_name

Access to the database on the local machine

> set orcl_sid = <sid_name>
> sqlplus /nolog
connect|conn username/password
connect|conn username/password@<database>
connect|conn sys as sysdba (connect as sysadmin)

Access database on a remote machine

Configure listener.ora on the server.

Listener role as one of the server headphones, listen to it instead of the database on the server. 1 listener can listen to multiple databases and 1 database can also be heard by many listeners.

  • The <listener_name> is the name you want.
  • For example, on the declaration allows listening orcl1 database (the database on the server orcl1.)

Configure tnsname.ora on the client.

tnsname.ora is one file containing the declaration of a database that allows clients to connect to. the database files in this report should be listening on the server side.

o Note: The host is the hostname or IP top of the database server.
o The <name> is the name of any place, the name used to access the command queries below. VD name is: orcl1
o Global_database_name is the name of the database on the server. As the example above is orcl1.example.com

Restart the listener on the server

Run -> cmd (admin)
> lsnrctl stop
> lsnrctl start
=> Need return success status. otherwise => false.

Test configuration on successful or not in the client.

Run => cmd (admin)
> tnsping orcl1
=> Return OK => success, otherwise => false => reconfigure.

Access to server side from client

Run -> cmd
> sqlplus /nolog
> SQL> conn sys@orcl1 as sysdba
If the error ora-xxx: TNS ... then review tnsname.ora file.

The continue, i will write basic replication.(Read – only Materialized Views)


March 04, 2015

Bootstrap Typeahead on Rails App - Typeahead and Gon

Posted by Unknown
0

Try example at : Demo Typeahead

Add Gemfile

gem 'bootstrap-typeahead-rails', '~> 0.10.5.1'
Run command to install gem
$ bundle install

Add gon Gem

gem 'gon'
$ bundle install

Add following line to application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>TenderMessenger</title>
    <%= include_gon %>
      ...other scripts, etc.
  </head>

Add Gon to your controllers. The idea is to assign your Rails variable to a Gon variable (which will become a JavaScript variable). In my case, trying to pass users’ names and images, it looked like this:

def index
  gon.usernames = User.pluck(:name)
  gon.gravatars = User.all.map { |user| user.gravatar }
  # ...other code that belongs in the controller action
end

You can assign any array to the Gon variable. Both of my examples return arrays by calling methods (ActiveRecord query for usernames and mapping image links), but you could just as easily do gon.variable = [example1, example2, example3] (though, as we’ll see, you could add this data straight into your JavaScript file)

Assign that Gon variable to a JavaScript variable. In whatever .js file you choose, assign

// Other javascript...
var gravatars = gon.gravatars
var usernames = gon.usernames;
// More javascript

Open application.js

//= require twitter/typeahead
Determine the css selector for the input on which you want to implement typeahead. In my case, I added a class of “typeahead” to my targeted text field as follows:
<!-- ...preceding html/erb... -->
<%= text_field_tag :name_or_email, nil, placeholder: "To: name or email", class: "typeahead" %> 
<!-- ... -->
 
  • In whichever JavaScript file you’ve made the dataset available, add $('.typeahead').typeahead(). Replace “.typeahead” with whatever CSS selector you’re using (see previous step). You now have the entire structure into which you can try the various typeahead.js examples.
     
  • I started with the basics, copying line 1-23 above my typeahead method, and everything withing the curly braces from line 37-44 into my typeahead method. Make sure to change the example’s default variable (“states” in the basic example, “best-pictures” in the custom templates example) to whatever variable you assigned using Gon. Depending on how your Rails app is structured–particularly what your asset pipeline looks like–this may be all you need.
  • I had conflicting stylesheets and JavaScript files, plus I wanted more flexibility creating templates for the typeahead, so I implemented the custom templates example. Full code for what I describe is below.
To begin, I added the templates (lines 28-40). The “empty” template worked easily–the code copied from Twitter’s example worked on its own. I had more difficulty with the “suggestion” template, primarily because I didn’t immediately realize that it’s a function, as opposed to the string that the “empty” template was. At this point, I was able to style the template as I liked, even including an image. pattern of passing entire objects and calling two or more different attributes (best pictures’ names and years in the custom template example), but I was unable to configure my JavaScript this way. Instead, knowing that my “gravatars” array directly mirrored my “usernames”, I used JavaScript’s indexOf() method, as seen in line 37. This enabled me to the the index of a given username and find the gravatar url at that index of the gravatars array. Not ideal, but it worked.
// Twitter Typeahead
$(document).ready(function() {
  var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
      var matches, substringRegex;
      matches = [];
      substrRegex = new RegExp(q, 'i');
      $.each(strs, function(i, str) {
        if (substrRegex.test(str)) {
          matches.push({ value: str });
        }
      });
      cb(matches);
    };
  };
  var gravatars = gon.gravatars;
  var usernames = gon.usernames;
  $('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1,
  },

  {
    name: 'usernames',
    displayKey: 'value',
    source: substringMatcher(usernames),
    templates: {
      empty: [
        '<div class="empty-message">',
        'No username matches found. Enter an email instead!',
        '</div>'
      ].join('\n'),
      suggestion: function(username){
        return  '<div id="user-selection">' +
                '<p><strong>' + username.value + '</strong></p>' +
                '<img src="' + gravatars[usernames.indexOf(username.value)] + '"/>' +
                '</div>' ;
      }
    }
  });
});


  • My final issue came with the highlighting. The highlight:true line within the typeahead method indicates that it should work right out of the box, but it did not for me (again, due to conflicting other assets). For this reason, I needed to debug in my JavaScript console, eventually finding that an item selected using typeahead was situated in a div with class of “tt-cursor”. A lot of the default styling was fine with me but, since the highlighting itself did not work, I added the following to my css, thus giving the selected item a background color. “` css styling.css div .tt-cursor { background-color: #16A085; } “` (that selector, “.tt-cursor”, was very important!)
  • And that concludes my adventures with typeahead. It took some time, but, as I described before, it’s those seemingly minor finishing touches that can end up taking the most time. This exercise was certainly proof of that. But it was worth it to get a working—and good-looking—typeahead form input.

    March 03, 2015

    Create A Sample Web Application On Rails

    Posted by Unknown
    0

     In this series I will create a simple web application. It includes the following main components: 

    • Mostly static pages, use bootstrap
    • Users can signin, signout, remember user signin
    •  Home page show all users, update their profiles, admin users can delete other users.
    • User can following or unfollow other users
    • Users can post articles, update and destroy their posts.
    • Users login and make their comments on articles.
    • Home page show all articles and current user profile, paging.
    • Build url for article
    • Simple search articles
    • Type ahead, use gon gem.

    Ok, start!

    Users, articles and some authorizations, validates...

    See more at : Rails Book

    The next articles: build friendly url, simple search box and type ahead on search box. 


    Sign up On Rails App - Create A Sample Web Application On Rails Part03

    Posted by Unknown
    0

     In this series I will create a simple web application. It includes the following main components: 

    • Mostly static pages, use bootstrap
    • Users can signin, signout, remember user signin
    •  Home page show all users, update their profiles, admin users can delete other users.
    • User can following or unfollow other users
    • Users can post articles, update and destroy their posts.
    • Users login and make their comments on articles.
    • Home page show all articles and current user profile, paging.
    • Build url for article
    • Simple search articles
    • Type ahead, use gon gem.

    Ok, start!

    Part III, Sign up on rails application

    1. Create User model

    $ rails g model User name:string email:string
    $ bundle exec rake db:migrate
    

    Simple validates and format email

    Open app/models/user.rb and add:
      validates :name,  presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
      validates :email, presence: true, length: { maximum: 255 },
                        format: { with: VALID_EMAIL_REGEX }
    

    Uniqueness validation email

    Open again app/models/user.rb and edit:
      before_save { self.email = email.downcase }
      validates :name,  presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
      validates :email, presence: true, length: { maximum: 255 },
                        format: { with: VALID_EMAIL_REGEX },
                        uniqueness: { case_sensitive: false }
    

    Database indices

    $ rails generate migration add_index_to_users_email
    
    Open db/migrate/[timestamp]_add_index_to_users_email.rb and edit
    class AddIndexToUsersEmail < ActiveRecord::Migration
      def change
        add_index :users, :email, unique: true
      end
    end
    
    Run command to migrate database
    # rake db:migrate
    

    Secure password

    Add password_digest to user model
    # rails generate migration add_password_digest_to_users password_digest:string
    # rake db:migrate
    
    Open Gemfile and add
    gem 'bcrypt',  '3.1.7'
    
    Run command to install gem
    # bundle install
    
    Add has secure password and validates to user.rb
      has_secure_password
      validates :password, length: { minimum: 6 }
    

    User sign up

    Add user resources to config/routes.rb
      resources :users
    
    resources :users => full restfull
    /users 
    /users/1
    /users/1/edit
    /users
    /users/new
    /users/1
    /users/1
    
    Saw full url with these method, run command
    # rake routes
    

    Create users controller

    # rails g controller users index new show
    
    Create app/views/users/show.html.erb
    <%= @user.name %>, <%= @user.email %>
    
    Open app/controllers/users_controller.rb and edit
    def show
      @user = User.find(params[:id])
    end
    
    def new
      @user = User.new
    end
    

    Create sign up form

    Open app/views/users/new.html.erb
    <% provide(:title, 'Sign up') %>
    <h1>Sign up</h1>
    
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
        <%= form_for(@user) do |f| %>
          <%= render 'shared/error_messages' %>
    
          <%= f.label :name %>
          <%= f.text_field :name, class: 'form-control' %>
    
          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control' %>
    
          <%= f.label :password %>
          <%= f.password_field :password, class: 'form-control' %>
    
          <%= f.label :password_confirmation, "Confirmation" %>
          <%= f.password_field :password_confirmation, class: 'form-control' %>
    
          <%= f.submit "Create my account", class: "btn btn-primary" %>
        <% end %>
      </div>
    </div>
    

    Open users_controller.rb

      
      def create
       @user = User.new(user_params)
       if @user.save
        flash[:success] = "Sign up successful"
        redirect_to @user
       else
        render 'new'
       end
      end
    
      private
    
        def user_params
       params.require(:user).permit(:name, :email, :password, :password_confirmation)
        end
    

    Create error messages

    Create app/views/shared/_error_messages.html.erb
    <% if @user.errors.any? %>
      <div id="error_explanation">
        <div class="alert alert-danger">
          The form contains <%= pluralize(@user.errors.count, "error") %>.
        </div>
        <ul>
        <% @user.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    <% end %>
    
    Run commands
    # rake db:migrate
    # rails s
    

    Try sign up

    Fill all and sign up will success.


    March 02, 2015

    Deploy Rails App on Heroku - Precompile Asset Errors

    Posted by Unknown
    0

    I use bootstrap on rails app, precompile appear when i deploy rails app on heroku. (Rails 4)

    I resolved and worked

    I added bootstrap to Gemfile
    gem 'bootstrap-sass', '3.2.0.0'
    
    Run command
    # bundle install
    
    My styles.css
    @import "bootstrap-sprockets";
    @import "bootstrap";
    
    I changed file name to styles.css.scss
    
    Reupload rails app to github and push to heroku app. That error resolved.

    May be use!

    # git push heroku master -f
    
    Edit following line if bootstrap not work on heroku
    # config/environments/production.rb
    config.assets.compile = true
    
    Then reupload to github and heroku.

    How To Use Bootstrap On Rails App - Create A Sample Web Application On Rails Part02

    Posted by Unknown
    0

     

     In this series I will create a simple web application. It includes the following main components: 

    • Mostly static pages, use bootstrap
    • Users can signin, signout, remember user signin
    •  Home page show all users, update their profiles, admin users can delete other users.
    • User can following or unfollow other users
    • Users can post articles, update and destroy their posts.
    • Users login and make their comments on articles.
    • Home page show all articles and current user profile, paging.
    • Build url for article
    • Simple search articles
    • Type ahead, use gon gem.

    Ok, start!

    Part I - Create sample app

    Part II, Use bootstrap on rails application.

    # cd sample_app
    

    1. Create StaticPages controller

    # rails g controller StaticPages home help about
    
    If you want undo
    # rails destroy controller StaticPages home help about
    
    Then point to /static_pages/home display:
    Open config/routes.rb and edit:
    Rails.application.routes.draw do
      get 'home' => 'static_pages#home'
      get 'help' => 'static_pages#help'
      get 'about' => 'static_pages#about'
      root 'static_pages#home'
    end
    
    Now, go /home = /static_pages/home, web root pages also point to home page. To modify home page, edit views/static_pages/home.html.erb file

    Use bootstrap

    Go to http://getbootstrap.com/
    Example navbar:
    <nav class="navbar navbar-default">
      <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>
    
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><%= link_to 'Link', '#' %> <span class="sr-only">(current)</span></li>
            <li><%= link_to 'Link', '#' %></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                <li><%= link_to 'Action', '#' %></li>
                <li><%= link_to 'Other action', '#' %></li>
                <li><%= link_to 'More action', '#' %></li>
                <li class="divider"></li>
                <li><%= link_to 'Separated link', '#' %></li>
              </ul>
            </li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><%= link_to 'Login', '#' %></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    
    Create new file: views/layouts/_header.html.erb and copy sample navbar code above to it.
    Open views/layouts/application.html.erb and add following line:
    
      <%= render 'layouts/header' %>
      
      <%= yield %>
    
    
    
    Refresh browser:
    To use bootstrap, add bootstrap gem to Gemfile
    gem 'bootstrap-sass',       '3.2.0.0'
    
    Then run command
    # bundle install --without production
    
    Create styles.css.scss
    $ touch app/assets/stylesheets/styles.css.scss
    
    Add following lines to styles.css.scss
    @import "bootstrap-sprockets";
    @import "bootstrap";
    
    Restart web server and point to http://localhost:3000

    Same above, you can create _footer.html.erb file or any other you want

    Create pages title

    Open layouts/application.html.erb and edit as:
    <!DOCTYPE html>
    <html>
      <head>
        <title><%= full_title(yield(:title)) %></title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 
        <%= stylesheet_link_tag "application", media: "all",
                                               "data-turbolinks-track" => true %>
        <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
        <%= csrf_meta_tags %>    
      </head>
      <body>
        <%= render 'layouts/header' %>  
        <div class="container">  
          <% flash.each do |message_type, message| %>
          <div class="alert alert-<%= message_type %>"><%= message %></div>
          <% end %>    
          <%= yield %>
          <%= render 'layouts/footer' %>
          <%= debug(params) if Rails.env.development? %> 
        </div>
      </body>
    </html>
    

    Create full_title function

    Open app/helpers/application_helper.html.erb file and edit
    module ApplicationHelper
      # Returns the full title on a per-page basis.
      def full_title(page_title = '')
        base_title = "Ruby on Rails Tutorial Sample App"
        if page_title.empty?
          base_title
        else
          "#{page_title} | #{base_title}"
        end
      end	
    end
    

    Update on github and push to heroku

    # git status
    # git add -A
    # git commit -m "Create StaticPages and use bootstrap"
    # git push origin master
    # git push heroku master -f
    # heroku open
    

    May you need!

    If on heroku not apply bootstrap, open config/environments/production.rb and edit:
      # Do not fallback to assets pipeline if a precompiled asset is missed.
      config.assets.compile = true
    
    Then push again to github and push it on heroku.

    March 01, 2015

    Rails Install and Make A New App - Create A Sample Web Application On Rails

    Posted by Unknown
    0

     

     In this series I will create a simple web application. It includes the following main components: 

    • Mostly static pages, use bootstrap
    • Users can signin, signout, remember user signin
    •  Home page show all users, update their profiles, admin users can delete other users.
    • User can following or unfollow other users
    • Users can post articles, update and destroy their posts.
    • Users login and make their comments on articles.
    • Home page show all articles and current user profile, paging.
    • Build url for article
    • Simple search articles
    • Type ahead, use gon gem.

    Ok, start!

    Part I: Create new project, configure database use MySQL, modify Gemfile and then push it on Github, deploy on heroku server

    Firstly, install ruby, rails framework on your system

    Install Ruby on Linux and Windows
    Install Rails Framework on Linux and Windows

    Test install ruby on rails

    # ruby -v
    # rails -v
    

    Create a new project

    # mkdir projects
    # cd projects
    # rails new sample_app -d mysql
    

    Modify Gemfile and configure database.yml

    Open database.yml and change:
    username: root
    password: [your password]
    database: [database name]
    
    Ex:
    default: &default
      adapter: mysql2
      encoding: utf8
      pool: 5
      username: root
      password: root
      socket: /var/run/mysqld/mysqld.sock
    
    development:
      <<: *default
      database: sample_app_development 
    test:
      <<: *default
      database: sample_app_test
    production:
      <<: *default
      database: sample_app_production 
    
    Open Gemfile and add some gem you want, following is sample Gemfile
    source 'https://rubygems.org'
    
    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    gem 'rails', '4.2.0.rc1'
    
    # Use SCSS for stylesheets
    gem 'sass-rails', '~> 4.0.0'
    
    # Use Uglifier as compressor for JavaScript assets
    gem 'uglifier', '>= 1.3.0'
    
    # Use CoffeeScript for .js.coffee assets and views
    gem 'coffee-rails', '~> 4.0.0'
    
    # See https://github.com/sstephenson/execjs#readme for more supported runtimes
    # gem 'therubyracer', platforms: :ruby
    
    # Use jquery as the JavaScript library
    gem 'jquery-rails'
    
    # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
    gem 'turbolinks'
    
    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 1.2'
    
    group :doc do
      # bundle exec rake doc:rails generates the API under doc/api.
      gem 'sdoc', require: false
    end
    
    # Use ActiveModel has_secure_password
    # gem 'bcrypt-ruby', '~> 3.1.2'
    
    # Use unicorn as the app server
    # gem 'unicorn'
    
    # Use Capistrano for deployment
    # gem 'capistrano', group: :development
    
    # Use debugger
    # gem 'debugger', group: [:development, :test]
    
    group :development, :test do
      gem 'mysql2'
      gem 'web-console'
      gem 'spring'
    end
    
    group :test do
      gem 'minitest-reporters'
      gem 'mini_backtrace'
      gem 'guard-minitest'
    end
    
    group :production do
      gem 'pg'
      gem 'rails_12factor'
    end
    
    gem 'mocha', group: :test
    
    
    Then run command to install gem
    # cd sample_app
    # bundle install --without production
    

    Run on localhost

    # cd sample_app
    # rails s
    
    Open browser, http://localhost:3000 or http://:3000

    Push on github

    Login on github and create an account, create a new project on github
    # cd sample_app
    # git init
    # git remote add origin git@bitbucket.org:<username>/sample_app.git
    # git add -A
    # git commit -m "First commit, Initialize project."
    # git push origin master
    or 
    # git push -u origin --all
    

    Push project on heroku

    Login on heroku, create an account if you don't have. Heroku only use git to deploy rails application.
    Add hello world
    Open application_controller.rb and add following lines:
      def hello
       render text: "Hello, world!"
      end
    
    Open routes.rb and add:
    root 'application#hello'
    
    Update your changes to github
    # git status
    # git add -A
    # git commit -m "Add hello"
    # git push -u origin master
    
    # heroku login
    # heroku create
    # git push heroku master
    
    Push other brand
    # git push heroku new-brand:master
    
    May you need!
    # git push heroku master -f
    # git push heroku new-brand:master -f
    
    If you want to remove remote link heroku and add new link
    # git remote -v
    # git remote rm heroku
    # heroku git:remote -a herokuappname
    
    If you want to remove current git remote link and add new link
    # git remote -v
    # git remote rm origin
    # git remote add origin remote link
    
    Open web application on heroku
    # heroku open
    
    DONE! Part02 to be continue.

    Popular Posts

    Labels

    Archive

     

    Blogroll

    Recepies

    Flickr Images

    Copyright © 2014. Tutorials Blog - All Rights Reserved