Fix some issues pinpointed by Code Analysis
Upgrade to .Net 4.0

Fix #654