Archive for May, 2008

Unit Testing on Your Database

When unit testing on your database, you will run into a common problem.

Rolling back.

So you want to do some unit tests, and then you want to reset your database back to the nice squeaky clean version that doesn’t have half failed unit tests.

So how can you do this?

There are many ways to achieve this.

The best way I found (requires Win XP SP2 or Windows Server 2003) is to use Roy’s Unit Testing Rollback Attribute.  Simply inherit his class, add a "DataRollback" attribute, and you are good to go.  Using some complicated Interception logic and Enterprise Services (COM+) it rolls back all the database work that was done.  It’s super easy to implement.  Here is some sample code that shows you just how easy it is.  You just have to download XtUnit (an extension to NUnit) to do this. (Full source code available)

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using TeamAgile.ApplicationBlocks.Interception.UnitTestExtensions;
using NUnit.Framework;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
namespace DBTest
    /// Test roll back functionality.
    public class RollbackTest : ExtensibleFixture
        [Test, DataRollBack]
        public void TestInsert()
            //this method will be performed inside a COM+ transaction
            //this requires windows XP SP2 or better
            //Windows Server 2003 works as well.
            string strCnn = "your_conn_string";
            Guid random = Guid.NewGuid();
            string sqlI = string.Format(@"insert into log4net (message,date,thread,level,logger) values ('{0}',getdate(),'{1}','Debug','Test')", random.ToString(), System.Threading.Thread.CurrentThread.GetHashCode());
            SqlHelper.ExecuteNonQuery(strCnn, CommandType.Text, sqlI);
            string sqlS = string.Format(@"select count(*) from log4net where message='{0}'", random.ToString());
            int rowcount = (int)SqlHelper.ExecuteScalar(strCnn, CommandType.Text, sqlS);
            Assert.That(rowcount > 0, "Cannot find {0}", random.ToString());
This test passes successfully.  What does that mean? The insert and select worked perfectly fine.  After that, I did a query and found the database to be clean.  So the rollback worked too.
There are also other ways to skin this cat (i.e. to achieve this goal).  One is to use Spring Framework and extend their Unit Testing class (AbstractTransactionalSpringContextTests), and they will handle rolling back everything.  Here is an article on this topic, but unfortunately I was not able to make it work for me due to some odd reason.  Here’s hoping you have better luck.  If you don’t have any transactions, and your code is wired to use Spring, it’s still also very easy, you just need to call TransactionManager.Rollback.
You can also try to achieve this using Nested Transactions if you have existing transactions implemented via Spring.  But then you have to set up checkpoints and stuff like that. 
I have some other ideas on how to achieve this that I will post later, God willing.


This is a very shallow comparison of my experiences with PHP and ASP.NET
Don’t take this as a religious war or something, the idea is just some basic comparison.
Here is a summary: If you are choosing which technology to use to build an application, use .NET. You will get more bang for the buck. With the same effort you will be able to build a much more rich user interface. 
My Disclaimer: Keep in mind there are a lot of great libraries and tools for PHP which I never got to use, I just had a simple PSPad text editor and my handy PHP web site.  I really wanted some “Intellisense” style code completion but I could not get it to work with PHP since I couldn’t find a decent IDE (i.e. editor)
However, it all depends on your requirements. For example, if you are selling something that most of your customers will be on a shared linux hosting environment, then why would you use .NET ? A good example is the software Clipshare, which is a clone of Youtube. The sites purchasing this product are mainly shared hosting customers who have PHP but not .NET. And Mono (.NET port on Linux) is not yet stable or popular enough to use.
I did some PHP programming before I started doing .NET fulltime. Before then I couldn’t say much about it, but after working with .NET for a few years now, I have much to say.
.NET does a very good job in handling the whole life cycle. With PHP you have to do it manually.   For example, there is no such concept of “Postback” with PHP. This is such a basic thing that you can easily check with .NET to see if the page has been submitted and what button was pressed. For example if your “btnSubmit” was pressed, it will call btnSubmit_Click. With PHP, you have to do this manually. Not to mention how mish mashed your PHP page can be in terms of mixed code and style/HTML elements.

How about caching? I wanted to implement caching with PHP and I had a fun time, I had to check if the cached output file existed, and then if so, then check how old it is, and so on… Yeah okay again maybe there are some nice components already done for this, but I didn’t have to look very hard to do it with .NET, I simply added a CacheDependency on an XML file (or whatever the case was), and BOOM! It regenerated the file whenever necessary.
How about reusable components? With .NET you can create ASCX (Custom Controls) that you can place within a page that expose certain properties and the control itself maintains its state, can have buttons, etc, etc.

How about master pages (i.e. templates) in .NET? Again, super cool reusability! You can create pages with repeatable parts, with headers, footers, all sorts of fun stuff.

I can go on and on…  but in general, the more I use .NET, the more impressed I am with it. However, what makes it not-so-practical is how expensive Windows Server hosting is.  In summary .NET kicks butt!
Update Oct 8 2008

I wanted to add some more meat to this article based on the comments below

I mentioned that getting Windows Server hosting is more expensive.. However, lets look at this in perspective.  What’s more expensive – server cost, or development cost?  Development cost in most cases far outweighs any particular savings of a Windows license.  What this means is even if your application takes two or three times as long to write, then you have lost any potential savings from running a "free" linux box. 

Also, I would like to hear about how to unit test with PHP. 

.NET offers unit testing via many different frameworks, NUnit probably being the most popular right now.   I would like to know how can I unit test in PHP?  There is also an extension for NUnit available called NUnitAsp that allows me to test my interface.  Another notable extension for Nunit is an automatic database rollback.  SWEET!  More details to come as time goes by.

20% Extra Security is Enough To Stop Kiddie Hackers

Here’s a security problem for you.

How do we stop people from using brute force attacks on our logon page?
Well, simple… just add a captcha.

Well, umm.. captcha is already broken.  Even if it isn’t, they can hire someone overseas to sit there all day and crack away at it.. right ?
Well, umm… fine, so we’ll set up this security scanner, and add that vulnerability protector, and automatically ban this and that, and let’s do this.. and that, and this, and that, and so on, and so forth, until we have a fortress.

Tell you the truth.  Unless your site is heavily targetted, captcha is probably good enough.  In fact, my experiences is that you just put in 20% effort and you will stop 80% of the hackers (there’s that 80/20 rule again…!).  For example, I had a web server that was getting daily hack attempts on the ssh port (port 21).   I had done lots of security tightening on it.  For example, I disabled root login, I added an automatic email that was sent to me on root logon, and so on… As well I had a software installed that would ban them after a certain number of failed logins, and would send me an email.   This software was called BFD (Brute Force Detection).  After getting these daily hack attempts, I decided I had enough, and I changed the port to a random value (say 561).   Since that day, I haven’t received hardly one or two hack attempts.  Seems most hackers were the kiddy hackers that didn’t really bother to try hard enough.  A simple port scan would have revealed my SSH port.  However.. by putting in that 20% effort, I got rid of 80% of the losers.

I eventually re-enabled direct root logon, since I realized this simple step was enough.

Now if your site is going to be targetted by hackers, no matter what you do, catpcha or no captcha, IP blocking or not, if they want to get in, they will get in.  The best way to stop those hackers is to hire some l33t hackers yourself to try to break their way in and then block it.  You will need to do some security audits and close any open holes you might have.

But in the end, the idea is, just put in a little extra security, don’t just leave your login page open for brute force attacks, because you never know,….they might have already hacked your site (scary.. isn’t it?)

Update – I found a good example of this in action – take a look at this quote from EmailSpoofer.NET:

Your Javascript sucks, I can decode it in 5min, why is it so easy to decode?

All javascript can be decoded. Its a matter of how much time/resources you want to devote to it. However, in this case, the javascript isn’t meant to be difficult to be decoded by humans. It’s meant to be difficult to be decoded by spambots. That being said, if you see some improvements I could make to the javascript routine, feel free to send them to me. I’d love to incorporate them into the control. However, please don’t send me scripts that is someone else’s work. Please send your original. Thanks!


Keep in mind that the 20% is always increasing. Hackers get smarter over time, and so you need to keep up with this minimum 20%. Take a look at how I was hacked in Server Security and PHP Safe mode

Optimization WordPress Plugins & Solutions by W3 EDGE