Scott Hanselman

The Weekly Source Code 6

September 26, 2007 Comment on this post [10] Posted in Source Code
Sponsored By

In my new ongoing quest to read source code to be a better developer, I now present the sixth in an infinite number of a weekly series called "The Weekly Source Code." Here's some source I'm reading this week that I enjoyed.

  • xUnit is a new Unit Testing Framework from Jim "Original NUnit Guy" Newkirk and Brad "The .NET Guy" Wilson. Posts about the "why" of it are already flying and I remain neutral, like Switzerland. Seems unnecessary to me, but whatever makes you happy. Let's see if there's anything neat in the source. You gotta give them style points for extensibility. See how they make up a new attribute "RepeatTest," give it behavior, then apply it to a test and the Test Runner just runs the test as the yield's return new TestCommands. Clean.
    public class Example
    {
        static int val;
    
        [RepeatTest(5, Timeout=500)]
        public void RepeatingTestMethod()
        {
            Thread.Sleep(100);
            Assert.Equal(2, 2);
            if (val == 0)
            {
                val++;
                Thread.Sleep(1000);
            }
        }
    }
    
    public class RepeatTestAttribute : TestAttribute
    {
        readonly int repeatCount;
    
        public RepeatTestAttribute(int repeatCount)
        {
            this.repeatCount = repeatCount;
        }
    
        public override IEnumerable<ITestCommand> CreateTestCommands(MethodInfo testMethod)
        {
            for (int index = 0; index < repeatCount; index++)
                yield return new TestCommand(testMethod);
        }
    }
  • Keith Brown's Password Manager (PWM) - I had my favorite Password Manager crash on launch for me today so I rebuilt it it locally and set the Platform to x86 and it worked. While I was in there...take a look at this bodiless "Record" constructor.
    public Record(string site, string salt, string encryptedUserId, string encryptedPassword, string encryptedNotes, string useSetWindowText, string duration, string nagSpan, string nextReminder, string lastReset, string usageCount) 
            : this(site, salt, encryptedUserId, encryptedPassword, encryptedNotes, "true" == useSetWindowText,
                   "" == duration ? 0 : Convert.ToInt32(duration),
                   "" == nagSpan  ? 0 : Convert.ToInt32(nagSpan),
                   "" == nextReminder ? DateTime.MaxValue : Convert.ToDateTime(nextReminder),
                   "" == lastReset ? DateTime.Now : Convert.ToDateTime(lastReset),
                   "" == usageCount ? 0 : Convert.ToInt32(usageCount)) {
     }
  • RhinoMocks (SVN source) - Both Matt Gilbert and Mike Minutillo pointed me (back) to RhinoMocks Mike says he likes the DisposableAction pattern Ayende is fond of.
    namespace Rhino.Commons
    {
        public class DisposableAction<T> : IDisposable
        {
            Proc<T> _action;
            T _val;
    
            public DisposableAction(Proc<T> action, T val)
            {
                if (action == null)
                    throw new ArgumentNullException("action");
                _action = action;
                _val = val;
            }
    
            public T Value { get { return _val; } }
            public void Dispose() { _action(_val); }
        }
    
        public class DisposableAction : IDisposable
        {
            Proc _action;
    
            public DisposableAction(Proc action)
            {
                if (action == null)
                    throw new ArgumentNullException("action");
                _action = action;
            }
            public void Dispose(){ _action(); }
        }
    }
  • Monorail HotSwap - While you're there, take a look at these 70 lines of code. I wonder aloud if this leaks Assemblies, but it's OK because it's primarily created as a development speed thing. Clever though. Did YOU know how easy it is to compile new code from within .NET?
    void CodeChanged(object sender, FileSystemEventArgs e)
    {
        string fileName = Path.GetFileNameWithoutExtension(e.FullPath);
        string typeName = controllersNamespace+"."+fileName;
        CompilerParameters options = CreateCompilerOptions();
    
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults compilerResults = provider
            .CompileAssemblyFromFile(options, e.FullPath);
    
        container.Kernel.RemoveComponent(typeName);
        
        if(compilerResults.Errors.HasErrors)
            return;
    
        Type type = compilerResults.CompiledAssembly.GetType(typeName);
        container.AddComponent(type.FullName, type);
    }
    

Feel free to send me links to cool source that you find hasn't been given a good read.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
September 26, 2007 6:02
Did YOU know how easy it is to compile new code from within .NET?


Yup ...

var hello =
Expression.Lambda(Expression.Call(typeof(Console).GetMethod("WriteLine",
new [] { typeof(string) }),
Expression.Constant("Hello, World!")));

var thatWasEasy = hello.Compile();
September 26, 2007 6:31
Nicely done sir. I suppose that does count! :)
September 26, 2007 9:33
OK, what's up with Keith Browns' code? Sure it's cute but is it really saving any lines of code especially after compilation? It's not really more legible and it's not commented/documented any better.

I'd like to see performance comps or even output assemblies between this and the typical if...then...else blocks. At first run it would seemingly have to compile to the same byte code... er MSIL code unless I'm really missing something. Am I?
September 26, 2007 13:16
I thought Ayende's code was so cool I did a screencast showing it in action:

http://colinramsay.co.uk/2007/09/23/hotswap-for-monorail-in-action/
September 26, 2007 15:32
I really like "The Weekly Source Code" column (as if you're blog were a magazine) more with the code/highlights. In epsiodes 1-5, I kept thinking, "Yeah...let's take a look at that sometime...del.icio.us..." and then never get around to looking at it. Thanks for adding this!
September 26, 2007 18:11
Hey Niow Scott,
From the time I've heard the episode on how to become a better developer & you stated to read some good code, I've really enjoyed these series of posts. I would have never been exposed this code if you didn't post it.
Hanselminutes Fan,
Catto
September 26, 2007 19:51
Scott,

Its nice that you are posting the weekly source code review news. This encourages readers like me, where to look for good code and possibly learn from it. It would be nice if you can write about the code reading process itself. Is there any process/pattern that you follow while reading the code? Do you use any tools to understand the architecture of the code base you are looking at? Are there any tips and tricks to get the maximum out of the reading session? I am just wondering how can you finish reading 4 code bases in a week to a level where you can appreciate the code.

- Kiran
September 26, 2007 20:55
Hey Scott... Instead of rebuilding to make something x86 I usually try corflags /32BIT+ on it first. If it's not signed that usually does the trick. I do this quite often.
September 28, 2007 11:10
The Ayende code isn't really production code. He said on his blog that it was basically a quick hack that he threw together just as a proof of concept. I, for one, am hoping to see more from him on the topic.
October 02, 2007 1:41
Scott, not sure if there's anything you can do about it but the code snippets don't look right in Google Reader.
Keep up the good work!

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.