Brian Hartsock's Blog

NHibernate Connection Release Modes

by bhartsock on Dec.17, 2009, under Uncategorized

Some team members and I spent the better part of a few hours today researching a really weird bug we were seeing with our data access code built on NHibernate.

The basic symptoms were a duplicate key violation on a unique column in a table. This only happened under decent load, so reproducing in dev was pretty hard. To make matters more interested, it only happened with NHibernate 2.0. We started looking at MySQL logs and saw the following.

INSERT (value, unique_value) some_table VALUES ('some_value', 'some_unique_value');
-- Auto-increment ID column gets set to 10
SELECT LAST_INSERT_ID()
-- Returns 9
UPDATE unique_value='some_unique_value' AND value='other_value' WHERE id=9
-- Duplicate key exception because unique constraint is violated

Yes, SELECT LAST_INSERT_ID() was returning the wrong value. After digging through the NHibernate source code, it became pretty apparent what was happening. We weren’t using transactions (because the DB is MyISAM) and we found the following code.

// (Some ConnectionManager code)
public void AfterTransaction()
{
	if (IsAfterTransactionRelease)
	{
		AggressiveRelease();
	}
	else if (IsAggressiveRelease && batcher.HasOpenResources)
	{
		log.Info("forcing batcher resource cleanup on transaction completion; forgot to close ScrollableResults/Enumerable?");
		batcher.CloseCommands();
		AggressiveRelease();
	}
	else if (IsOnCloseRelease)
	{
		// log a message about potential connection leaks
		log.Debug(
			"transaction completed on session with on_close connection release mode; be sure to close the session to release ADO.Net resources!");
	}
	transaction = null;
}
 
private bool IsAggressiveRelease
{
	get
	{
		if (connectionReleaseMode == ConnectionReleaseMode.AfterTransaction)
		{
			return !IsInActiveTransaction;
		}
		return false;
	}
}
 
//Some AbstractSessionImpl code
 
protected void AfterOperation(bool success)
{
	using (new SessionIdLoggingContext(SessionId))
	{
		if (!ConnectionManager.IsInActiveTransaction)
		{
			ConnectionManager.AfterNonTransactionalQuery(success);
		}
	}
}
 
//And finally the AdoTransaction code
public bool IsActive
{
	get { return begun && !rolledBack && !committed; }
}

Basically, NHibernate will quasi-create an implicit transaction if it isn’t explicitly created. What’s weird is the scope of the transaction is just a single query. As you can see in the above code, I never called BeginTransaction() so tx.IsActive returns false, which indirectly makes the AbstractSessionImpl class think the transaction is over, which in turn indirectly triggers the ConnectionManager code to release the connection if the ConnectionReleaseMode is set to after transaction (which it is by default).

Whew!

Some outstanding questions though are why did this start happening with 2.0 and not 1.2? My guess is some code was refactored with how the last insert ID is retrieved, and in 1.2 it was impossible for it to have different connections. With 2.0, it is pretty easy to have different connection objects if concurrent operations are occurring.

Read more on ConnectionReleaseMode’s here.

(I hope this post made sense as I am super tired and have been learning NHibernate source code rapidly for the past few hours)

Post to Twitter Post to Digg Post to Facebook Post to Reddit

Leave a Comment :, more...

Find Orphaned Solution Files

by bhartsock on Dec.07, 2009, under Uncategorized

Each day, I am becoming more and more OCD. Tonight I wrote a script that will analyze a Visual Studio csproj file and compare it to the files in the directory. The main goal being an easy way to find orphaned files that might still be in version control. It probably only works on very vanilla projects, but I figured I would share anyways.

# find-orphanedFiles.ps1
#
# Compare files in a Visual Studio project file to the actual files in the directory
#
# Usage:
# .\find-orphanedFiles.ps1 Project\FooBar.csproj
# .\find-orphanedFiles.ps1 Project\FooBar.csproj -exclude "*.csproj","*.csproj.user","svn.ignore"
 
param
(
    $csProjFile,
    $exclude = ("*.csproj*")
)
 
function custom-gci($path=(get-location)){
    gci $path -exclude $exclude | 
    %{
        if($_.PSIsContainer -and ($_.name -ne "bin" -and $_.name -ne "obj")){
            custom-gci $_
        }elseif(!($_.PSIsContainer)){
            $_
        }
    } 
}
 
if(!(test-path $csProjFile)){
    throw "File $csprojFile does not exist"
}
 
$dir = split-path $csProjFile
$csProjfile = split-path $csProjFile -leaf
 
push-location $dir
 
$x = [xml] (gc $csProjFile)
 
$filesInProject = $x.Project.ItemGroup | 
    foreach {
        if($_.Compile) { 
            $_.Compile
        }elseif($_.None){
            $_.None
        }elseif($_.Content){
            $_.Content
        }elseif($_.EmbeddedResource){
            $_.EmbeddedResource
        }
    } | 
    select -expand include | 
    resolve-path | 
    gi | 
    select -expand fullname
 
$filesInDir = custom-gci |
    select -expand fullname
 
compare-object $filesInProject $filesInDir
 
pop-location

Post to Twitter Post to Digg Post to Facebook Post to Reddit

Leave a Comment :, more...

Are you in the Cloud yet?

by bhartsock on Dec.03, 2009, under Uncategorized

Sometimes I forget that cloud computing is still fairly new. There are still thousands of companies runnings their own servers and software. A couple weeks ago, in San Francisco, I saw something that caught my eye.

DSC00489 (600x800)

Seeing a SalesForce ad didn’t surprise me. What amazed me was it was on a bus stop. Not a big billboard (although I am sure they have those too), but a dingy little bus stop. The audience SalesForce is targeting is the masses, not a niche group of early adopters. This speaks volumes for the potential they see in software as a service.

Are you in the cloud yet?

Post to Twitter Post to Digg Post to Facebook Post to Reddit

Leave a Comment : more...

Don Norman – Ten Rules for Successful Products

by bhartsock on Dec.02, 2009, under Uncategorized

DSC00309 (800x600)Don is #2 on my list of speakers from Business of Software 2009. Don forces you to understand how people are using your product. It sounds simple, but most companies have a different outlook on their product than their customers. Here are his 10 rules for successful products.

Everything is a product. Everything is a service. You can’t have one without the other. The software you create is a product, but the experience you provide is your service. Don’t forget about one of these principles while focusing on the other.

Don’t be too logical. This might be the downfall of 99% of all developers. We are wired to think about the logical steps to perform an action, but users have emotion which plays the major role in their decisions. Usability testing is the best way to truly see how someone will use your product.

Design systems. Think about the iPod + iTunes + Add-ons or Kindle + Amazon + Verizon. This goes back to the above. Think about the entire service your product is providing, not just the functionality the product contains. A complete system solves the entirety of a customers problem. If you only solve a small portion of their problem, the experience is going to be lacking.

The other main points, which I think are fairly self explanatory.

  • It’s all about the experience
  • Memory is more important than actuality – Make the beginning and ending memorable
  • Complexity is good, Complicated is bad
  • Design for the real world.
  • Design for the people.
  • It’s all about the experience

Check out Don’s books if you want to hear more.

DSC00310 (800x600)

Post to Twitter Post to Digg Post to Facebook Post to Reddit

Leave a Comment : more...

iDoes Droid Review

by bhartsock on Dec.01, 2009, under Uncategorized

I spent the Thanksgiving holiday watching my dad play around with his new Droid. To my surprise, he was kind enough to let my try it out while he slept off Thanksgiving goodness. In short, it is Way Ugly, Blazing Fast, and Surprisingly Fun. It won’t dethrone the iPhone, but I think Google is onto something if they can fix a few shortcomings.

Way Ugly

motorola-droid-verizon_01The aesthetics of the physical device and the OS itself was quite disappointing. It is a big rectangle, and rectangles went out with Zach Morris. It is on the large side, heavy, and gets fairly hot. Even though it brags about a QWERTY keyboard, I bet you won’t use it, I didn’t. The buttons are in cumbersome locations, and it is easy to accidentally hit one while doing other tasks (like swinging a Schwartz Saber). These are all minor, but compared to the iPhone they are big differences.

As for the software, there seems to be very little unifying UI traits, unlike the iPhone. Every app looks, feels, and behaves differently. And since it is open to everyone to build on, I don’t see this changing. It is definitely a step backward in UI design, whereas Apple is the opposite.

Blazing fast

My dad told me the Droid was faster than his laptop at browsing the internet. I laughed. Then I actually played with the Droid and realized he wasn’t that far off (his laptop is pretty old anyways). Verizon’s 3G is fast and ubiquitous (unlike AT&T). Not to mention the Droid hardware performs very well. After a few hours of perusing, I realized slowness wasn’t an issue, especially compared to my BlackBerry. Even though the iPhone slightly out performs it, I have no doubt Android phones will continue to push the envelop on speed.

Surprisingly Fun

The overall experience was good with the Droid, even though the aesthetics were lacking. It had all the functionality I would need, plus a lot more. The device is easy to use, which is a big plus (my dad hasn’t asked me once how to do something).

Let’s not forget the Android platform. I didn’t have to pay a dime (unlike iPhone) to create an app that I could sell on the Android market, without the pain of going through the iPhone Apps process. This is an awesome plus for the techie world.

Would I buy the Droid if I needed a phone? Absolutely. I have a BlackBerry which works great for email, but lacks fun. Also, I am not an Apple fanboy (I have a Zune HD), so I would get it over the iPhone too.

The bottom line?

Microsoft should be scared. They need something huge with Windows Mobile 7, otherwise they will end up being last in the mobile device market. The Droid could easily surpass any Windows Mobile device I have ever seen.

BlackBerry’s still meets the business users needs best, but I think this will slowly erode unless they improve the web experience and build a better/easier platform to develop on.

iPhone has nothing to worry about for now. If they just keep innovating, the Android won’t pass them unless Google gets serious about its mobile involvement. Their only concern should be AT&T and will their network support future innovation.

Post to Twitter Post to Digg Post to Facebook Post to Reddit

Leave a Comment :, , more...

Post by day

March 2010
M T W T F S S
« Jan    
1234567
891011121314
15161718192021
22232425262728
293031