RSS

Monthly Archives: June 2010

General Command Ubuntu

$ sudo passwd root : Change root password

$ sudo shutdown -h now : shutdown

Configure Network Interface Using Command-Line

sudo vi /etc/network/interfaces

# The primary network interface – use DHCP to find our address
auto eth0
iface eth0 inet dhcp

# The primary network interface

auto eth0
iface eth0 inet static
address 192.168.3.90
gateway 192.168.3.1
netmask 255.255.255.0
network 192.168.3.0
broadcast 192.168.3.255

sudo /etc/init.d/networking restart

Restart Apache Server

sudo /etc/init.d/apache2 restart


Copy, Move and Rename
cp file file2 copy file
rm file1 file2 - rename
rm file1 dir/file1 - move file
Advertisements
 
Leave a comment

Posted by on June 18, 2010 in General

 

Column Header CheckBox in DataGridView (Winfoms)

Introduction

This article will explains about creating & displaying Column Header CheckBox in winforms DataGridView.

Background

Bydefault DataGridView doen’t supports column header chekbox, for this we need to write a class which is inherited by DataGridViewColumnHeaderCell class.

1) Add a boolean propery named CheckAll in that class to maintain the seleced state of Header checkbox.

2) override default implemention of Paint method. In this method, drawing the CheckBox at column Header.

3) override its OnMouseClick event. Here handle the click event of header checkbox.

I have created class named DGVColumnHeader as follows…

<pre id="pre0">    class DGVColumnHeader : DataGridViewColumnHeaderCell
    {
        private Rectangle CheckBoxRegion;
        private bool checkAll = false;

        protected override void Paint(Graphics graphics,
            Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
            DataGridViewElementStates dataGridViewElementState,
            object value, object formattedValue, string errorText,
            DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {

            base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value,
                formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            graphics.FillRectangle(new SolidBrush(cellStyle.BackColor), cellBounds);

            CheckBoxRegion = new Rectangle(
                cellBounds.Location.X + 1,
                cellBounds.Location.Y + 2,
                25, cellBounds.Size.Height - 4);


            if (this.checkAll)
                ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked);
            else
                ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal);

            Rectangle normalRegion =
                new Rectangle(
                cellBounds.Location.X + 1 + 25,
                cellBounds.Location.Y,
                cellBounds.Size.Width - 26,
                cellBounds.Size.Height);

            graphics.DrawString(value.ToString(), cellStyle.Font, new SolidBrush(cellStyle.ForeColor), normalRegion);
        }

        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            //Convert the CheckBoxRegion 
            Rectangle rec = new Rectangle(new Point(0, 0), this.CheckBoxRegion.Size);
            this.checkAll = !this.checkAll;
            if (rec.Contains(e.Location))
            {
                this.DataGridView.Invalidate();
            }
            base.OnMouseClick(e);
        }

        public bool CheckAll
        {
            get { return this.checkAll; }
            set { this.checkAll = value; }
        }
    }
</pre>

First Initialize a object of DGVColumnHeader add to DataGridView columns using Insert method at desired place. In this example i have added at first column and assigned to HeaderCell of it.

<pre id="pre2">
<pre id="pre1">//Create the object of DGVColumnHeader 
        DGVColumnHeader dgvColumnHeader;
        private void Form1_Load(object sender, EventArgs e)
        {
            //initialize DGVColumnHeader object
            dgvColumnHeader = new DGVColumnHeader();
            
            //Add columns dynamically  to gridview
            dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());
            dataGridView1.Columns[0].HeaderCell = dgvColumnHeader;
            
            //Data Binding 
            DataTable dt = new DataTable();
            dt.Columns.Add("1");
            dt.Columns.Add("2");
            dt.Rows.Add("100", "101");
            dt.Rows.Add("102", "103");
            dataGridView1.DataSource = dt;
        }
</pre>
</pre>

Add the following code in dataGridView1_ColumnHeaderMouseClick event to check/uncheck all the records based on the header checkbox state

<pre id="pre3">        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                for (int i = 0; i < this.dataGridView1.RowCount; i++)
                {
                    //Escalate Editmode
                    this.dataGridView1.EndEdit();
                    string re_value = this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString();
                    this.dataGridView1.Rows[i].Cells[0].Value = "true";
                }
            }
        }
</pre>

Add the following code in dataGridView1_ColumnHeaderMouseClick event to check/uncheck all the records based on the header checkbox state

<pre id="pre2">        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    dataGridView1.Rows[i].Cells[0].Value = dgvColumnHeader.CheckAll;
                }
            }
        }
</pre>

When we select any of checkbox cell other than Header checkbox, by default grid will shows as edit mode. This we can handle using dataGridView1_CellClick event

<pre id="pre3">        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                for (int i = 0; i < this.dataGridView1.RowCount; i++)
                {
                    //Escalate Editmode
                    this.dataGridView1.EndEdit();
                    string re_value = this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString();
                    this.dataGridView1.Rows[i].Cells[0].Value = "true";
                }
            }
        }
</pre>

Referenced by: http://www.codeproject.com/KB/grid/DataGridView_winforms.aspx

 
Leave a comment

Posted by on June 14, 2010 in C#, Window Application

 

Data Validation in CakePHP

Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application. For example, you might want to make sure that passwords are at least eight characters long, or ensure that usernames are unique. Defining validation rules makes form handling much, much easier.

var $validate = array('fieldName' => 'ruleName');
<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array(
        'login' => 'alphaNumeric',
        'email' => 'email',
        'born' => 'date'
    );
}
?>

One Rule Per Field

var $validate = array(
    'fieldName1' => array(
        'rule' => 'ruleName', // or: array('ruleName', 'param1', 'param2' ...)
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // or: 'update'
        'message' => 'Your Error Message'
    )
);
  1. Single value : 'alphaNumeric'
  2. Max, min or range : array('minLength', 15)
  3. Comparison : array(‘comparision’, ‘>’,  0.00)
  4. Number : numeric
  5. Date : date
  6. Money format : array(‘decimal’, 2)
  7. Email format : email
  8. Between 0-15 characters :  array(‘between’, 0,  15)
  9. Alphabets and Number only : alphaNumeric

Multiple Rules per Field

var $validate = array(
    'fieldName' => array(
        'ruleName' => array(
            'rule' => 'ruleName',
            // extra keys like on, required, etc. go here...
        ),
        'ruleName2' => array(
            'rule' => 'ruleName2',
            // extra keys like on, required, etc. go here...
        )
    )
);


<pre>var $validate = array(
    'login' => array(
        'loginRule-1' => array(
            'rule' => 'alphaNumeric',
            'message' => 'Only alphabets and numbers allowed',
            'last' => true
         ),
        'loginRule-2' => array(
            'rule' => array('minLength', 8),
            'message' => 'Minimum length of 8 characters'
        )
    )
);

Custom Validation Rules

Custom Regular Expression Validation

<pre>var $validate = array(
    'login' => array(
        'rule' => '/^[a-z0-9]{3,}$/i',
        'message' => 'Only letters and integers, min 3 characters'
    )
);

The example above checks if the login contains only letters and integers, with a minimum of three characters.

The regular expression in the rule must be delimited by slashes. The optional trailing ‘i’ after the last slash means the reg-exp is case insensitive.

Adding your own method

Sometimes checking data with regular expression patterns is not enough. For example, if you want to ensure that a promotional code can only be used 25 times, you need to add your own validation function, as shown below:

<pre><?php
class User extends AppModel {
    var $name = 'User';

    var $validate = array(
        'promotion_code' => array(
            'rule' => array('limitDuplicates', 25),
            'message' => 'This code has been used too many times.'
        )
    );

    function limitDuplicates($check, $limit){
        //$check will have value: array('promomotion_code' => 'some-value')
        //$limit will have value: 25
        $existing_promo_count = $this->find( 'count', array('conditions' => $check, 'recursive' => -1) );
        return $existing_promo_count < $limit;
    }
}
?>
</pre>

The current field to be validated is passed into the function as first parameter as an associated array with field name as key and posted data as value.

If you want to pass extra parameters to your validation function, add elements onto the ‘rule’ array, and handle them as extra params (after the main $check param) in your function.

Your validation function can be in the model (as in the example above), or in a behavior that the model implements. This includes mapped methods.

When writing a validation rule which can be used by multiple fields, take care to extract the field value from the $check array. The $check array is passed with the form field name as its key and the field value as its value. The full record being validated is stored in $this->data member variable.

<pre><?php
class Post extends AppModel {
  var $name = 'Post';

  var $validate = array(
    'slug' => array(
      'rule' => 'alphaNumericDashUnderscore',
      'message' => 'Slug can only be letters, numbers, dash and underscore'
      )
    );

    function alphaNumericDashUnderscore($check) {
      // $data array is passed using the form field name as the key
      // have to extract the value to make the function generic
      $value = array_values($check);
      $value = $value[0];

      return preg_match('|^[0-9a-zA-Z_-]*$|', $value);
    }
}
?>
</pre>
 
1 Comment

Posted by on June 12, 2010 in PHP

 

Recover MySQL root Password

You can recover MySQL database server password with following five easy steps.

Step # 1: Stop the MySQL server process.

Step # 2: Start the MySQL (mysqld) server/daemon process with the –skip-grant-tables option so that it will not prompt for password.

Step # 3: Connect to mysql server as the root user.

Step # 4: Setup new mysql root account password.

Step # 5: Exit and restart the MySQL server.

Here are commands you need to type for each step (login as the root user):

Step # 1 : Stop mysql service

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld.

Step # 2: Start to MySQL server w/o password:

# mysqld_safe --skip-grant-tables &
Output:

[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started

Step # 3: Connect to mysql server using mysql client:

# mysql -u root
Output:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Step # 4: Setup new MySQL root user password

mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

Step # 5: Stop MySQL Server:

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended

[1]+  Done                    mysqld_safe --skip-grant-tables

Step # 6: Start MySQL server and test it

# /etc/init.d/mysql start
# mysql -u root -p

 
Leave a comment

Posted by on June 11, 2010 in MySQL Server

 

How to install CakePHP

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

  1. Webserver for PHP (Wamp server or Xamm)
  2. PHP 5.3.2
  3. MySQL 5
  4. CakePHP 1.3.1 : http://github.com/cakephp/cakephp/zipball/1.3.1

Installation CakePHP with Web Server

  1. Extract CakePHP file that you have download from URL above to the place and rename to “cake” only
  2. Go into this folder: cake/cake/console/ and right click on “cake.bat” file; copy this file path to past in Path of Environment Variables (System Properties -> Advanced  -> System variables)
  3. Point to PHP bin and copy it’s path to the Path of Environment Variables
  4. Point to MySQL bin and copy it’s path to the Path of Environment Variables too.
  5. Open CMD and type : cake and enter to test that cake works or not?

*Notation: Path of CakePHP, PHP, and MySQL must be separated by “;”

If you install CakePHP on Windows, it has a little bit problem that we have to fix.

Fix The Problem

  1. In cake/cake/console : copy directory “templates” to directory “libs”
  2. In cake/cake/libs/cache/file.php : change $data = unserialize((string)$data); to $data = unserialize(trim((string)$data)); in line 176

Referenced by: http://www.cakephp.org/

 
Leave a comment

Posted by on June 10, 2010 in PHP