• More Effective C# Notes: Generics

    I’ve been reading the More Effective C# book by Bill Wagner. I’m going to blog some of my notes and thoughts on the book. If you find some of this stuff useful you will want to pick up a copy of the book.

    Use the least amount of constraints on type parameters as possible. I’ve run into this, and besides limiting the usefulness of your class, in many cases you need to implement an interface or add a default constructor to get classes to compile. And ultimately your generic class ends up not being very generic.

    In order to help achieve the above, you can use methods or delegates to enforce a specific needed operation. Whatever constraint you were going to have you could create a delegate that needs to be passed in and remove the constraint.

    If you need to create new instances of the type parameter, you need to make sure you dispose of it correctly if it implements IDisposable. If it’s created as an instance member your generic classes needs to implement IDisposable. This simple pattern can be used for method scoped instances.

    T instance = new T();
    using (instance as IDisposable)</p>
    instance.MethodCall();<style type="text/css">.csharpcode, .csharpcode pre


    font-size: small;
    color: black;
    font-family: consolas, "Courier New", courier, monospace;
    background-color: #ffffff;
    /*white-space: pre;*/

    .csharpcode pre { margin: 0em; }
    .csharpcode .rem { color: #008000; }
    .csharpcode .kwrd { color: #0000ff; }
    .csharpcode .str { color: #006080; }
    .csharpcode .op { color: #0000c0; }
    .csharpcode .preproc { color: #cc6633; }
    .csharpcode .asp { background-color: #ffff00; }
    .csharpcode .html { color: #800000; }
    .csharpcode .attr { color: #ff0000; }
    .csharpcode .alt

    background-color: #f4f4f4;
    width: 100%;
    margin: 0em;

    .csharpcode .lnum { color: #606060; }

    Remember that the type parameter is always going to be the best match in an overloaded method search. As, such you can use run-time type checking to optimize for performance. I would not bother doing this until you know that it’s a performance issue. Or unless your making a closed source framework.

    Use generic methods unless the type parameter is going to be an instance field. This makes the generic class easier to use as you don’t need a new class for each different type parameter being used. Also these types of methods lend themselves to becoming extension methods.

    Again these are just some of my notes, the book, like the previous one, is worth a full read.

  • Intro To Unit Testing: 2 of n

    Where do tests fit into my project and process?

    There are a few ways to structure unit tests. Two of the most common seem to be one to one assemblies and same assembly. One to one assemblies meaning one test assembly for each assembly being tested. This approach has the benefit of easily removing the test assemblies before releasing code to production. It also allows testing release built code with out an extra build cycle like the following method requires. One drawback is that internal classes are harder to test.

    The second structure, same assembly, has the TestFixtures in the assembly being tested. The main challenge with this is creating builds without the tests. I’ve seen this handled two way, first by the build script excluding all files under a Tests directory. And secondly, using compiler directives like #if TEST around the test code. Both have draws backs but the main one being two complies one to test and one to release. The main advantages are access to internal classes and fewer assemblies in a solution.

    Which is right? As with many things, it depends.

    Unit tests generally fit into the development in two key places, three for TDD. The first is before any code check-in the unit tests should be run and pass. Secondly, the continuous integration system should run the tests and fail the build if the tests fail. Third, if developing using TDD you would run the tests almost constantly while developing and refactoring.

  • Intro To Unit Testing: 1 of n

    What is UnitTesting? What are UnitTests?

    UnitTesting is testing a unit of functionality with other code.

    UnitTests, in the context of c#, are simply classes with attributes. Usually they are called test fixtures which contain test cases. Test cases are just methods with a Test attribute on them. UnitTests are mostly concerned with testing interaction between classes or logical outcomes. Interaction tests test for the correct interaction between classes, usually with Stub or Mock objects. An interaction test might test for a web service call with a specific message. Logical tests test that the given business logic is working was expected. For example making sure a filter on insurance applications actually filters out applications. Both of these test types will use Assertions to make sure what was expected to happen did happen. An Assertion is really just a logical check that throws an exception if it’s false. If a test has Assert.AreEqual(expected, actual) and expected does not equal actual it will throw an exception, with details, to fail the test.
    Here is a super simple test to make sure the test framework is working correctly.

    using MbUnit.Framework;
    namespace IntroToUnitTests.Tests
    <span class="kwrd">public</span> <span class="kwrd">class</span> TestFixture
        <span class="kwrd">public</span> <span class="kwrd">void</span> Is_The_Test_Framework_Working()
            Assert.IsTrue(<span class="kwrd">true</span>);


    Why would I want to write tests? What are the advantages?

    • Unit tests allow code to be changed and refactored without worrying about breaking the expected functionality.
    • Unit tests promote better design and cleaner, simpler code.
    • Unit tests help document the intent of code.
    • Unit tests help make sure bugs do not come back to life.
    • Unit tests help reduce time in the debugger.

    Why wouldn't I want to write tests? What are the challenges?

    Unit testing the UI is typically a very challenging. WebForms usually make unit testing really hard or impossible. This is partly because recreating the ASP.Net life cycle is not possible. And partly because it's really easy to mix business concerns with UI concerns.

    Unit testing databases is challenging on two fronts. First having a way to create a clean DB for testing. Secondly, keeping the test time reasonable.

    Legacy Code, which is often considered code without tests, is challenging because before you change legacy code it needs tests, but often you need to change the code to be more testable.

    Who writes and maintains these tests?

    Developers are responsible for writing, maintaining, and running unit tests. The build/release process should also be responsible for running and failing if any of the unit tests fail.

    I hope this provides basic high level overview of unit testing, and idea of what value they might add and what challenges they might present. More detailed posts will be coming soon.

  • Monitor Twitter and Respond with BabbleWatch.com!

    babblewatch-logo-final-med-whiteI’m looking to get some early feedback on a side project of mine, BabbleWatch.com. It’s a tool for monitoring Twitter and Responding. It’s main goal is to help build and maintain your companies brand reputation. It’s in very early stage development, but I wanted to get some feedback so please give it a try; BabbleWatch.com.

  • Re-blogging: Developing Linq to NHibernate

    If you’re at a company that might be interested in helping fund a Linq to NHibernate project please read Developing Linq to NHibernate.

  • Tips for using Silverlight with Monorail (or embedded)

    Today I worked on getting a Silverlight chart embedded in my monorail application. I learned a few things.

    You need to have a Silverlight application project someplace in order to create the XAP file. This is what will ultimately get used in your view.

    Since it’s really running client side, the XAP files are included in your other projects like other client site stuff, that is just manually copied into a directory there.

    Databinding to XML doesn’t seem to work, I think I must be doing something wrong, but I finally ended up using Linq to transfer the data into objects and bind to those. Like this:

    series.ItemsSource = from n in descendants</p>
                     select <span class="kwrd">new</span> Data
                                    Date = n.Attribute(<span class="str">"Date"</span>).Value,
                                    Count = <span class="kwrd">int</span>.Parse(n.Attribute(<span class="str">"Responded"</span>).Value)

    series.IndependentValueBinding = new Binding(“Date”) { Mode = BindingMode.OneWay };
    series.DependentValueBinding = new Binding(“Count”) { Mode = BindingMode.OneWay };

    public class Data

    <span class="kwrd">public</span> <span class="kwrd">string</span> Date { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">int</span> Count { get; set; }


    In your View you use embed the XAP file using the object tag like:

    <object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
        <param name="source" value="/assets/Charts.xap"/>
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="2.0.31005.0" />
        <param name="autoUpgrade" value="true" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
        <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>

    This is really my first time checking out Silverlight, so I'm sure I'm missing a lot and have a ton left to learn. There is a bunch of great info on the Silverlight site.

  • Selecting Aggregate Data With Castle.ActiveRecord

    Lets say your using Castle’s ActiveRecord and you have a complex query to aggregate some data, but you want that query to return the data in a typed class, just not one that NHibernate or ActiveRecord know about…

    Here’s what I ended up doing. Creating the SQL query then using the HqlBasedQuery class. There are two important details regarding this, first the query needs to name the columns using the SQL as keyword and setting the Scalar definition. Second, you need to set a transformer using the SetResultTransformer method. Luckily, NHibernate includes a class that will map named scalars to matching properties or fields. More about that here, in section 14.1.5.

    Here’s the code:

    var sql = @“
    select convert(varchar, published, 101) as [Date],
    count(state) as [Total],
    sum(case when state = 2 then 1 else 0 end) as [Responded]
    from notices n
    inner join sources s on n.sourceid = s.id and s.userid = :userid
    where published >= dateadd(day, -7, getdate())
    group by convert(varchar, published, 101)”;</p>

    HqlBasedQuery q = new HqlBasedQuery(typeof (Notice), QueryLanguage.Sql, sql); q.AddSqlScalarDefinition(NHibernateUtil.String, “Date”); q.AddSqlScalarDefinition(NHibernateUtil.Int32, “Total”); q.AddSqlScalarDefinition(NHibernateUtil.Int32, “Responded”); q.SetParameter(“userid”, Id); q.SetResultTransformer(Transformers.AliasToBean(typeof(NoticeCount)));

    var results = ActiveRecordMediator.ExecuteQuery(q) as ArrayList; if (results == null)

    <span class="kwrd">return</span> <span class="kwrd">new</span> NoticeCounts();

    var counts = results.ToArray(typeof (NoticeCount)) as NoticeCount[];
    return new NoticeCounts { Counts = counts };