How To: Using symfony to add a join between tables

1. simple join two tables

purpose:
generate sql like:

select * from photo p
    left join artist a on p.artist_id = a.artist_id
      where a.genre = "something" and p.genre = "something"

code:

if(!CriteriaUtil::hasJoin($criteria, ArtistPeer::TABLE_NAME)){
    $criteria->addJoin(PhotoPeer::ARTIST_ID, ArtistPeer::ARTIST_ID, Criteria::LEFT_JOIN);
}
$criteria->add(ArtistPeer::GENRE, $genre);    
$criteria->add(PhotoPeer::GENRE, $genre);

2. join two tables, add AND OR between conditions
purpose:
generate sql like:

select * from photo p
    left join artist a on p.artist_id = a.artist_id
      where (a.genre = "some" or p.genre="something")
        and a.name = "something"

code:

if(!CriteriaUtil::hasJoin($criteria, ArtistPeer::TABLE_NAME)){
   $criteria->addJoin(PhotoPeer::ARTIST_ID, ArtistPeer::ARTIST_ID, Criteria::LEFT_JOIN);
}
$criteria->add(ArtistPeer::GENRE, $genre);
$c = $criteria->getCriterion(ArtistPeer::GENRE);
if($c != null){
   $c->addOr($criteria->getNewCriterion(PhotoPeer::GENRE, $genre));
}
$criteria->add(ArtistPeer::NAME, $name);

Note:
It’s a good habit to check if we have joined the table already. to check this, you can use
the following util class, it get all the joined tables, and check if the table exists in them.

class CriteriaUtil{
    public static function hasJoin($c, $table_name){
        $joins = $c->getJoins();
        if($joins != null){
            foreach($joins as $join){
                if($join->getRightTableName() == $table_name){
                    return true;
                }
                if($join->getLeftTableName() == $table_name){
                    return true;
                }
            }
        }
        return false;
    }
}

WLW: QI for IEnumVARIANT failed on the unmanaged server.

It maybe popup an error message to say that “QI for IEnumVARIANT failed on the unmanaged server” when open the Windows Live Writer.

After search on google, I found the resolution is import some settings into registry.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{00020404-0000-0000-C000-000000000046}]
@="IEnumVARIANT"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{00020404-0000-0000-C000-000000000046}NumMethods]
@="7"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{00020404-0000-0000-C000-000000000046}ProxyStubClsid]
@="{00020421-0000-0000-C000-000000000046}"

[HKEY_LOCAL_MACHINESOFTWAREClassesInterface{00020404-0000-0000-C000-000000000046}ProxyStubClsid32]
@="{00020421-0000-0000-C000-000000000046}"

You can also download the file here, unzip and import it to your registry.

How To: Clear cache for symfony

Original article: http://www.symfony-project.com/book/1_0/18-Performance

Clearing Selective Parts of the Cache

During application development, you have to clear the cache in various situations:

  • When you create a new class: Adding a class to an autoloading directory (one of the project’s lib/ folders) is not enough to have symfony find it automatically. You must clear the autoloading configuration cache so that symfony browses again all the directories of the autoload.yml file and references the location of autoloadable classes–including the new ones.
  • When you change the configuration in production: The configuration is parsed only during the first request in production. Further requests use the cached version instead. So a change in the configuration in the production environment (or any environment where SF_DEBUG is turned off) doesn’t take effect until you clear the cached version of the file.
  • When you modify a template in an environment where the template cache is enabled: The valid cached templates are always used instead of existing templates in production, so a template change is ignored until the template cache is cleared or outdated.
  • When you update an application with the sync command: This case usually covers the three previous modifications.

The problem with clearing the whole cache is that the next request will take quite long to process, because the configuration cache needs to be regenerated. Besides, the templates that were not modified will be cleared from the cache as well, losing the benefit of previous requests.

That means it’s a good idea to clear only the cache files that really need to be regenerated. Use the options of the clear-cache task to define a subset of cache files to clear, as demonstrated in Listing 18-14.

Listing 18-14 – Clearing Only Selective Parts of the Cache

// Clear only the cache of the myapp application
symfony clear-cache myapp

// Clear only the HTML cache of the myapp application
symfony clear-cache myapp template

// Clear only the configuration cache of the myapp application
symfony clear-cache myapp config

You can also remove files by hand in the cache/ directory, or clear template cache files selectively from the action with the $cacheManager->remove() method, as described inChapter 12

Note:

1. We can use $cacheManager->remove() to clear cache after we deployed a new version product.

2. write code to generate models from database, and then call $cacheManager->remove() to clear cache.

How To: Enable Mysql binary log

#server-id       = 1
log-bin         = /var/log/mysql/mysql-bin.log

#if you set the expire_logs_days = x var in the [mysqld] section of your my.cnf it will automatically rotate your bin logs after x days.
expire_logs_days = 30

#it will create a new log file when the current file reach the specified size.
max_binlog_size = 100M

How To: using bash script to backup MySql

Create a file backup_db.sh, and paste the following contents:

#get the first parameter as the database name
DATABASE=$1

#if no database specified, then you can set the default one
if [ -z $DATABASE ]; then
    DATABASE=default_database_name_here
fi

#mysql user and password to backup the database.
MYSQLUSER=mysql_user
MYSQLPWD=mysql_password
    
#path to backup
ARCHIVEPATH=~/backup/db_backup
DATE=`date +%Y%m%d`
YEAR=`date +%Y`
MONTH=`date +%m`
FOLDER_MONTH=$ARCHIVEPATH/$YEAR$MONTH
    
if [ ! -d $FOLDER_MONTH ]; then
    echo "mkdir $FOLDER_MONTH"
    mkdir $FOLDER_MONTH
fi
    
# Backup
echo "mysqldump -u$MYSQLUSER -p$MYSQLPWD $DATABASE | gzip $FOLDER_MONTH/$DATABASE-$DATE.sql.gz"
mysqldump -u$MYSQLUSER -p$MYSQLPWD $DATABASE | gzip $FOLDER_MONTH/$DATABASE-$DATE.sql.gz

and you can add the script to cron job under *nix and schedule under windows:

*nix:

Save the following text in file: db_backup.at

10 * * * * ~/backup/backup_db.sh databasename

and call

crontab db_backup.at

You need to change the period to run the script for your business, e.g. each day, each week etc.

Add two ips to one NIC in ubuntu

edit file: /etc/network/interfaces

the original content should be something like:

# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1
    
# dns-* options are implemented by the resolvconf package, if installed
dns-nameservers 192.168.0.1

add the following settings in the file:

auto eth0:1
iface eth0:1 inet static
address 192.168.0.6
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1

# dns-* options are implemented by the resolvconf package, if installed
dns-nameservers 192.168.0.1

run command in root mode:

/etc/init.d/networking restart

that’s all. you can run ifconfig to check if it works.

I had tested it under ubuntu 6.10.

type redefinition Error after Import ADO in vc++

It is important to invoke ADO correctly in your program, or you can have compiler errors. The following code demonstrates the correct way to use #import with Msado10.dll the MSADO15.dll:

#import <msado15.dll>
no_namespace
rename("EOF", "adoEOF")

error C2011: ‘EditModeEnum’ : ‘enum’ type redefinition
error C2011: ‘LockTypeEnum’ : ‘enum’ type redefinition
error C2011: ‘FieldAttributeEnum’ : ‘enum’ type redefinition
error C2011: ‘DataTypeEnum’ : ‘enum’ type redefinition
error C2011: ‘ParameterDirectionEnum’ : ‘enum’ type redefinition
error C2011: ‘RecordStatusEnum’ : ‘enum’ type redefinition

Here’s the original solution in MSDN:
http://support.microsoft.com/kb/169496/EN-US/

Add Command here to right button click in explore (Windows XP)

Add Command here to right button click in explore (Windows XP)

Cmd Here

  1. Download the file and unzip the file CMDHere.reg.
  2. Double click it to import into registry,
  3. Right click on any folder, you’ll see there’s a menu which is “Command here”,
  4. Click it, you’ll get into the cmd window with the current path is which you selected.

Or you can import the settings manually.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt]
@="Command Prompt"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt\command]
@="Cmd.exe /k pushd %L"

Use AbstractTransactionalSpringContextTests to rollback NUnit test case automatically

I have two test cases: UserTest and CustomerTest, both of them extend the AbstractTransactionalSpringContextTests class and using the same config file, so I wrote a BaseSpringTest class:

public class BaseSpringTest : AbstractTransactionalDbProviderSpringContextTests
{
    static protected string ctxName="application_context.xml";
    static protected string[] configlocation = new string[]{"assembly://test/test.config/" + ctxName};

    protected override string[]ConfigLocations
    {
        get
        {
            return configlocation;
        }
    }
}

public class UserTest : BaseSpringTest
{
    //test case ...
}

public class CustomerTest : BaseSpringTest
{
    //test case ...
}

When I run the tests, the first one runs ok, but the second one throws an exception:

Spring.Objects.Factory.ObjectCreationException : 
        Error creating object with name 'xxxService' defined in 
        'assembly [Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [test.config.Service.xml]' :
        Initialization of object failed : Duplicate type name within an assembly.

I traced into AbstractSpringContextTests class and found that it’s using a hashtable to cache the loaded context, but the hashtable isn’t a static field: Continue reading “Use AbstractTransactionalSpringContextTests to rollback NUnit test case automatically”

Could not load file or assembly ‘ADODB, Version=7.0.3300.0

Could not load file or assembly ‘ADODB, Version=7.0.3300.0

When run cc.net to build and test the web project, it throws an exception:

Could not load file or assembly 'ADODB, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

after a research on the internet, found the solution:

Copy the gacutil.exe (D:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin) to the destination pc.

Copy adodb.dll(D:\Program Files\Microsoft.NET\Primary Interop Assemblies) to the destination pc.
run gacutil /i adodb.dll to register the adodb to the gac.

Everything is ok now.