Tracking outgoing links with Google Analytics

Normally, a link’s HTML code looks like the following.

<a href="http://ww2db.com">World War II History</a>

If you are using Google Analytics, you know that you can easily see what site is referring traffic to your site. But how do you use Google Analytics to track traffic flowing the other way? One way you can do so is by calling the ._trackPageview() method in Google Analytics’ pageTracker object. For example:

<a href="http://ww2db.com" onClick="javascript: pageTracker._trackPageview('/outgoing/ww2db.com');">World War II History</a>

Now whenever someone clicks on the World War II History link, it will be tracked as a normal visit to a particular content page. To see this data, log on to Google Analytics and go to Content, then Top Content, and finally search for all URLs containing the word “outgoing”. By the way, you can name these mock content URLs whatever you want. I chose to use the word “outgoing” because no other pages in my site contains the word “outgoing”, thus making it easy to distinguish between normal content and outgoing content.

Update

Updated code based on Google Analytics changes:

onclick="javascript: ga('send','pageview','/outgoing/ww2db.com');"

Recovering from MySQL *.MYI corruption

Personally, I experienced this with the Bugzilla software issue tracking software. The message I got on the browser screen is as follows.

Software error:

DBD::mysql::db selectrow_array failed: Can’t open file: ‘logincookies.MYI’ (errno: 145) [for Statement "SELECT profiles.userid, profiles.disabledtext FROM logincookies, profiles WHERE logincookies.cookie=? AND logincookies.userid=profiles.userid AND logincookies.userid=? AND (logincookies.ipaddr=? OR logincookies.ipaddr=?)"] at Bugzilla/Auth/Cookie.pm line 69

Bugzilla::Auth::Cookie::authenticate(‘Bugzilla::Auth::Cookie’, 5, 4928) called at Bugzilla/Auth/CGI.pm line 106

Bugzilla::Auth::CGI::login(‘Bugzilla::Auth::CGI’, 1) called at Bugzilla.pm line 74

Bugzilla::login(‘Bugzilla’) called at C:/bugzilla/buglist.cgi line 81

For help, please send mail to the webmaster (…@……), giving this error message and the time and date of the error.

To resolve the issue, I first stopped the MySQL database.

C:>net stop mysql
The MySQL service is stopping..
The MySQL service was stopped successfully.

Then, I issued the myisamchk.exe command as below to recover the table that became corrupted; for me, it was the logincookies.MYI file.

C:>c:mysqlbinmyisamchk.exe -r logincookies.MYI
- recovering (with sort) MyISAM-table 'logincookies.MYI'
Data records: 158
- Fixing index 1
- Fixing index 2

Once the recovering process was completed, I restarted the MySQL database.

C:>net start mysql
The MySQL service is starting.
The MySQL service was started successfully.

Once the MySQL restart is completed, the database was functioning properly once again, and my Bugzilla system was running without a hitch. Alternatively, I could have logged in to MySQL and issued the following SQL command to repair the corrupted table.

use bugzilla;
repair table logincookies.MYI;

Format Windows command line date

The need for me to format date in the Windows command line environment came up when I needed to write a batch file to automatically copy the latest copies of certain files in a large folder. The files are named in the format of ???YYYYMMDD.txt, which presented itself as one easy way for me to query for latest files.

Built in to Windows command line is the %date% variable, which displays the system date as follows based on my regional setting.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:>echo %date%
Wed 10/08/2008

Please note that your regional settings might be different. For example, for those in Australia, the date might be presented in a DD/MM/YYYY format rather than the typical US MM/DD/YYYY format. If this is the case, you may wish to adjust the code below accordingly.

To suit my needs, I need to format this date to YYYYMMDD. Knowing that %date%’s format is consistent in format, we can just parse it as a string.

C:>echo %date:~10,4%
2008

C:>echo %date:~4,2%
10

C:>echo %date:~7,2%
08

Bringing it together, I will have the YYYYMMDD format I am looking for.

C:>echo %date:~10,4%%date:~4,2%%date:~7,2%
20081008

Once again, you may need to adjust the above command based on your own regional settings.

Here is how I put this code in action in the form of a batch file that copied only the files with today’s date.

set backupcmd=c:windowssystem32xcopy.exe /c /d /e /h /r /y
set dt=%date:~10,4%%date:~4,2%%date:~7,2%
%backupcmd% C:stuff*%dt%.txt D:backupstuff

Oracle 11g database creation quick step-by-step guide

This is a simple step-by-step of how I created my main database in the Oracle 11g server running in a Linux environment. It is by no means comprehensive, but it may serve as a good starting point should you be looking for such a quick guide.

Increase Shared Memory Size

I am running Oracle Enterprise Linux, and on all Linux flavors, the total shared memory (shm) size is limited to 2gb. I am looking for a maximum size of 3gb, so I need to perform the following preparatory steps to set up a memory file system before setting up my database. You may or may not review this section.

[oracle@dbserver ~]$ su - root
Password:
[root@dbserver ~]# nano /etc/fstab

In nano (or your favorite editor), add or modify your entry for “/dev/shm” so that it looks like this:

[root@dbserver ~]# more /etc/fstab
...
tmpfs     /dev/shm     tmpfs     size=3g     0 0
...

At this point, you have the option of either running the following command to increase “/dev/shm” size to 3gb at runtime, or simply restart the server so that the change you have just made in fstab will take effect.

[root@dbserver ~]# mount -t shm tmpfs -o size=3g /dev/shm

Either after running “mount” or after restarting, “df -k” should reveal the following. If so, you are ready to set up the database. Note you should now use the “oracle” user instead of the “root” user.

[oracle@dbserver ~]$ dk -k
Filesystem   1K-blocks   Used   Available   Use%   Mounted on
...
tmpfs          3145728      0     3145728     0%   /dev/shm
...

Database Configuration Assistant (DBCA)

You may launch DBCA as follows.

[oracle@dbserver ~]$ dbca

Step 1: Operations — Choose “Create a Database”

Step 2: Database Templates — Choose the appropriate template. “General Purpose or Transaction Processing” is likely the one you will select.

Step 3: Database Identification — Set “Global Database Name” to “db_name.yorktel.com” and “SID” to “db_name”

Step 4: Management Options — Check “Configure Enterprise Manager”, check “Enable Alert Notifications”, and configure the SMTP server and email address.

Step 5: Database Credentials — Enter passwords for each system user, or choose “Use the Same Administrative Password for All Accounts” to use only one password.

Step 6: Storage Options — In my environment, I chose “File System”; your system might be different.

Step 7: Database File Locations — Since I chose “File System” in the previous step, in this current step I chose “Use Common Location for All Database Files” and set the path to “/u02/app/oracle/oradata”. Once the database is created, my database files will thus end up in “/u02/app/oracle/oradata/db_name”.

Step 8: Recovery Configuration — Check “Specify Flash Recovery Area” and set the “Flash Recovery Area Size”; in my environment, I use the very large value of “81920” (in mb) because I have the space available to waste. In this step, also check “Enable Archiving”.

Step 9: Database Content — No change necessary in my case

Step 10: Initialization Parameters — Under “Memory” tab, set “Memory Size (SGA and PGA)” to 3072mb (which is 3gb); if you cannot move beyond this step due to the 2gb limitation, please see the first section of this guide. Knowing my environment and the high number of individual user sessions, under “Sizing” tab, I changed the “Processes” parameter to 220 to suit my environment’s needs. I then clicked on “All Initialization Parameters” and “Show Advanced Parameters” to update/confirm the following; you may use the list for reference, but you may need to do different configurations for your environment.

  • db_flashback_retention_target: I set it to “5760” for setting up the flashback database later
  • db_unique_name: I set this to “unique_db_name”
  • memory_max_target: I set this to “3G”
  • processes: I confirmed this is “250”
  • standby_file_management: I set this to “AUTO”
  • undo_management: I set this to “AUTO” for setting up the flashback database later
  • undo_retention: I set this to “3600” for setting up the flashback database later

Step 11: Security Settings — No change necessary in my case

Step 12: Automatic Maintenance Tasks — No change necessary in my case

Step 13: Database Storage — You should confirm that the file locations are correct

Step 14: Creation Options — Make appropriate selections and “Finish” the DBCA process

The “Finish” button starts the database creation process.

Database Backup with Enterprise Manager

Once DBCA database creation is completed, the database will be set up and will be available for use. At this point, I logged on to Enterprise Manager to perform some final set up items regarding database backup. Again, this may or may not be fitting with your requirements, but it may present a good reference for you to review. To go into Enterprise Manager (EM), go to the URL “https://dbserver:1158/em/” and log on as sysdba.

Once I got into EM, I went to the “Availability” tab and clicked on “Recovery Settings”. I checked “ARCHIVELOG Mode” and changed the first archive log file destination to a path I prefer, such as “/u02/app/oracle/oradata/flash/db_name”. I checked “Enable Flashback Database” and restarted the database for this to take effect.

After the database was restarted, I logged back into EM (again as sysdba), I returned to “Availability” tab, and clicked on “Schedule Backup”. I clicked on the “Schedule Oracle-Suggested Backup” button and chose “Disk” in step 1 and configured the date and time in step 3. I set it up so that it runs a full database backup regularly during periods that typically sees low usage. The RMAN script hidden behind this GUI is the following.

run {
allocate channel oem_disk_backup device type disk;
recover copy of database with tag 'ORA$OEM_LEVEL_0';
backup incremental level 1 cumulative  copies=1 for recover of copy with tag

'ORA$OEM_LEVEL_0' database;
}

Next, again in “Availability”, I clicked on “Manage Current Backups” and scheduled “Crosscheck All”, “Delete All Obsolete”, and “Delete All Expired” jobs so that obsolete and expired backup sets will be removed regularly in free up space for current backup sets; note to schedule it to run regularly, you should choose the “repeating” radio button. The RMAN scripts hidden behind the GUI are as follows.

-- Crosscheck
CROSSCHECK BACKUPSET;
CROSSCHECK COPY;
-- Delete Obsolete
DELETE NOPROMPT OBSOLETE;
-- Delete Expired
DELETE NOPROMPT EXPIRED BACKUP;
DELETE NOPROMPT EXPIRED COPY;

Oracle 11g Data Guard switchover/failover quick step-by-step guide

Assumptions

In this sample, it is assumed that you already have your Oracle 11g primary database functioning, and have already set up a Oracle 11g physical standby database, and can access them using the Data Guard Command-Line Interface (dgmgrl) utility. The current primary database will be referred to as “orcl1” and the current physical standby database will be referred to as “orcl2”. The SID for both primary and standby is “orclsid”. The current primary host is “host1” and the standby host is “host2”.

Switchover/Failover Procedures

First, launch the Data Guard Command-Line Interface and connect to the database.

[oracle@host1 ~]$ dgmgrl
DGMGRL for Linux: Version 11.1.0.6.0 - Production

Copyright (c) 2000, 2005, Oracle. All rights reserved.

Welcome to DGMGRL, type "help" for information.
DGMGRL> connect sys@orcl1
Password:
Connected.

Then, issue switchover or failover command depending on your situation. Generally, a switchover is used to willingly pass the role of the primary database to the physical standby database (or, one of the physical standby databases), while a failover is typically done only when a major problem prevents you from normally using the primary database. Below is what you may see when you perform a switch over.

DGMGRL> switchover to orcl2
Performing switchover NOW. Please wait...
Operation requires shutdown of instance "orclsid" on database "orcl1".
Shutting down instance "orclsid"...
ORA-01109: database not open

Database dismounted.
ORACLE instance shut down.
Operation requires shutdown of instance "orclsid" on database "orcl2".
Shutting down instance "orclsid"...
database not mounted
ORACLE instance shut down.
Operation requires startup of instance "orclsid" on database "orcl1".
Starting instance "orclsid"...
ORACLE instance started.
Database mounted.
Operation requires startup of instance "orclsid" on database "orcl2".
Starting instance "orclsid"...
ORACLE instance started.
Database mounted.
Switchover succeeded. New primary is "orcl2"

And in the case of a failover…

DGMGRL> failover to orcl2
Performing failover NOW, please wait...
Failover succeeded, new primary is "orcl2"

To confirm Data Guard switchover or failover has completed successfully, log in to Data Guard Command-Line Interface and issue the “show configuration” command.

[oracle@host2 ~]$ dgmgrl
DGMGRL for Linux: Version 11.1.0.6.0 - Production

Copyright (c) 2000, 2005, Oracle. All rights reserved.

Welcome to DGMGRL, type "help" for information.
DGMGRL> connect sys@orcl2
Password:
Connected.
DGMGRL> show configuration

Configuration
  Name:                DRSolution
  Enabled:             YES
  Protection Mode:     MaxAvailability
  Databases:
    orcl2 - Primary database
    orcl1 - Physical standby database

Fast-Start Failover: DISABLED

Current status for "DRSolution":
SUCCESS

The above sample shows what the display would look like after a switchover. In the case of a failover, the physical standby database will show as “disabled” as below.

DGMGRL> show configuration

Configuration
  Name:                DRSolution
  Enabled:             YES
  Protection Mode:     MaxAvailability
  Databases:
    orcl2 - Primary database
    orcl1 - Physical standby database (disabled)

Fast-Start Failover: DISABLED

Current status for "DRSolution":
Warning: ORA-16608: one or more databases have warnings

As an additional note, as the former physical standby database of orcl2 is now operating as your new primary database, you may wish to use Enterprise Manager to help you manage orcl2. If that is the case, you will need to perform the following to recreate the DBControl repository to enable Enterprise Manager on host2.

[oracle@host2 ~]$ emca -config dbcontrol db -repos recreate
STARTED EMCA at Sep 29, 2008 2:02:40 PM
EM Configuration Assistant, Version 11.1.0.5.0 Production
Copyright (c) 2003, 2005, Oracle.  All rights reserved.

Enter the following information:
Database SID: orclsid
Database Control is already configured for the database orclsid
You have chosen to configure Database Control for managing the database orclsid
This will remove the existing configuration and the default settings and perform a fresh configuration
Do you wish to continue? [yes(Y)/no(N)]:

At this point, you should have your former physical standby database orcl2 running fully as your primary database server.

After a failover, the physical standby database will not be present in your current setup. In the case that the failed database could be brought back, issue the following command in Data Guard Command-Line Interface to reinstate the failed database as a physical standby database.

DGMGRL> reinstate database orcl1
Reinstating database "orcl1", please wait...
Operation requires shutdown of instance "orclsid" on database "orcl1"
Shutting down instance "orclsid"...
Database closed.
Database dismounted.
ORACLE instance shut down.
Operation requires startup of instance "orclsid" on database "orcl1"
Starting instance "orclsid"...
ORACLE instance started.
Database mounted.
Continuing to reinstate database "orcl1" ...
Operation requires shutdown of instance "orclsid" on database "orcl1"
Shutting down instance "orclsid"...
ORA-01109: database not open

Database dismounted.
ORACLE instance shut down.
Operation requires startup of instance "orclsid" on database "orcl1"
Starting instance "orclsid"...
ORACLE instance started.
Database mounted.
Continuing to reinstate database "orcl1" ...
Reinstatement of database "orcl1" succeeded

Performing 301 Redirect with Apache, IIS, PHP, and others

Apache

If you use Apache with the mod-rewrite module installed, 301 Redirect may be set up by editing your .htaccess file found at the root directory of your website. The following is a sample of what you might add to your .htaccess file; in this example, we are redirecting any visits to /blah/pictures.html to its new location, http://ww2db.com/photo.php.

Redirect 301 /blah/pictures.html http://ww2db.com/photo.php

Sometimes you may encounter a situation where you changed technology of your platform, for example, from static HTML pages to dynamic PHP pages. With the sample code below, you can redirect all HTML pages to PHP pages by the same name.

RedirectMatch 301 (.*).html$ http://ww2db.com$1.php

Looking to use .htaccess to redirect an entire site because you have moved from one domain to another? This is what you want to do:

Redirect 301 / http://ww2db.com/

PHP

If your site’s pages are made of PHP files, redirection is fairly easy. If you had moved the /old/pictures.php page to the new location of http://ww2db.com/photo.php, modify the /old/pictures.php page by adding the following PHP snipped on the top of the code, ie. before any HTML code is written to screen.

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://ww2db.com/photo.php");

IIS

If you using Microsoft’s Internet Information Services (IIS), perform the following steps to do a 301 Redirect.

  • Right click on “My Computer”, go to “Manage”, “Services and Applications”, and then “Internet Information Services (IIS) Manager”.
  • Under “Web Sites”, look for the particular folder or file you wish to redirect. Right click and select “Properties”.
  • Click the “A redirection to a URL” radio button. In the bottom section that had just appeared, and enter the new URL in the “Redirect to:” text box, and make sure to check “A permanent redirection for this resource” checkbox.
  • Click OK to complete the process.

ASP and ASP.NET

Classic Active Server Pages (ASP) web pages can be redirected in a method very similar to PHP above.

Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://ww2db.com/photo.php"

ASP.NET redirect code is very similar to its ASP predecessor’s.

private void Page_Load(object sender, System.EventArgs e) {
  Response.Status="301 Moved Permanently";
  Response.AddHeader("Location","http://ww2db.com/photo.php");
}

JSP

Redirection for Java Server Pages (JSP), again, is similar to the other scripting languages we have seen above.

response.setStatus(301);
response.setHeader("Location","http://ww2db.com/photo.php");
response.setHeader("Connection", "close");

CGI/Perl

If you are using Perl-based CGI code, this is the code you may wish to deploy to perform a 301 Redirect.

$q=new CGI;
print $q->redirect("http://ww2db.com/photo.php");

Cold Fusion

ColdFusion pages can be redirect also by working with the header.

<.cfheader statuscode="301" statustext="Moved permanently">
<.cfheader name="Location" value="http://ww2db.com/photo.php">

Ruby on Rails

Not surprisingly, Ruby on Rails pages are redirected in a very similar manner.

def old_action
headers["Status"]="301 Moved Permanently"
redirect_to "http://ww2db.com/photo.php"
end

Convert text to upper or lower case

To do so, simply make use of the toUpperCase() or toLowerCase() methods. For example:

<input type="text" name="myField" id="myField" size="20" onKeyup="javascript:this.value=this.value.toUpperCase();"> : To Upper

<input type="text" name="myField" id="myField" size="20" onKeyup="javascript:this.value=this.value.toLowerCase();"> : To Lower

Below is the working sample:

 To Upper

 To Lower

If you do not wish to run it for each key-up such as in this example, try the onChange event, which will only fire when the user leaves the input field.

Display Oracle instance uptime

Please note that, this query makes use of a v$ table, thus keep in mind you must be logged in as a DBA.

select instance_name,to_char(startup_time,'mm/dd/yyyy hh24:mi:ss') as startup_time from v$instance;

Your output should look something like that following:

INSTANCE_NAME    STARTUP_TIME
---------------- -------------------
orcl01           08/03/2008 00:23:08

Remove unwanted line feeds in your data with Oracle SQL

To remove these line feeds that you do not need, you will need to make use of the chr() function built-in to Oracle, which allows you to find special ASCII characters. Consider the case that a product’s description may contain line feeds such as the following:

This is an amazing product.
It removes stains from your clothing, restoring crisp colors as if fresh from the store.
Buy it today!

select 
replace(
  replace(
    replace(
      product_description
    ,chr(10),' ') -- replace new lines with spaces
  ,chr(13),' ') -- replace carriage returns with spaces
,'  ',' ') as product_description -- cleans up double-spaces
from products
where product_id=1;

You should see that the line feeds are removed in the end result.

This is an amazing product. It removes stains from your clothing, restoring crisp colors as if fresh from the store. Buy it today!

Note that there is a replace() function that changes double-spaces to single-spaces. This may be needed because we may run into the case where there might be a trailing space at the end of a line, immediately before a line feed, which will become a double-space and may mess up your spacing slightly.

Export Oracle synonyms to text file

This is achieved by using the sys.dba_synonyms table, which means these queries must be done using an account with proper privileges. Note the output file has the extension .sql, which suggests that it can be run directly from SQL*Plus as part of an automated script, if necessary.

set linesize 256;
spool c:oracleSynonyms.sql;

select 'create or replace '|| decode(owner,'PUBLIC','public ',null) ||  
'synonym ' || decode(owner,'PUBLIC',null, lower(owner) || '.') ||  
lower(synonym_name) || ' for ' || lower(table_owner) || '.' || lower(table_name) || decode(db_link,null,null,'@'||db_link) || ';'
from sys.dba_synonyms 
where table_owner not in('SI_INFORMTN_SCHEMA','SYS','SYSTEM','ORDSYS','XDB','CTXSYS','DMSYS','EXFSYS','MDSYS','SYSMAN','WKSYS','WMSYS')
order by owner, table_name;

spool off;