A classical musician turned programmer... or something

Here's a better version of string.IsNullOrEmpty(). Why is it better you say? Well my friend, this one checks the string for spaces... It also returns a positive statement (true if it is NOT null and NOT empty)

    public static class Extensions
        public static bool IsSafe(this string s)
            return (s != null && s.Trim().Length > 0);

And some unit tests...

        public void IsSafeStringTest()
            string cheese = "is good";
            cheese = "";
            cheese = "   ";
            cheese = null;
            cheese = "yum";
            cheese = "";
            cheese = null;
            // rut roh... 
            // string.IsNullOrEmpty() and spaces are not nice together.
            cheese = "   ";
            // should be true!

While the following might be nice, we know that we can't do it because of the null reference exception we might get (if cheese were to be null)...


Anyway, while we're doing some extension methods, here's a similarly named one I also use when working with generic lists.

        public static bool IsSafe<T>(this List<T> t)
            return (t != null && t.Count() > 0);

And some unit tests...

        public void IsSafeListTest()
            var objectList = new List<object>();
            List<int> intList = null;
            var stringList = new List<string>(){"cheese","beer","nachos"};


As promised, the materials.


Yo yo howdy-doody. I'm doing a talk on NUnit (and friends) with VS 2008 at CTDOTNET's second CodeCamp -- June 13th, 2009.

It's an intro to unit testing, but I'll talk about reasons why testing is beneficial, how to setup a unit testing environment, and tools (friends) to use along the way.

Get the deets about the day.

Hope to see you there!

This post will allow you to unit test objects that have a dependency on a SqlDataReader by mocking/stubbing a data reader.

Here I've made a 'wrapper' of sorts for the good ol' Microsoft SqlHelper class, which is ancient now, ya? Since the SqlHelper.ExecuteReader's method class implements the IDataReader interface we're in luck.

public interface IFetch {
//add members as necessary
IDataReader ExecuteDataReader(string connectionString, 
string storedProcedureName,SqlParameter[] parameters);
public class Fetch : IFetch {
public IDataReader ExecuteDataReader(string connectionString, 
string storedProcedureName, SqlParameter[] parameters){
return SqlHelper.ExecuteReader(connectionString, 

Next we create our object from the results of our IDataReader. The SqlHelper class removes the worry about mocking SqlCommand and SqlConnection classes. All you need to worry about are the results (SqlDataReader).

(You can make your own RockStar object, fo sho.)

Whether you call it constructor initialization or constructor chaining, we have it here, and will allow us to inject the correct dependency, in this case, an interface that defines an ExecuteReader method. (I've never gotten into DI/IoC frameworks, should I, and which??)

private readonly RockStar rs;
private readonly IFetch fetch;
//here's the magic sauce for the unittests
public FetchCms(IFetch fetch, RockStar rs){
this.fetch = fetch;
this.rs = rs;
//production code calls this which calls 
//the other constructor. mmm.
public FetchRockStar() : this(new Fetch(), new RockStar()) { }
public RockStar GetRockStar(string urlToLookup){
var parms = new[] { new SqlParameter("@urlName", urlToLookup) };
using (IDataReader reader = 
fetch.ExecuteDataReader("localhell", "rockstar_page_get",parms)){
if (reader != null && reader.Read()){
rs.Name = reader["name"].ToString();
rs.Guitar = reader["guitar"].ToString();
//add some logic... and so on...                       
catch //swine flu
return fs;

ok, so now your production code is hawt, but how do you 'fake' a reader, or 'fake' its results? Good question, but never fear, Phil Haack has you covered with his totally rock-tacular StubDataReader class. Get it.

so now, in your UnitTest project...

I'm creating some fake results that I can use to test my expectations, using the StubDataReader class you've downloaded above and added to your UnitTest project.

private static StubDataReader getData_Kerry_King(){
var resultSet = new StubResultSet("name", "guitar");
resultSet.AddRow("Kerry King", "B.C. Rich");
return new StubDataReader(resultSet);

I'm using the Moq framework to mock my interfaces. (it's from an older release, hence the Expect calls rather than the Setup calls [anyone: what does the new version get me?])

public void Execute_DataReader_Test() {
var m = new Mock<IFetch>();
//here i'm expecting that my ExecuteReader implementation
//return my 'fake' data
x => x.ExecuteReader(
var rockStar = new RockStar();
// pass IN the interface using the special constructor.
var fetch = new FetchRockStar(m.Object, rockStar);
rockStar = fetch.GetRockStar("kerry-king");
Assert.AreEqual("Kerry King",rockStar.Name);
Assert.AreEqual("B.C. Rich",rockStar.Guitar);

Even Kerry thinks you should be testing!

kick it on DotNetKicks.com

After looking at google analytics (ga) graphs all these months, I've come to the conclusion that if my site's ga graph were that of a stock/eft/etc I'd be a RICH dude. I'm guessing you'd be too since it's not a terribly new phenomenon; traffic or sales dropping off on the weekend. Akin to the turmoil on wall street, investors are often afraid to hold securities over the weekend. I don't blame them.

But really what do people do on the weekends? Beats me. I guess they don't read my blog! Granted it is somewhat technical-related. I don't read anyone's on the w/e either so whatev.

Ok, so here is the ga graph... (this is a snapshot from a month ago... by week)

my site as stock graph

I can assure you, this continues on for months...and months.... and months.

"So what does this all mean?" you ask. Well, in the next highly technically list, I will tell you the secret to becoming rich in this psuedo website exchange.

1. Know the future (which I clearly know regarding this site's traffic)
2. Buy / Cover low.
3. Sell / Short high.

short high, cover low

Here I've clearly laid out the points for which actions should be taken! Depending on your strategy, buying, shorting or both (just not at the same time :)) you too can be richy!

happy trading.


If you're like me, and make all of your data-related html bits yourself because you want full control of its output or you enjoy micro optimization... read on.

You're doing your loop thing with your StringBuilder thing because your specs say all the data needs to be on the same page (no paging, more-data-as-you-scroll (or other ajax) [bad specs, eh? Or you're just doing it wrong].

You finally got your page finished, loaded and hot DAMN it's 950kb. That's CRAZY! You gotta do something about that! You'll definitely want to optimize the html that is created during the looping operation. You know, it looks something like this...

StringBuilder sb = new StringBuilder();
for(int i=0; i<aZillion; i++) {
sb.Append(@"<tr class=""oddTableDataRow""><td align=""center"" valign=""middle"">blah</td>
<td class=""bottomBorderDarkest""><strong>zonk</strong></td></tr>");

Ok, so that was very simple. Obviously most cases are much more complicated, but still, it can be optimized. Some of these are general, others are very specific... some might not even be 100% html standards compliant. But hey, no one likes a slow loading page?

here we go:

· Make sure all css classes are actually used, and necessary.

· NO, I repeat, NO inline styles or style-like attributes. Everything should be done in your style sheet(s).

sb.Append(@"<tr><td width=""500"" align=""left"" valign=""top"">...);

· Use the smallest possible names for css classes, css ids, and javascript function names

Instead of id="header" use id=hdr
Instead of class="topBorderNew" use class=tbn
Instead of SomeJsFunctionThatIsPairedWithEachRow(); use s();

· If you have to make words 'stand out,' use <b> instead of <strong>, it's shorter

<b>a</b> = 8 characters.
<strong>a</strong> = 18 characters.

We're on an html diet, so sorry semantics!

· use <i> instead of <em>
(same logic as above)

· Use the innerHTML of a dropdown (<select>, rather than its value) (unless innerHTML and value are wildly different). <select> boxes are notorious for using up lots of Kbs.

· don't use double quotes (or any quotes for that matter).

<img src=image.jpg /> rather than <img src="image.jpg" />
<td class=blah> instead of <td class="blah">

· if you have lots of line breaks, use <br> instead of <br />

google does it all the time.

· limit the use of <span> tags

Use a parent container/selector to modify a would-be span-wrapped item.

· Don't use an 'odd' and an 'even' class for row highlighting.
Use one of them. You pick. (You could argue that this can easily be done client-side, but with large datasets you will notice the striping applied after the page is loaded.)

With some of these strategies, I turned a 950kb dynamically-generated page into 603kb page. That's a 36% savings! You could argue that, it's still pretty hefty, or most of this now can be done client-side, or hey "use a templating language" dumbo... but it isn't always an option.



If you tried any of these and they worked for you, let me know how many kbs you saved! Or please give any of your own.

Is it me... or did today, about perhaps 2-3pm EST, google made all their fonts a tad bit smaller?

UPDATE: I'm a dumbsky :)

Really? Yeah you bet!

I usually just toss that junk snailmail from the cable/phone company, but this time, they made me a special deal with part of my name in the url! We'll call this company pomcast (no disrespect to the real pomcast.com). I couldn't resist.

Something like http://www.mypomcastsavings.com/MYNAMEHERE0321... (like that sort of dynamic url has never been done before. dumbskys).

So in my clicking around the site specifically made for me and all my bundled needs, i noticed a nifty little savings calculator!

Since I don't have cable (minus the ~8 channels that comes with my internet), I entered $59.00 for internet and $0.00 for telephone (mobile phone is all I need)...

And look at my savings...

that's right, $-7.00. I would have the amazing privilege of paying them more per month for a service completely useless to me! HOT.

Not a terribly great marketing tactic.

You have a data-driven site and you like to keep the number of .aspx files to a minimum, so you opt for UserControls. Ok cool!

user controls are hot!Something you can do to be more dynamic-y is to name a UserControl the same as the requesting url, then check its existence on PageLoad. If it exists, load it into an asp:PlaceHolder control (or some other control). This can help keep your site more modular, and perhaps increase the chances that you'll reuse a UserControl in another project...or not.

Here the UserControls are stored in the /UserControls/dynamic folder on my site.

In your aspx page, we make an asp:PlaceHolder...

<asp:PlaceHolder ID="PHUserControls" runat="server"></asp:PlaceHolder>

And in code behind, on PageLoad... we make the path of the UserControl and see if it exists. If it does, we add it to the placeholder.

string path = AppDomain.CurrentDomain.BaseDirectory + "UserControls\\dynamic\\" + PageUrl + ".ascx";
if (File.Exists(path))
Control c = LoadControl("~/UserControls/dynamic/" + PageUrl + ".ascx");


Extension methods have been around since C# 3.0 came out, which I guess was some time ago. I really like using them. The syntax is short and neat. Notice how the example below lives in a static class. Nutty eh!?

This example is for all you foos out there that might not be checking input before it's passed down into the database. It checks the input string for null/empty and if there's something, it will replace a single quote with two single quotes (since the single quote is arguably the most devastating character in user inputs / SQL inserts)

   public static class StringUtils
        public static string ToSafeSql(this string s)
            return (s == null || s.Trim().Length == 0) 
            ? "" 
            : s.Replace("'", "''");

About Brian

profile for bluevoodoo1 on Stack Exchange, a network of free, community-driven Q&A sites

Brian Canzanella brings you nifty tips and tricks for most things .NET. read more...

Readers / Stuff