Code Snippets

Nick followed up on my C# snippet post with a nice piece about using code snippets in Visual Studio 2005 and using a snippet editor to create and share your own code snippets. His post reminded me that I had forgotten to mention that to use that snippet you will need to add a “using System.Data.SqlClient;” and System.Data to your references.

Nick mentioned the VB.NET version of the code snippets editor; you can download Snippy, a Visual Studio C# Snippet Editor from GotDotNet (soon to disappear; come on Microsoft, I’m sure it wouldn’t break the bank to keep this running. I ask myself if Google would close down a similar site…) [BTW, Brian Madsen one of our other Perth MVP’s loves VB.NET with a passion. He is going to kill me for saying that :)… ]

I was also going to recommended having a look at the gotcodesnippets.com site but the second C# snippet I looked at was flawed: don’t use the singleton that is posted there. It’s not thread safe. Use this one instead: C# Singleton Best Practice. The gotcodesnippets site could be improved by having some sort of comment or peer review voting system (similar to regexlib, for example), otherwise it is in danger of spreading incorrect information. I suppose this is always the danger with such open sites. I’m sure there are many useful snippets there; just don’t go using them without checking first. One nice feature is that the site is RSS enabled so you can be notified of new code snippet uploads.

Free Developer E-Learning

One of the developer resources that I’ve mentioned a few times on my blog are the free e-learning courses Microsoft provide. There are several currently available:

Branching Guidance for Team Foundation Server

Jeff Beehler has announced the initial release of Branching guidance for Team Foundation Server:

“While the product documentation will tell you how each of our tools works, it
doesn’t provide insight into the best practice usage of each. The guidance
that we recently released attempts to fill that gap in the area of version
control and how to best work with branches. … what you’ll read in this
guidance isn’t some theoretical description of how things should work in a
perfect world but instead has been pressure tested and proved to be effective
through actual TFS projects. In fact, you’ll find examples pulled directly
from our own teams experiences as well. ”

I found it interesting that they appear to have moved away from what I assumed was the industry standard terminology of ‘trunk’ to ‘main’. Much of the advice is familiar. The few differences I suspect are down to working in very large teams (> 100 developers). This is a work in progress, and I’m sure a few changes will be made to it…

The best source of advice on branching and merging that I have come across to date is the free online book Version Control with Subversion. I wonder if the authors read this?

C# Code Snippet: Read Data from Stored Procedure

I love clear, concise, easy to read code. Here’s a fairly minimalist .NET 2.0 code snippet to read data using a stored procedure that is hopefully all those things. It makes use of the using statement which guarantees that resources held by types that implement IDisposable will be released even if an exception is thrown (using is syntactic sugar for an enclosing try/catch/finally loop):

// Execute a stored proc to read data
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "ProcName";
        cmd.CommandType = CommandType.StoredProcedure;
 
        // Add any input Params...
        cmd.Parameters.AddWithValue("@SomeIDParam", myID);
 
        conn.Open();
 
        // Assuming Stored Proc returns a set of records...
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (rdr.Read())
            {
                // do something with each rdr row ... 
            }
        }
 
        // OR alternatively, 
        // if your proc returns a single valued result (e.g. an image)
        // (i.e. query of the form "SELECT imgColumnName FROM Table WHERE ID= ?"
        // byte[] img = (byte[])cmd.ExecuteScalar();  
    }
}

Source Code Highlighting for Blogger Posts: CopySourceAsHTML

If you have read any of my blog posts that contain C# source code, you will have no doubt noticed the varied, or lack of indentation! It wasn’t intentional. I’ve actually sat down and tried to post entries with lots of source code and then given up in frustration.

I’ve been using CopySourceAsHTML 2.0, a great little add-in for Visual Studio 2005, for some time but Blogger would lose the indentation when I swapped between the HTML and compose views. I played around with it for a bit today and found settings that seem to work:

I also tried turning off “Embed styles” and placing the small amount of required CSS into the blog template, but I had no luck getting this to work. Let’s just say I’m not the world’s greatest CSS wizard (Lvl 1, AC10, small kitten…).

CopySourceAsHTML made it into James Avery’s must read MSDN article “Ten Essential Tools: Visual Studio Add-Ins Every Developer Should Download Now”.

I also came across Jean-Claude Manoli’s Code Format Tool which does the job nicely but misses out on the ‘Teal’ Type colouring that you get from CopySourceAsHTML. It’s worth downloading his lean source code for a peek; a very nice piece of coding. Doug Rohm posted a syntax colouring round-up here.

SQL Server 2005 Security: Operational Best Practices

Bob Beauchemin‘s SQL Server 2005 Security Best Practices – Operational and Administrative Tasks whitepaper is up on the Technet website:

“This white paper covers some of the operational and administrative tasks
associated with SQL Server 2005 security and enumerates best practices and
operational and administrative tasks that will result in a more secure SQL
Server system. Each topic describes a feature and best practices.”

T-SQL Helper Table Utilities

Over at Red Gate’s Simple-Talk blog, Robyn Page and ‘Phil Factor’ have a nice article on using a helper table of numbers to convert some common T-SQL iterative tasks to set-based operations:

  • Splitting Strings into table-rows, based on a specified delimiter
  • Encoding and decoding a string
  • Substituting values into a string
  • Extracting individual words from a string into a table
  • Extracting all the numbers in a string into a table
  • Removing all text between delimiters
  • Scrabble score
  • Moving averages
  • Getting the ‘Week beginning’ date in a table
  • Calculating the number of working days between dates

Rob Farley is a bit of a demon with a table of numbers; I wonder if knows any more of these? Rob?

Attachment Detachment!

Ken Getz is no slouch when it comes to coding. The “Access Developers Handbook” series by Litwin/Getz/Gilbert was a classic. Few books covered the material so well or as comprehensively. I just pulled my Access 97 version down from the bookshelf. Ah, Access we had some good times! Right, that’s enough reminiscing!

It’s therefore reassuring to discover that developers of Ken’s stature occasionally make the same kinds of mistakes as the rest of us! As testament to the fact that the .NET framework is, in the words of Michael Palin as the chaplain in ‘Monty Python’s The Meaning of Life’, “…so very, very Huge! ..”, Ken posted this article.

Ken’s advice is worth heeding:

“A word to the wise: If you find yourself writing .NET code which seems like it
sure as heck ought to have been included in the Framework, take a few seconds
and try to convince yourself that it’s not.”

Test Your Apps for SQL Injection Attacks

Do you test your applications for SQL injection vulnerabilities? I came across a nice round-up of possible attacks here: SQL Injection Cheat Sheet It has a nice reference section.

About a year and half ago, I was going to submit some of my photographs to a stock library based in Queensland, Australia, and on a whim I decided to try a very basic SQL injection to see how secure this site would be with my financial details. It didn’t pass! I contacted the owner/maintainer and told him about the problem. One year later, I checked back to see if it had been fixed. It had not. Needless to say, I don’t list any photos with them!

NDepend2

NDepend is a static code analysis tool that can provide you with some surprising insights into your code. Scott Hanselmann did a podcast and blogged about this tool recently, and when Scott waxes lyrical about something I sit up and take note. I played around with tool in its earlier incarnation some time ago, but didn’t fully ‘grok’ it, as I didn’t persevere over the 15 – 30 minutes ‘hump’ with the excellent tutorials (it’s only 5 – 10 minutes for Scott, apparently. Damn those Hanselmann clones!) It complements FxCop’s functionality and it can be similarly incorporated into your automated build process. Don’t take my word for it, go and download the free trial version and work through all 6 tutorials at least twice.

So what can NDepend be used for? Getting familiar with an existing, large codebase, gathering all kinds of metrics with a view to refactoring and improving existing code.

It can give you the 100ft view of a large and complex code base, but at the same time allows you to analyse and pinpoint a problem and then drill-down right to the code. If I remember correctly, I think Scott said it was Reflector on Steroids, but then so much more! It uses some pretty clever visualization techniques to convey code metric information.

I’m going to blog about NDepend2 in a bit more detail presently. In fact, I’m thinking it would make a great .NET User Group session…