programming.torensma.net: Code Snippets

CakePHP: catching error in Model->query()

In my recent CakePHP application I use some custom SQL queries that I fire at the database using the $model->query($sql) syntax. Works great, until you have an error in your $sql. I tried the obvious error handling with try … catch:

try {
  $this->Model->query('INSERT INTO model WHERE id=invalid');
} catch (exception $ex) {
  // exception never happens
}

But the CakePHP Debugger class already catches the error and does it’s handling; which is writing the error to the browser. In my case I need to act upon an error.

After some trial and error (including hacking the core Cake files, which is really dirty) I came up with this: the Cake Debugger class set an error handler using set_error_handler('someErrorHandlingRoutine'). So i made my own error handing routine, borrowing some from the Debugger class:

class MyModel {
  function handleError($code, $description, $file = null, $line = null, $context = null) {
    if (error_reporting() == 0 || $code === 2048 || $code === 8192) {
      return;
    }

    // throw error for further handling
    throw new exception(strip_tags($description));
  }
}

Now before calling $model->query($sql) I set my custom error handler:

// set error handler in controller
set_error_handler(array($this, 'handleError'));

try {
  // execute dangerous sql
  $this->Model->query($sql);
} catch (exception $ex) {
  // custom error handling here...
}

What it does is simple and ellegant; throw an exception. Now my $model->query code can be wrapped in a try…catch block and if an exception happens I can act on it.

How to: Check if a Microsoft SQL-server database exists?

Here’s an easy, single line statement to check if a database exists in the current SQL-server instance:

IF db_id('db_name') IS NOT NULL

First post from iPhone

Hi all, this is my first post from my iPhone. I’m using the WordPress 2.0 iPhone app (make sure XML-RPC is enabled in your WordPress back-end). Even adding images from the iPhone Camera Roll is easy peasy.

Compute hash of a file

Computing the hash value of a file is quite strait forward. I use the routine below. It opens the file, specifies the hash-algorithm to use and returns the hash of the file. If you rather use MD5 hashes, just change hashAlgorithm into MD5CryptoServiceProvider.

Public Function ComputeFileHash(ByVal fileName As String) As String

  Dim hashAlgorithm As New System.Security.Cryptography.SHA1CryptoServiceProvider()

  Using stmcheck As System.IO.FileStream = System.IO.File.OpenRead(fileName)

    Dim hash As Byte() = hashAlgorithm.ComputeHash(stmcheck)
    Dim computed As String = BitConverter.ToString(hash).Replace("-", "")

    Return computed

  End Using

End Function

SHA1 hashes typically produce 160-bit (20 bytes) messages (16 bytes for MD5). If you want to store the hash value in a database table, make sure the field is wide enough to prevent data from getting truncated. By default the ComputeHash method returns the bytes separated by a hyphen (-). To save space I opted to remove these.

Icon Finder, the Google for icons

1255430950_old-edit-findHere’s a very useful tool: http://www.iconfinder.net/

It allows you to search for icon, and it returns a lot of high quality images. Recommended!

How to: Get the name of the running SQL-server instance

Here’s a script to retrieve the name of the currently running SQL Server instance:

SELECT @@SERVERNAME AS 'ServerName'

Resultset:

ServerName
---------------------------
DEV-SQL

(1 row(s) affected)

SQL-server: Get current database name

It can sometimes be handy to know in which database you are working. To get the name of the current database you can use a simple script:

SELECT DB_NAME() AS DataBaseName

Resultset:

DatabaseName
------------------------
NorthWind

(1 row(s) affected)

Am I running as a 32 or 64-bit application?

Here’s an easy way to determine if a .NET application is running as either 32 or 64-bit  application.

VB

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  If IntPtr.Size = 8 Then
    Response.Write("64-bit")
  ElseIf IntPtr.Size = 4 Then
    Response.Write("32-bit")
  End If
End Sub

C#

protected void Page_Load(object sender, EventArgs e)
{
  if (IntPtr.Size == 8)
  {
    Response.Write("64-bit");
  }
  else if (IntPtr.Size == 4)
  {
    Response.Write("32-bit");
  }
}

1,000 free icons

transmitAs a developer you’re probably familiar with the FamFamFam icon collection. It has certainly served me well over the years. But even though FamFamFam is great, there’s always room for improvement. That’s why you should check out the new FatCow collection, comprised of no less than 1,000 icons in both 16×16 and 32×32 high quality PNG files.

Purge OpenX statistics tables

logo_openxOpenX is a great tool for displaying ads on your website. But there is a small issue I’ve been wanting to address: statistics data. OpenX gathers a lot of data about clicks and impressions of your banners. While this can be very helpful, it also puts a strain on the database. And as I use Google Adsense as my main ad source, I don’t really need the OpenX stats because Google does a great job of keeping tabs on things.

So I had a look at the OpenX tables. In my case there were 3 tables with a lot of records (10,000+): xopen_data_intermediate_ad, xopen_data_summary_ad_hourly and xopen_data_summary_zone_impression_history. From what I found on different forums I learned that the _data_ tables are used for statistics, so I figured it would be fairly safe to empty them. To be on the safe side, I decided to delete records older than 1 month, you may want to adjust this for your particular situation.

Anyway, here are the queries I used to purge my tables:

DELETE FROM xopen_data_intermediate_ad
WHERE interval_end < DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
DELETE FROM xopen_data_summary_ad_hourly
WHERE date_time < DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
DELETE FROM xopen_data_summary_zone_impression_history
WHERE interval_end < DATE_SUB(CURDATE(), INTERVAL 1 MONTH);

Just for good measure a little disclaimer:
USE THIS AT YOUR OWN RISK! I HAVE USED IT IN MY PRODUCTION ENVIRONMENT, BUT I CAN GIVE NO GUARANTEE THAT IT WILL WORK IN YOURS. TESTED WITH OPENX 2.8.1

Error message 401.2.: Unauthorized: Logon failed due to server configuration. (IIS7)

After installing Windows 7 my ASP.NET application displayed an Access is deniederror. The complete error message was:

Error message 401.2.: Unauthorized: Logon failed due to server configuration.  Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server.  Contact the Web server’s administrator for additional assistance.

My application makes use of Windows Authentication and impersonation. For this IIS needs to support Digest Authentication. In the default IIS7 installation neither Windows Authentication not Digest Authentication is installed.

To turn those features on, go to Control Panel -> Programs -> Turn Windows features on or off -> Internet Information Services ->World Wide Web Services -> Security.

Now check the authentication methods needed. Now restart both IIS and the IIS Management Console. After re-opening the IIS7 management console, navigate to your site, open Authentication and enable the authentication methods here also.

You should now be able to login to your ASP.NET application using your Windows account.

iis7-authentication-settings

HTTP Redirect using htaccess

To redirect all incoming traffic to a new site and send an http status code indicating that the content has moved permanently, use the following snippet in your .htaccess file:

 RedirectMatch 301 ^(.*)$ http://www.mynewsite.com/

The 301 code is the status for permantly moved content. The regex ^(.*)$ matches all urls and finally http://www.mynewsite.com/ specifies where visitors must be redirected to.

Redirect using PHP

If you can’t use .htaccess or are reluctant to do so, then PHP can also to the job. The following lines send a 301 status code and redirect to the client’s browser:

header("Status: 301");
header("Location: http://www.mynewsite.com/");
exit;

7 signs your UI was created by a programmer

Are you a programmer? Then you might to read these 7 signs your UI was created by a programmer. No more excuses next time!

Project name generator

Having trouble coming up with a suitable project name? Try this project name generator and you can get back to work.

Here are some examples:

  • Tidy Firecracker
  • Rainbow Uranium
  • Severe Tungsten
  • Nocturnal Temple

Select column names from a Microsoft SQL-Server table

sql_server_2005I’ve posted a snippet before that allows you to select a list of tables (or views, stored procedures, etc) from a SQL-Server database. It would be only logical to also have a snippet that allows you to select the columns in the table you’re interested in. The following piece of SQL code does just that.

The statement has 2 variable in the WHERE clause: sysobjects.xtype=’U‘ and sysobjects.name=’MyTableName’. Obviously you need to substitute MyTableName with the table you’re interested in.

The valid values for xtype can be found in my previous post.

SELECT table_name=sysobjects.name, column_name=syscolumns.name,
datatype=systypes.name, length=syscolumns.length
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U'
AND systypes.name <> 'sysname'
AND sysobjects.name='MyTableName'
ORDER BY sysobjects.name,syscolumns.colid