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?