C#

warning: Creating default object from empty value in /home1/seocactu/public_html/csharptocsharp/modules/taxonomy/taxonomy.module on line 1388.

Here's a quick little one-liner I use all the time.

It will create a concrete instance that implements 'I' interface. This has a string as a parameter, but there are lots of other possibilities (and overloads for Type and CreateInstance).

But, be careful with this, you can easily get into trouble, as the magic happens at runtime, so watch your speeling.

public class Activator<I>
    {
        public static I Create(string s)
        {
            return (I)System.Activator.CreateInstance(Type.GetType(s));
        }
    }

Tags:

Year after year you know you have a product that will be updated at a[round] a certain month. It happens a lot with my business domain. Rather than changing lots of text, this should work nicely for my needs. (I didn't use any timezone or culture considerations)

the pivot month is the int that decides when we flip to next year.

/// <summary>
/// Figures out if should use this year 
///or next based on a defined pivot month.
/// </summary>
/// <returns>4 digit year</returns>
public int YearPivot(DateTime dt, int pivotMonth)
{
     return (dt.Month <= pivotMonth) ? dt.Year : dt.AddYears(1).Year;
}

couple tests showing it in action...

DateTime dt = new DateTime(2009, 10, 1);
//returns 2009
Assert.AreEqual(2009, m.YearPivot(dt, 10));
//returns 2010
Assert.AreEqual(2010, m.YearPivot(dt, 5));

Tags:

I work for a fabulous company, I've been with them for about 3 years. They are incredible about making sure developers have what they need to get the job done, whether it's software or hardware (or classes, or books). In fact, I'm on my third development machine! Most software requests are usually also granted.

So what does your gear look like? What development software has your company gotten for you to help better your work?

This is what it looks like for me:(as of posting)

Hardware:

  • Windows XP 64, core 2 quad @ 2.5 GHz, 8 gigs of ram
  • 3 19 inch widescreen monitors
  • microsoft natural ergo keyboard
  • trackball mouse
  • physical server 03 box [for testing]
  • various XP/03 virtual machines [more testing]

Software:

  • Resharper 4
  • dotTrace
  • NDepend
  • NCover complete
  • RegexBuddy
  • BareTail Pro
  • All the microsoft dev. stuff (VS 03,05,08, SQL server 05,08)
  • Snag it
  • ultramon

What about you?

kick it on DotNetKicks.com

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...

       [Test]
        public void IsSafeStringTest()
        {
            string cheese = "is good";
            Assert.IsTrue(cheese.IsSafe());
            cheese = "";
            Assert.IsFalse(cheese.IsSafe());
            cheese = "   ";
            Assert.IsFalse(cheese.IsSafe());
            cheese = null;
            Assert.IsFalse(cheese.IsSafe());
 
            //-------------------------------
            cheese = "yum";
            Assert.IsFalse(string.IsNullOrEmpty(cheese));
            cheese = "";
            Assert.IsTrue(string.IsNullOrEmpty(cheese));
            cheese = null;
            Assert.IsTrue(string.IsNullOrEmpty(cheese));
 
            // rut roh... 
            // string.IsNullOrEmpty() and spaces are not nice together.
            cheese = "   ";
            // should be true!
            Assert.IsFalse(string.IsNullOrEmpty(cheese));
 
 
        }

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)...

string.IsNullOrEmpty(cheese.Trim());

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...

       [Test]
        public void IsSafeListTest()
        {
 
            var objectList = new List<object>();
            Assert.IsFalse(objectList.IsSafe());
 
            List<int> intList = null;
            Assert.IsFalse(intList.IsSafe());
 
            var stringList = new List<string>(){"cheese","beer","nachos"};
            Assert.IsTrue(stringList.IsSafe());
        }

Tags:

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, 
CommandType.StoredProcedure,storedProcedureName, 
parameters);
}
 
}

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){
try
{
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?])

[Test]
public void Execute_DataReader_Test() {
var m = new Mock<IFetch>();
//here i'm expecting that my ExecuteReader implementation
//return my 'fake' data
m.Expect(
x => x.ExecuteReader(
It.IsAny<string>(), 
It.IsAny<string>(), 
It.IsAny<SqlParameter[]>()
)
).Returns(getData_Kerry_King());
 
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
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

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();
sb.Append("<table>");
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>");
}
sb.Append("</table>");

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.


$$cha-ching!$$


cha-ching!


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.

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("'", "''");
        }
    }
Tags:

So, I totally dig pre-processor directives. Use them all the time. Do you? I hope so! It can make a Debug build ready for a Release build with the change of a dropdown in Visual Studio.

Here's an example to change the logPath string if you're building in Debug mode (or anything else). This could be very handy with programmatically creating a log4net config.

        string logPath;
#if DEBUG
        logPath = @"C:\csharptocsharp.com\log.txt";
#else
        logPath = @"Q:\sites\csharptocsharp.com\logs\log.txt";              
#endif

Anyway, if you're not using preprocessor directives in your code, then what are you waiting for?

Other References:
MSDN Preprocessor directives

Tags:

One of the things I learned at DevConnections 08 is the magic behind ASP.NET MVC, and how it actually works. Beside the UrlRouting (which you can do with HttpModule stuff), it's pretty easy and relies a lot on Activator.CreateInstance(). As seen in my post about creating a csv from list, you can read about it here.

The magic is...shhh...

To programmatically create the worker class based on the url.

magic mvc

Yeah, no-DUH you say. Well it took MS this long to come up with it for public consumption when MVC has been around for decades. Anyhooo.

NOTE: I'm more of an MVP guy, so this is geared toward using the MVP's Presenter rather than the MVC's Controller. They're similar patterns, 'cept MVP is a bit more decoupled (and deprecated...), so in my example below, you can replace 'Presenter' with 'Controller' if it makes you fuzzy, because really, that's where all the work gets done.

Here we go.

mvc is on fire!A request comes in for blah.com/hotguitars.aspx. Your UrlRouting can match the url up with the correct view [handler] and rewrite its path to that page handler. In this case, I'd most likely use the DefaultView since the page lives off of the root (/).

On PageLoad the presenter factory is going to take the url and try to figure out which class to instantiate [return] to make the contents for the view. Each of the classes returned implement Presenter, which implements IPresenter... so I can code to the interface, which is nicer. (Notice the interfaces. I'm an interface kinda dude, because they're hot when it comes to testing).

Ok, so here's the little POC for you.

    // Presenter class implements this because all *Presenter
    // classes need to have a DoIt() method
    public interface IPresenter
    {
        void DoIt();
    }
 
    public class Presenter : IPresenter
    {
        public Presenter() { }
        public virtual void DoIt() { }
    }
    public class PresenterFactory
    { 
        //return the url minus hyphens
        private static string GetPresenterName(Regex re, string url)
        {
            return re.Match(url).Groups[1].Value.Replace("-","");
        }
        //get the url
        private static Regex rePage = 
new Regex(@"/(.+?)\.aspx", RegexOptions.IgnoreCase);

This is the sexiness....

        public static Presenter GetPresenter(Page page)
        {
            // this is blah.com/hotguitars.aspx
            string rewrittenUrl = page.Request.RawUrl;
            string presenterName = GetPresenterName(rePage, rewrittenUrl);    
            //here is where you make sure you have a HotGuitarsPresenter
            string className = "BunchaJunk.Presenters." + presenterName + "Presenter";
            // get the type, throw error, and ignore case
            Type type = Type.GetType(className, true, true);
            // create an instance of the correct Presenter/Controller and return it
            return (Presenter)Activator.CreateInstance(type, new object[] { page });
        }
    }
    public interface IBasicPage
    {
        string HtmlTitle { get; set; }
        string HtmlMetaKeywords { get; set; }
        string HtmlMetaDescription { get; set; }
        string MainContent { get; set; }
    }
    public class HotGuitarsPresenter : Presenter
    {
        private IBasicPage ibp;
        public HotGuitarsPresenter(IBasicPage ibp)
        {
            this.ibp = ibp;
        }
        public override void DoIt()
        {
            ibp.HtmlMetaDescription = "Hot stuff!";
            ibp.HtmlMetaKeywords = "jackson, paul reed smith";
            ibp.HtmlTitle = "Here are the hottest guitars at csharptocsharp!";
            ibp.MainContent = "paul reed smith, jackson, gibson";
        }
    }
 
 

Here is how it is called from aspx code behind
    public partial class _Default : Page, IBasicPage
    {  
        protected void Page_Load(object sender, EventArgs e)
        {
            //coding to the interface is the cat's meoooooooooooow
            IPresenter p = PresenterFactory.GetPresenter(this);
            p.DoIt();
        }
        public string HtmlTitle { get; set; }
        public string HtmlMetaKeywords{get;set;}
        public string HtmlMetaDescription { get; set; }
        public string MainContent{get;set;}
    }

Here is how it's used in the aspx
<title><%=HtmlTitle%></title>

That is all!

kick it on DotNetKicks.com

Tags:

Here's a method I've been working on for a recent project. It will make a csv file from a generic list of type <T>.

There are methods out there for doing similar with DataTables... I like working with generic lists myself.

It does what it needs to do, but I'm not terribly happy with it yet, especially with a class with multiple constructors (all properties are used in csv).

(sorry about the formatting... gotta find a c# code format plugin...)
UPDATE: http://drupal.org/project/geshifilter

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
        public static void CreateCSVFromGenericList<T>(List<T> list, string csvNameWithExt)
        {
            if (list == null || list.Count == 0) return;
 
                //get type from 0th member
                Type t = list[0].GetType();
                string newLine = Environment.NewLine;
 
                using (var sw = new StreamWriter(csvNameWithExt))
                {
                    //make a new instance of the class name we figured out to get its props
                    object o = Activator.CreateInstance(t);
                    //gets all properties
                    PropertyInfo[] props = o.GetType().GetProperties();
 
                    //foreach of the properties in class above, write out properties
                    //this is the header row
                    foreach (PropertyInfo pi in props)
                    {
                        sw.Write(pi.Name.ToUpper() + ",");
                    }
                    sw.Write(newLine);
 
                    //this acts as datarow
                    foreach (T item in list)
                    {
                        //this acts as datacolumn
                        foreach (PropertyInfo pi in props)
                        {
		  //this is the row+col intersection (the value)
                            string whatToWrite =
                                Convert.ToString(item.GetType()
                                                     .GetProperty(pi.Name)
                                                     .GetValue(item, null))
                                    .Replace(',', ' ') + ',';
 
                            sw.Write(whatToWrite);
 
                        }
                        sw.Write(newLine);
                    }
                }  
        }

So there you have it... C# generic list to csv file!

Couple things to change/ideas...

  • take in a delimiter (string) (comma is standard now, but it could be anything, use that as .Replace() of value as well)
  • remove last comma in header row.
  • fix this line 'Type t = list[0].GetType();' (I don't like it!)

Any suggestions are welcome!

kick it on DotNetKicks.com

Tags:

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