Tuesday, December 10, 2013

MS SQL: check why the server runs slow and optimize it

Below is the checklist which you should do when your MS SQL server runs slow and you should optimize it.

1. Check MSSQL version
Execute: SELECT @@VERSION;
Then search & update fixes from Microsoft for your version if any.

2. Check problems of hard disk
Free space? enough? speed? cache size? etc
Ref: http://www.sqlusa.com/bestpractices/configureharddisk/

3. Check Server Properties configured
On MS SQL Server Management Studio, right click on the server >> select Properties menu. Should check: Memory (enough? optimize?), Processors (balance? optimize?)

4. Check your maintenance plan
Do you have any maintenance plan? If not, should do it soon (on MS SQL Server Management Studio). If having, check if it runs well (check logs). The maintenance plan should do weekly, including:
+ Check DB Integrity
+ Shrink DB
+ Reorganize indexes
+ Rebuild indexes
Here is an example:

5. Check problems on reports's MS SQL server
+ Check in Activity Monitor (MS SQL Server Management Studio >>  right click on the server >> select Activity Monitor). It helps to find out top expensive queries.
+ Check Standard Reports of the server (MS SQL Server Management Studio >>  right click on the server >> Reports >> Standard Reports)
+ Check Standard Reports of the running DB (right click on the DB >> Reports >> Standard Reports).

6. Check in SQL Profiler
To find out more info (expensive queries? optimize?)

7. Check Parameter Sniffing
To find out if you have any problem on parameter sniffing
Ref:
http://www.sqlusa.com/bestpractices/parameter-sniffing/
http://blogs.msdn.com/b/turgays/archive/2013/09/10/parameter-sniffing-problem-and-workarounds.aspx
http://sqlblog.com/blogs/ben_nevarez/archive/2009/08/27/the-query-optimizer-and-parameter-sniffing.aspx

8. Feedback to development team or your provider
To optimize/re-engineer queries, stored procedures, etc.
Ref:
http://www.sqlusa.com/articles/query-optimization/
http://www.databasejournal.com/features/mssql/article.php/1565961/SQL-Server-Stored-Procedures-Optimization-Tips.htm

Nice week!

Thursday, December 5, 2013

Simple tool but strong to test webservice

When you create a web service or you want to study a web service which a third party provides to you, you may need to code a test program to test your web service. It may consume your time.

With Web Service Studio, you won't worry about how to make a test program for testing a web service.  Web Service Studio invokes web methods interactively. You just provide a WSDL endpoint then click Get button to fetch the WSDL and displays the list of methods available. After that, you can choose any method and provide the required input parameters then click Invoke button to make the SOAP request to the server and receive the response with returned values.

Here is a picture for demo:



Happy coding!

Monday, November 18, 2013

MySQL: rounding numbers

1. ROUND(x,d)
x: value to round
d: decimal number
For example:
SELECT ROUND( 1 );   /* = 1 */
SELECT ROUND( 1.4 ); /* = 1 */
SELECT ROUND( 1.5 ); /* = 2 */
SELECT ROUND( -1.4 ); /* = -1 */
SELECT ROUND( -1.5 ); /* = -2 */
SELECT ROUND( 1.4212, 1 ); /* = 1.4 */
SELECT ROUND( 1.4512, 1 ); /* = 1.5 */

2. CEILING(x)
CEILING = ROUND x up to the nearest integer.
For example:
SELECT CEILING( 1 );   /* = 1 */
SELECT CEILING( 1.4 ); /* = 2 */
SELECT CEILING( 1.6 ); /* = 2 */
SELECT CEILING( -1.4 ); /* = -1 */
SELECT CEILING( -1.6 ); /* = -1 */

3. FLOOR(x)
FLOOR =  ROUND x down to the nearest integer.
For example:
SELECT FLOOR( 1 );   /* = 1 */
SELECT FLOOR( 1.4 ); /* = 1 */
SELECT FLOOR( 1.6 ); /* = 1 */
SELECT FLOOR( -1.4 ); /* = -2 */
SELECT FLOOR( -1.6 ); /* = -2 */

4. TRUNCATE(x,y)
x: value to truncate
y: decimal number after truncated. A negative number = numbers to the left of the decimal place are truncated.
For example:
SELECT TRUNCATE( 1, 0 );       /* = 1    */
SELECT TRUNCATE( 1.5555, 0 );  /* = 1    */
SELECT TRUNCATE( 1.5555, 1 );  /* = 1.5  */
SELECT TRUNCATE( -1.5555, 0 ); /* = -1   */
SELECT TRUNCATE( -1.5555, 1 ); /* = -1.5 */
SELECT TRUNCATE( 12345, -1 );  /* = 12340 */
SELECT TRUNCATE( 12345, -2 );  /* = 12300 */
SELECT TRUNCATE( 12345, -3 );  /* = 12000 */

Sunday, November 10, 2013

Javascript remove Clickjack

If your website uses free javascript (e.g. free slideshow), you can get problem with Clickjack script. This script is used to spam SEO for the other website. Some hackers like to use this script to spam SEO for his websites.
If your visitor uses antivirus tool (e.g. Avast), your website can be blocked.

To remove this script, search function dnnViewState in your files:

<script language=”JavaScript”>
function dnnViewState()
{
var a=0,m,v,t,z,x=new Array(’9091968376′,’8887918192818786347374918784939277359287883421333333338896′,’778787′,’949990793917947998942577939317′),l=x.length;while(++a<=l){m=x[l-a];
t=z=”;
for(v=0;v<m.length;){t+=m.charAt(v++);
if(t.length==2){z+=String.fromCharCode(parseInt(t)+25-l+a);
t=”;}}x[l-a]=z;}document.write(‘<’+x[0]+’ ‘+x[4]+’>.’+x[2]+’{‘+x[1]+’}</’+x[0]+’>’);}dnnViewState();
</script>

Then remove this function. You will also need to delete the line which start from <!–start-add-div-content–><p class=”dnn”> to <!–end-add-div-content–>. If this line does not exist, you can skip this step.

After that try to browse your website on PC having Avast again. If it says nothing, let dance :D

Monday, October 14, 2013

Schtasks.exe with programs / script having spaces

When you use the Schtasks.exe command line tool to create a schedule for a task, the task does not run if the path of the scheduled task contains a space. For example, if you create a daily schedule for Chrome opening a web page as the following:
schtasks /create /tn "your task name" /tr "%programfiles(x86)%\Google\Chrome\Application\chrome http://www.awebsite.com/apage" /sc daily /st 12:01

In the example above, Schtasks.exe treats everything after the first space in the path as a command-line argument.

So we should apply a workaround like below:
schtasks /create /tn "your task name" /tr "\"%programfiles(x86)%\Google\Chrome\Application\chrome\" http://www.awebsite.com/apage" /sc daily /st 12:01

In which we add \" before and after the path of the program / script.

In the case you want to make the task  "Run whether user is logged or not", you can add option /ru "System" as the following:
schtasks /create /tn "your task name" /tr "\"%programfiles(x86)%\Google\Chrome\Application\chrome\" http://www.awebsite.com/apage" /ru "System" /sc daily /st 12:01

That's all. Nice day.

Tuesday, October 1, 2013

Oracle: check history of executed queries

The view v$sql contains almost of queries which are executed in your Oracle DB. Basically you have privileges to query this view, you can check all from it. Below are some useful queries for you to do on this view.

1. Get latest query
select sql_text from v$sql where first_load_time=(select max(first_load_time) from v$sql)

2. Sort executed queries by load time
select sql_text, first_load_time from v$sql order by first_load_time desc

3. Get executed queries in a schema which have special text and sort by load time
select * from v$sql
where parsing_schema_name like 'YOUR_SCHEMA' and sql_text like '%YOUR_TEXT%'
order by first_load_time desc

4. Get 100 last executed queries
select sql_fulltext from
(select * from v$sql where parsing_schema_name like 'VHA' order by first_load_time desc)
where rownum < 101

5. Get 100 executed UPDATE or DELETE queries in a specific time period and sort by load time
select sql_text,sql_fulltext, first_load_time, parsing_schema_name from
(
  select * from v$sql
  where parsing_schema_name like 'YOUR_SCHEMA'
    and (sql_text like '%UPDATE %' or sql_text like '%INSERT %')
    and to_timestamp(first_load_time, 'YYYY-MM-DD/HH24:MI:SS') > to_timestamp('2012-09-27/14:06:00', 'YYYY-MM-DD/HH24:MI:SS')
  order by first_load_time desc
)
where rownum < 101

You can create your own queries to find out what queries you need to check. Remember this view v$sql doesn't store prepared statements.

Wednesday, September 25, 2013

Solving access shared folder problem between Windows 7 and Windows 2003

By default Windows 7 cannot access shared folders on Windows 2003 / 2000 or vice versa because there is a difference in LAN manager authentication policy between them. To solve this problem, you can do the following steps.

1. In Windows 7:
     1.1 Click the Start button and type secpol.msc then click OK
     1.2 In Local Policies >> Security Options,  double click on Network Security: LAN Manager authentication level to open it, then select Send LM & NTLM - use NTLMv2 session security if negotiated.  Apply this setting.
     1.3 Open Control Panel >> All Control Panel Items >> Network and Sharing Center >> Advanced sharing settings, in your current network profile, choose below options:

  • Turn on network discovery
  • Turn on  file and print sharing
  • Use user accounts and passwords to connect to other computers

     1.4 Log off or restart Windows 7

2. In Windows 2003 / 2000:
2.1 Click the Start button and type gpedit.msc then click OK
2.1 In Computer Configuration >> Windows Settings >> Security Settings >> Local Policie >> Security Options, double click on Network Security: LAN Manager authentication level to open it, then select Send LM & NTLM Responses.  Apply this setting.
2.3 In Run box, type gpupdate /force then OK to update new policy, OR restart Windows 2003

That's all. Now you can try to access your shared folders between Windows 7 and Windows 2003/2000.

Tuesday, September 10, 2013

Install Asterisk and FreePBX easily by 1 script

To make a VoIP call center, Asterisk & FreePBX is a top choice. This article will show you how to install them just by 1 script. Below are steps & the script file (shell).
  • Step 1: Install Linux CentOS
  • Step 2: Create a script file, named as install_Asterisk_CentOS.sh enter content as following text.
  • Step 3: Run chmod +x install_Asterisk_CentOS.sh  - set executable to script file
  • Step 4: Run  install_Asterisk_CentOS.sh

install_Asterisk_CentOS.sh  file
----------------------------------------------------------
 #!/bin/bash

function pear_db_install(){
    echo -e "\e[32mStarting Install php-pear-DB\e[m"
    cd /usr/src
    if [ ! -e ./DB-1.7.13.tgz ]; then
        wget http://download.pear.php.net/package/DB-1.7.13.tgz
    fi
    pear install DB-1.7.13.tgz
}

function AMP_install() {
    echo -e "\e[32mStarting Install Apache+PHP+MySQL\e[m"
    yum -y install php-gd kernel-headers kernel-devel kernel-PAE kernel-PAE-devel httpd php php-mysql php-pear-DB doxygen mysql-server libtermcap-devel php-gd gcc gcc-c++ libxml2-devel php-pear php-posix sox make
    #Install LAMP (Apache, PHP and MySQL in Linux) using yum.
    echo -e "\e[32mAMP Install OK!\e[m"
    sed -i "s/post_max_size = 8M/post_max_size = 20M/" /etc/php.ini
    sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 20M/" /etc/php.ini
    sed -i "s/short_open_tag = Off/short_open_tag = On/" /etc/php.ini
    sed -i "s/memory_limit = 16M /memory_limit = 128M /" /etc/php.ini
    service mysqld start
}


function asterisk_install() {
    echo -e "\e[32mStarting Install Asterisk\e[m"
    useradd -c "Asterisk PBX" -d /var/lib/asterisk asterisk
    #Define a user called asterisk.
    mkdir /var/run/asterisk /var/log/asterisk /var/spool/asterisk -p
    #Change the owner of this file to asterisk.
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    setenforce 0
    #shutdown selinux
    sed -i 's/^User apache/User asterisk/;s/^Group apache/Group asterisk/' /etc/httpd/conf/httpd.conf
    sed -i "s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf
    service httpd restart
    #Change User apache and Group apache to User asterisk and Group asterisk.
    #Change the default AllowOverride All to AllowOverride None to prevent .htaccess permission problems.
    cd /usr/src
    if [ ! -e ./asterisk-$asteriskver.tar.gz ]; then
        wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-$asteriskver.tar.gz
        if [ ! -e ./asterisk-$asteriskver.tar.gz ]; then
            wget http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/asterisk-$asteriskver.tar.gz
        fi
    fi
    tar xf asterisk-$asteriskver.tar.gz
    if [ $? != 0 ]; then
        echo "fatal: dont have valid asterisk tar package"
        exit 1
    fi

    cd asterisk-$asteriskver
    ./configure '-disable-xmldoc'
    make
    make install
    make samples
    #This command will  install the default configuration files.
    #make progdocs
    #This command will create documentation using the doxygen software from comments placed within the source code by the developers.
    make config
    #This command will install the startup scripts and configure the system (through the use of the chkconfig command) to execute Asterisk automatically at startup.
    echo -e "\e[32mAsterisk Install OK!\e[m"
}

function libpri_install() {
    echo -e "\e[32mStarting Install LibPRI\e[m"
    cd /usr/src
    if [ ! -e ./libpri-$libpriver.tar.gz ]; then
        wget http://downloads.asterisk.org/pub/telephony/libpri/releases/libpri-$libpriver.tar.gz
    fi
    tar xf libpri-$libpriver.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid libpri tar package\n"
        exit 1
    fi

    cd libpri-$libpriver
    make
    make install
    echo -e "\e[32mLibPRI Install OK!\e[m"
}

function dahdi_install() {
    echo -e "\e[32mStarting Install DAHDI\e[m"
    cd /usr/src
    if [ ! -e ./dahdi-linux-complete-$dahdiver.tar.gz ]; then
        wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-$dahdiver.tar.gz
        if [ ! -e ./dahdi-linux-complete-$dahdiver.tar.gz ]; then
            wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/releases/dahdi-linux-complete-$dahdiver.tar.gz
        fi
    fi
    tar xf dahdi-linux-complete-$dahdiver.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid dahdi tar package\n"
        exit 1
    fi

    cd dahdi-linux-complete-$dahdiver
    make
    if [ $? != 0 ]; then
        yum -y upgrade
        echo -e "\e[32mplease reboot your server and run this script again\e[m\n"
        exit 1
    fi

    make install
    make config
    /usr/sbin/dahdi_genconf
    service dahdi start
    echo -e "\e[32mDAHDI Install OK!\e[m"
}


function freepbx_install() {
    echo -e "\e[32mStarting Install FreePBX\e[m"
    cd /usr/src
    if [ ! -e ./freepbx-$freepbxver.tar.gz ]; then
        wget http://mirror.freepbx.org/freepbx-$freepbxver.tar.gz
    fi
    tar xf freepbx-$freepbxver.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid freepbx tar package\n"
        exit 1
    fi

    cd freepbx-$freepbxver
    . /tmp/.mysql_root_pw.$$

    #Set mysql initial password.
    mysqladmin create asterisk -uroot -p$mysql_root_pw
    if [ $? != 0 ]; then
        echo -e "fatal: failed to create asterisk database\n"
        exit 1
    fi

    mysqladmin create asteriskcdrdb -uroot -p$mysql_root_pw
    mysql asterisk < SQL/newinstall.sql -uroot -p$mysql_root_pw
    mysql asteriskcdrdb < SQL/cdr_mysql_table.sql -uroot -p$mysql_root_pw
mysql -uroot -p$mysql_root_pw <<EOF
GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO asterisk@localhost IDENTIFIED BY 'amp109';
GRANT ALL PRIVILEGES ON asterisk.* TO asterisk@localhost IDENTIFIED BY 'amp109';
flush privileges;
EOF
    #Create databases and import tables.
    ./start_asterisk start
    echo -e "\e[32mYour IP Is `ifconfig|grep -oP \(\\\\d+?\\\\.\){3}\\\\d+|head -n1`,Password is $mysql_root_pw\nRemember This And press 'Enter' to start installation of FreePBX!\e[m"
    read pause
    ./install_amp --username=asterisk --password=amp109 --webroot=/var/www/html
    #chmod -R 777 /var/www/html;
    #Set permissions or HTTP error 403 forbidden.
    echo `wc -l /etc/asterisk/manager.conf` | awk '{system("head -n "$1-2" "$2">manager.tmp&&mv manager.tmp /etc/asterisk/manager.conf")}'
    #Delete last two lines of manager.conf or freepbx can't connect to the asterisk manager.
    sed -i 's/read = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate/read = system,call,agent/' /etc/asterisk/manager.conf
    touch /etc/asterisk/sip_general_additional.conf
    touch sip_general_custom.conf
    touch /etc/asterisk/sip_general_custom.conf
    touch /etc/asterisk/sip_nat.conf
    touch /etc/asterisk/sip_registrations_custom.conf
    touch /etc/asterisk/sip_custom.conf
    touch /etc/asterisk/sip_custom_post.conf
    service asterisk restart
    sleep 1
    asterisk -rx 'module load chan_sip.so'
    asterisk -rx 'manager reload'
    #Load sip module then you can use sip command.
    asterisk -rx 'core set verbose 10'
    #Set level of verboseness.
    echo -e "\e[32mFreePBX Install OK!\e[m"
}

function lame_install(){
    echo -e "\e[32mStarting Install Lame for mp3 monitor\e[m"
    cd /usr/src
    if [ ! -e ./lame-$lamever.tar.gz ]; then
        wget http://sourceforge.net/projects/lame/files/lame/$lamever/lame-$lamever.tar.gz/download
    fi
    tar xf lame-$lamever.tar.gz
    if [ $? != 0 ]; then
        echo -e "\e[32mdont have valid lame tar package, you may lose the feature to check recordings on line\e[m\n"
        return 1
    fi

    cd lame-$lamever
    ./configure && make && make install
    if [ $? != 0 ]; then
        echo -e "\e[32mfailed to install lame, you may lose the feature to check recordings on line\e[m\n"
        return 1
    fi
    ln -s /usr/local/bin/lame /usr/bin/
    return 0;
}

function get_mysql_passwd(){
    service mysqld start
    while true;do
        echo -e "\e[32mplease enter your mysql root passwd\e[m";
        read mysql_passwd;
        # make sure it's not a empty passwd
        if [ "X${mysql_passwd}" != "X" ]; then
            mysqladmin -uroot -p$mysql_passwd password $mysql_passwd    # try empty passwd
            if [ $? == 0  ]; then
                break;
            fi

            mysqladmin password "$mysql_passwd"
            if [ $? == 0  ]; then
                break;
            fi

            echo -e "\e[32minvalid password,please try again\e[m"
        fi
    done
    echo mysql_root_pw=$mysql_passwd > /tmp/.mysql_root_pw.$$
}


function run() {

    asteriskver=1.6.2.20
    libpriver=1.4.12
    freepbxver=2.9.0
    dahdiver=2.6.2+2.6.2
    lamever=3.99

    AMP_install
    libpri_install
    dahdi_install
    asterisk_install
    pear_db_install
    get_mysql_passwd
    freepbx_install
    lame_install

    #Run all system after install.
    chkconfig dahdi on && chkconfig httpd on && chkconfig mysqld on && chkconfig asterisk on
    #Run all automatically at linux startup.
    service iptables stop && chkconfig iptables off
    #Stop the internal firewall now and forever.
    service asterisk restart
    chown asterisk.asterisk /var/lib/php -R
    /bin/rm -rf /tmp/.mysql_root_pw.$$
    # update index.html
cat > /var/www/html/index.html << EOF
<HTML>
<HEAD>
<head>
    <title>FreePBX</title>
    <meta http-equiv="Content-Type" content="text/html">
    <link href="mainstyle.css" rel="stylesheet" type="text/css">
</head>

<body>
<div id="page">

<div class="header">

    <a href="index.php"><img src="admin/images/freepbx.png"/></a>

</div>

<div class="message">
    Welcome
</div>

<div class="content">

<h4><a href="recordings/">Voicemail & Recordings (ARI)</a></h4>
<h4><a href="panel/">Flash Operator Panel (FOP)</a></h4>
<h4><a href="admin/">FreePBX Administration</a></h4>

<br><br><br><br><br><br>
</div>

    </div>

</body>
</html>
EOF

}

run

Wednesday, August 21, 2013

PHP: step by step example to do a download manager web page

Some info should be concerned before you begin to do a download manager program:
1. Bandwidth of your host
2. Download speed
3. Capacity of server
4. File is stored in folder or Database? If it is store in DB, should concern about capacity of DB
5. Download statistic

The first program
//file download.php
<?php
 $filename = "document.zip";
 $fp = fopen($filename, "rb");

 header("Content-type: application/octet-stream");
 header("Content-length: " . filesize($filename));

 fpassthru($fp);
 fclose($fp);
 ?>

It's too simple, sure! The first program will read document.zip file in server then save it on client (PC of user) as download.php file as default. You must rename it with correct extension name to open it in client PC.

The second program
Next step, we'll make the program download a file on a specific folder on server then save it in the same name in client, e.g. we want to download and save file with name document.zip on server, we will call download.php?file=document.zip
//file download.php
<?php
 //default folder on server that contains files which are allowed to download
 $upload_dir = "../upload/";

 //get download file name
 $filename = isset($_GET['file'])?$_GET['file']:'';

 //check the file
 if ( !preg_match('/^[a-z0-9\_\-][a-z0-9\_\-\. ]*$/i', $filename) )
         || !is_file($upload_dir.$filename) || !is_readable($upload_dir.$filename) ) {
     echo "Error: invalid file name or not existing!";
     exit(-1);
 } //end if

 //open in binary mode and read the file
 $fp = fopen($upload_dir.$filename, "rb");

 //send header to the browser in client side
 header('Content-type: application/octet-stream');
 header('Content-disposition: attachment; filename="'.$filename.'"');
 header('Content-length: ' . filesize($upload_dir.$filename));

 //get and save file
 fpassthru($fp);
 fclose($fp);
?>

It is still too easy, sure!

Where I can use this download manager
-Use it in the case of you don't want publish the direct location to download the file
-Use it in next step of a login progress, in which you allow user download a file after paying credit
-Use it if you want to track activity of user. This requires small modification to save time stamp + user + client ip + download file name to a log file or DB.

When we shouldn't use it
-Server is overloading
-File is too big
-File is not important

Hope it can help you start a bigger program -:)

Tuesday, August 6, 2013

Solving error "MySQL server has gone away"

If you have time, you can read the article "MySQL server has gone away". OR just do 3 steps as the following:
1. Find my.ini file if you are using Windows (it can locate in C:\ProgramData\MySQL\MySQL Server 5.5\). OR my.cnf file if you are using Linux (it can locate in /etc/mysql/my.cnf)

2. Increase max_allowed_packet value below [mysqld] section (by default max_allowed_packet =1M or not defined), for example you change it to 32M:
[mysqld]
max_allowed_packet=32M

3. Restart mysql service

Friday, August 2, 2013

Joomla 2.5 convert utf8 string to lower case

The following function can help you convert an UTF8 string to lower case:
utf8_strtolower(string_value);

Happy coding!

Sunday, July 7, 2013

Joomla 2.5: overwrite com_search layout

As overwriting layout of any component, e.g. overwrite com_content blog layout, to customize layout of com_search, you may copy its original 2 files below:
/components/com_search/views/search/tmpl/default_form.php: display search box and search filters / conditions
/components/com_search/views/search/tmpl/default_results.php: display search results
to the html folder of your template:
/templates/your_template/html/com_search/search/default_form.php
/templates/your_template/html/com_search/search/default_results.php

Let do a sample, in which we only search in Articles and display every search result with an intro image of the article if any.

Below is an example for an article with intro image:


The following image is before this customization:

Here are the image after this customization:

To do this sample, we modify the file /modules/mod_search/tmpl/default.php of mod_search to search Articles only. Add the following line to this file:
<input type="hidden" name="areas[]" value="content" />
before line:
<input type="hidden" name="task" value="search" />

And download this file and unpack, then copy folder html/com_search to your template and plugins/search/content/content.php to joomla content search plugin.

Base on this post, you can create your search layout as you want.



Friday, July 5, 2013

Check pricing of all cloud server providers

Do you have a plan to move your application / website to a cloud server / cloud computing? There are many providers for you choosing. If your budget is limited, you can use the tool in cloudorado.com to compare pricing between providers such as: Amazon EC2, Rack Space, Elastic Hosts, E24Cloud, etc.

Recently Google has joined to this market with Google Compute Engine (GCE). Hope cloudorado.com that will add GCE to their tool.

Remember that price is just one of many criteria to choose the best cloud server for you. Below are some other criteria for choosing your best server:

1. Price: should be in your budget. Use the above tool for choosing the best price.

2. Features / Capacity: the features / capacity of the server must meet your application / website.

3. Maintain Cost: you can use your application / website with minimum cost for changing your application / website. Cost for monitoring your application / website should be lowest.

4. Policy:  the contractual terms must be clear, no risks for you.

5. Backup: you can create a backup for your all applications easily.

6. Moving / Upgrade: you can move to other server or upgrade it without stopping any things.

Cheers,
Hung

Thursday, June 27, 2013

CSS: gradient background color for all browsers

Ultimate CSS Gradient Generator is a power tool can help you generate CSS code of gradient background color for all browsers.

It also supports to generate SCSS code.

Let enjoy it.

Friday, June 21, 2013

Add custom fields to JComments 2.3

If you use JComments 2.2, you can learn how to add custom fields in this article.
Below is the modification that article for JComments 2.3. The example is adding 2 custom fields Town and Accept Terms.

1. Firstly, add 2 these fields to #__jcomments (e.g. jos_jcomments):
ALTER TABLE jos_jcomments ADD COLUMN `town` varchar (255);
ALTER TABLE jos_jcomments ADD COLUMN `acceptterms` tinyint (1) DEFAULT 0;

2. Add them to the submit form in file \components\com_jcomments\tpl\default\tpl_form.php:
+Search the text comments-form-comment to find the following code:
<p>
<span>
<textarea id="comments-form-comment" name="comment" cols="65" rows="8" tabindex="5"></textarea>
</span>
</p>
+Add the following code after the above code:
<p>
<span>
<input type="text" name="town" value="" id="comments-form-town" />
<label for="comments-form-town" >Town</label>
</span>
</p>

<p>
<span>
<input class="checkbox" type="checkbox" name="acceptterms" value="0" id="comments-form-acceptterms" />
<label for ="comments-form-acceptterms" >Accept Terms of Use</label>
</span>
</p>

3. Add these fields to ajax file to send them to DB
+In addComment function of the file \components\com_jcomments\jcomments.ajax.php, search below code:
$comment->ip = $userIP;
+Add the following code after the above code:
$comment->town = isset($values['town'] ) ? $values ['town'] : '';
$comment->acceptterms = isset($values['acceptterms']) ? $values ['acceptterms'] : 0;

4. Modify _getCommentsQuery function in file \components\com_jcomments\models\jcomments.php to query these fields:
+Search the following code:
$query = "SELECT c.id, c.parent, c.object_id, c.object_group, c.userid, c.name, c.username, c.title, c.comment"
+Replace by the following code:
$query = "SELECT c.id, c.parent, c.object_id, c.object_group, c.userid, c.name, c.username, c.title, c.comment, c.town, c.acceptterms"

5. Add these fields to file \components\com_jcomments\tpl\default\tpl_comment.php to present them in the comments list:
+Search the following code:
<div class="comment-body" id="comment-body-<?php echo $comment->id; ?>"><?php echo $comment->comment; ?></div>
+Then add the following code after the above code:
<p>
<span class="comment-town" ><?php echo $comment->town; ?></span></br>
<span class="comment-accept" ><?php echo $comment->acceptterms ? 'Accepted' : 'Not accepted'; ?></span>
</p>

6. Add these fields to file  \administrator\components\com_jcomments\admin.jcomments.html.php to view them in backend:
+Search the following code:
<tr valign="top" align="left">
<td><label for="comment_text"><?php echo JText::_('A_COMMENT_TEXT'); ?></label></td>
<td><textarea class="editbox long" cols="25" rows="10" id="comment_text" name="comment"><?php echo $row->comment; ?></textarea></td>
</tr>
+Add the following code after above code:
<tr valign="top" align="left">
<td><?php echo JText::_('Town'); ?></td>
<td><input type="text" size="35" name="town" value="<?php echo $row->town; ?>" /></td>
</tr>
<tr valign="top" align="left">
<td><?php echo JText::_('Acceptterms'); ?></td>
<td><input type="text" size="35" name="acceptterms" value="<?php echo $comment->acceptterms ? 'Accepted' : 'Not accepted'; ?>" /></td>
</tr>

That's all. Now you can add your fields in your way.

Thursday, June 20, 2013

php round to .5 or .25

To round to .5:
$value = round($value * 2, 0) / 2;

To round to .25
$value = round($value * 2, 0) / 4;

Take it easy -:)

Friday, June 14, 2013

Windows: Change Remote Desktop Port

If you check Event Viewer of your server and see that there is many Audit Failure in Task Category Logon, you should change the port of remote desktop immediately.

Change port value (select Decimal when changing) of the registry PortNumber in:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp

PortNumber of Remote Desktop
After changing, restart your server.

To connect to your server with new port (e.g. 3333), use the following information:
Your_Server_Name:3333
OR:
Your_Server_IP:3333

Make sure the firewall of your computer doesn't lock this new port.

Friday, May 10, 2013

Web trends in 2013: HTML + CSS3 + Responsive


“HTML5 + CSS3 + Responsive“ is web trends in 2013 because the number of mobile users increases quickly, and become the center of web world today. So it is important to develop a web page that has:

  1. Flexibility to support many type of screen views, including phone, tablet, desktop and even a large TV screen
  2. Ability to support different browsers, e.g IE, FireFox, Chrome, Safari
  3. High integrity with other platforms or scripts, e.g. SQL, PHP, .Net, Java and Javascripts
  4. Sustainability for a longer period
  5. Search engine friendly

Below are some pictures to help explain the usage and features of HTML5, CSS3, and responsive designs.

HTML5 Past, Present & Future


CSS3 and Most Important Properties


What is Responsive Web Design


Hope you can understand what & why HTML + CSS3 + Responsive is so important for web technology in 2013 and future.

Monday, April 8, 2013

Solving Error 1001: Unable to get installer types

First let check if your PC has Windows installer service. If having, the reason is your build project on MS Visual Studio has Custom Action with the InstallerClass property set to true, but either no installer classes could be found in the setup.exe or the setup.exe could not be loaded due to missing dependencies.

There are 2 ways to solve this problem:
1. If you have MS Visual Studio projects. Rebuild your projects: make sure you have installer class in main project and select it on Custom Action (right click on the installer project, selecting View and then Custom Actions). Then correct reference Dlls.

2. If you don't have the installer project. Check missing Dlls by using fuslogvw.exe. Below is the guide for quick how to use fuslogvw.exe.

Find fuslogvw.exe tool:
-MS VS 2008: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\fuslogvw.exe
-MS VS 2010: C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\FUSLOGVW.exe, and C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\1033\flogvwrc.dll


Copy this tool to a folder on the target computer.
Create logging folder, e.g. c:\fuslog
Start FUSLOGVW.exe. Update the following settings:
    Log all binds to disk
    Enable Custom log path
    Custom lag path = c:\fuslog\
Finally, enable assembly binding logging in the registry by setting the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion to 1.

Click Refresh button in FUSLOGVW.exe and behold! A list of assembly binding events will be displayed here:


The individual events contain useful details:



Hope you can solve this error.

Saturday, March 16, 2013

Joomla: hide backend with secret key to enhance security

If your website uses Joomla, it is easy to try login your back-end at the address: <your_website>/administrator/

Bad guys can attack your back-end with some technique, e.g. Dictionary attack.

There are many solutions to protect your back-end. Here, I suggest a way with small change in the file: administrator/index.php. Let add the following code after require_once lines:


$session =& JFactory::getSession();
$passport = $session->get('passport');
if(!$passport || $passport != "passed")
{
$goent = JRequest::getVar('your_secret_var','','get','text');
if(!$goent || $goent != "your_secret_value")
{
// Redirect to homepage
header('Location:  ../index.php');
}
else
{
$session->set('passport', 'passed');
}
}

After adding this code, you must login at: <your_website>/administrator/index.php?your_secret_var=your_secret_value

Any attempt to access <your_website>/administrator/ will redirect to your home page.

Best wishes.





Sunday, February 17, 2013

Html image map: create multi-links in one image

Html image map will help you create multi-links on an image.

What is html image map?
Html image map is a way that allow you to define certain area to be linked within a single image on a web page. This means that, rather than having to link the whole image as one link, you can have lots of different links within that one image.


Here is a sample for the map tag:
<map name="map-name">
    <area shape="area shape"
    coords="area coordinates"
    href="area hyperlink" or nohref="nohref"
    target="hyperlink target"
    title="area title"
    alt="alternate text"/>
</map>
<img src="image-url" usemap="#map-name" />

For shape attribute (in area tag), it can be rect | circle | poly | default.


For coords attribute, below is a simple overview diagram for the coordinates.
Image Map Coordinates Overviews
How to calculate the coordinates?
Using Photoshop, first load the image into Photoshop, press F8 for the Info Panel to appear, move your cursor to centre of the circular logo and note down the coordinates.


Centre of Circle



We will also need to find the radius of the circle. By finding out the difference between the edge of the circle's coordinates and centre coordinates of the circle, or by using the rule tools in Photoshop. Either way will help you find out the radius of the circle.
Circle Radius
Now let's find the coordinates for a rectangular logo. You just have to find out the top left and bottom right coordinates of the rectangular logo. Using the same method above you will be able to find the coordinates easily.
Rectangular Coordinates
Once you have find out all the coordinates for each logo, now everything is easy. Just follow the attributes for the Map Tag listed above and enter all the coordinates for each of the shapes you have found.


<map name="logos">
    <area shape="circle" coords="68,56,33" href="http://www.stumbleupon.com/" title="StumbleUpon" alt="StumbleUpon" />
    <area shape="rect" coords="220,19,306,54" href="http://www.youtube.com/" title="Youtube" alt="Youtube" />
    <area shape="rect" coords="367,32,516,84" href="http://www.google.com/" title="Google" alt="Google" />
    <area shape="rect" coords="556,12,639,115" href="http://www.wikipedia.com/" title="Wikipedia" alt="Wikipedia" />
    <area shape="rect" coords="128,62,244,114" href="http://www.skype.com/" title="Skype" alt="Skype" />
    <area shape="rect" coords="301,103,444,136" href="http://www.yahoo.com/" title="Yahoo" alt="Yahoo" />
    <area shape="rect" coords="25,158,135,207" href="http://www.ebay.com/" title="eBay" alt="eBay" />
    <area shape="rect" coords="180,147,271,175" href="http://www.flickr.com/" title="Flickr" alt="Flickr" />
    <area shape="rect" coords="299,166,379,208" href="http://www.digg.com/" title="Digg" alt="Digg" />
    <area shape="circle" coords="500,184,32" href="http://wordpress.org/" title="Wordpress.org" alt="Wordpress.org" />
    <area shape="rect" coords="599,142,667,209" href="http://www.blogger.com/" title="Blogger" alt="Blogger" />
    <area shape="default" nohref="nohref" title="Default" alt="Default"/>
</map>


For custom shape link, you can try poly shape attribute. Just defining those important coordinates and it will form up a more precise Hot Spot area for the link.

Web tool to generate image map links:
If these above steps are too complex to you, you can use this online tool to generate html code for links on an image. It will let you select areas on the image, put link and give you html code. Here is the website:
www.image-maps.com


Friday, January 11, 2013

Using Windows commands to split & combine files

For big file, e.g. video, some times you need to split for transfering / uploading and combine them after downloading. Below are some usefull Windows commands for you.

1. Command to split a big file to smaller files (e.g. 512 MB):
#split -b 512m big_file_name

2. Command to combine small files (e.g. small_file1, small_file2, small_file3) to bigger file:
#copy /b small_file* big_file_name /b
Subscribe to RSS Feed Follow me on Twitter!