Count the number of lines in your project with one line of Powershell

ls * -recurse -include *.aspx, *.ascx, *.cs, *.ps1 | Get-Content | Measure-Object -Line

Just replace the file extensions with the ones you use in your project.

Posted in PowerShell | Leave a comment

Useful Moq Extension Method

I have been working with ASP .NET MVC and I use the Moq mocking library to help test the code I write.   Often in ASP MVC anonymous objects are passed around as function arguments.  This is especially common in calls to RouteUrl.  Since I want to be able to test this and verify that it is called correctly I wrote a handy extension method to make it easier called AsMatch.

To be able to test the UrlHelper (since it doesn’t have an interface or virtual methods) I wrote a simple wrapper around it with an interface to enable testing.  Using that with this extension method makes testing route generation a breeze.

Given a call to generate a Url like this:

var url = Url.RouteUrl("Show", new { projectName="matt" });

You can write a setup on your Mock of the Url helper using a similar syntax:

UrlHelperMock
.Setup(x => x.RouteUrl("Show",new{ projectName="matt"}.AsMatch()))
.Return("someUrlToTest");

Here is the code that defines the AsMatch extension method:

public static class ObjectMoqExtensions
{
    public static object AsMatch(this object @object)
    {
        return Match<object>.Create(testObject => DoObjectsMatch(@object, testObject));
    }

    private static bool DoObjectsMatch(object object1, object object2)
    {
        var props1 = ToDictionary(object1);
        var props2 = ToDictionary(object2);
        var query = from prop1 in props1
                    join prop2 in props2 on prop1.Key equals prop2.Key
                    select prop1.Value.Equals(prop2.Value);
        return query.Count(x => x) == Math.Max(props1.Count(), props2.Count());
    }

    public static Dictionary<string, object> ToDictionary(object @object)
    {
        var dictionary = new Dictionary<string, object>();
        var properties = TypeDescriptor.GetProperties(@object);
        foreach (PropertyDescriptor property in properties)
            dictionary.Add(property.Name, property.GetValue(@object));
        return dictionary;
    }
}
Posted in ASP .NET MVC, C#, Moq | Leave a comment

Converting RTF to HTML

Have you ever had the desire to convert some RTF text into HTML? Probably not. But if you do, then you are in luck! I recently had the need to do this conversion and after some searching found out a way to do it by enhancing a sample distributed in the MSDN library.  The sample is called: XAML to HTML Conversion Demo

The sample has code which converts HTML to and from a XAML Flow Document.  But this doesn’t make things easier until you realize that there is a way to convert RTF to XAML easily. The key is to use System.Windows.Controls.RichTextBox which can load RTF from a stream and save it as XAML.  This conversion is shown below:

private static string ConvertRtfToXaml(string rtfText)
{
    var richTextBox = new RichTextBox();
    if (string.IsNullOrEmpty(rtfText)) return "";
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    using (var rtfMemoryStream = new MemoryStream())
    {
        using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream))
        {
            rtfStreamWriter.Write(rtfText);
            rtfStreamWriter.Flush();
            rtfMemoryStream.Seek(0, SeekOrigin.Begin);
            textRange.Load(rtfMemoryStream, DataFormats.Rtf);
        }
    }
    using (var rtfMemoryStream = new MemoryStream())
    {
        textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
        textRange.Save(rtfMemoryStream, DataFormats.Xaml);
        rtfMemoryStream.Seek(0, SeekOrigin.Begin);
        using (var rtfStreamReader = new StreamReader(rtfMemoryStream))
        {
            return rtfStreamReader.ReadToEnd();
        }
    }
}

With this code we have all we need to convert RTF to HTML. I modified the sample to add this RTF To XAML conversation and then I run that XAML through HTML converter which results in the HTML text. I added an interface to these conversion utilities and converted the sample into a library so that I would be able to use it from other projects.  Here is the interface:

public interface IMarkupConverter
{
    string ConvertXamlToHtml(string xamlText);
    string ConvertHtmlToXaml(string htmlText);
    string ConvertRtfToHtml(string rtfText);
}

public class MarkupConverter : IMarkupConverter
{
    public string ConvertXamlToHtml(string xamlText)
    {
        return HtmlFromXamlConverter.ConvertXamlToHtml(xamlText, false);
    }
    public string ConvertHtmlToXaml(string htmlText)
    {
        return HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, true);
    }
    public string ConvertRtfToHtml(string rtfText)
    {
        return RtfToHtmlConverter.ConvertRtfToHtml(rtfText);
    }
}

With this I am now able to convert from RTF to HTML.  However, there is one catch – the conversion uses the RichTextBox WPF control which requires a single threaded apartment (STA).  Therefore in order to run your code that calls the ConvertRtfToHtml function, it must also be running in a STA.  If you can’t have your program run in a STA then you must create a new STA thread to run the conversion. Like this:

MarkupConverter markupConverter = new MarkupConverter();

private string ConvertRtfToHtml(string rtfText)
{
   var thread = new Thread(ConvertRtfInSTAThread);
   var threadData = new ConvertRtfThreadData { RtfText = rtfText };
   thread.SetApartmentState(ApartmentState.STA);
   thread.Start(threadData);
   thread.Join();
   return threadData.HtmlText;
}

private void ConvertRtfInSTAThread(object rtf)
{
   var threadData = rtf as ConvertRtfThreadData;
   threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
}


private class ConvertRtfThreadData
{
   public string RtfText { get; set; }
   public string HtmlText { get; set; }
}
Posted in C#, HTML, RTF, WPF, XAML | Leave a comment

I finally got fed up with Enum.Parse

I don’t know why I didn’t do this long ago, but I am done writing this:

var val = (SomeEnum)Enum.Parse(typeof(SomeEnum),”someString”);

I have typed this too many times and it annoys me.

I wrote a small extension method on the string type to make this better:

public static class StringExtensions
{
    public static T ToEnum<T>(this string @string)
    {
        return (T)Enum.Parse(typeof (T), @string);
    }
}

With this I can now write the previous line as:

var val = "someString".ToEnum<SomeEnum>()

It is a bit shorter and I think much more readable.

Posted in C# | Leave a comment

DRY and Unit Tests don’t mix well

When reading source code, I sometimes come across unappealing code(sometimes even my own).  However, there is one kind of “bad code” I see quite frequently.  It is a set of unit tests which have had the DRY (Don’t Repeat Yourself) principle unduly forced upon them.  DRY is the idea that you shouldn’t have to write the same code over and over; abstract it in a function or a class and just call the abstraction.  This is all well and good in most cases, but I find it misguided when applied to a test case. 

A test case should be like a simple short story.  The characters are introduced, action/conflict occurs and then resolution takes place (sometimes with a moral).  This (kind of) corresponds to the 3 steps of a unit test: arrange, act and assert.  You arrange and setup what you need for your test to run, you perform the action that you are trying to test and then you assert the results. The issue I find is that a coder, in attempting to apply DRY to his test cases, will abstract away all of the arrange step into a function often with a name like SetupExpectations or just Setup.  This goes against the point of a test case. A test case needs to be concise and tell me everything I need to know about how that one bit of functionality works. I don’t want to jump around the test class trying to read one test case. To me, this is like reading a book that says, “If you want to learn about the characters in this book please open this other book.”  This doesn’t stop you from understanding the test, but it slows you down…and is just annoying.

 

That is why I will come out and say do not apply DRY haphazardly to test cases.

Posted in Programming, testing | Leave a comment

How to teach your girlfriend Hexadecimal?

It is an age old question: How do you teach your girlfriend hex?

I encountered this problem when I was a web developer in college for a late night student activities program aptly named  Late Nite Binghamton.  My co-worker and girlfriend Mallory was a graduate assistant for the program and had many ideas for how to make the website better and more engaging.  While working with her she would often see me typing in the hexadecimal color codes in css such as:

color: #F24A7D

As I am inept with what color look good (I often say that I never learnt colors) I would often ask her for help with picking out colors and I decided that if she was able to give me these colors in their hex color codes it would make us more efficient :) I sat her down and described to her how they work but after talking for a bit I realized that although she understood everything that I said she wouldn’t gain a feel for what hex numbers related to what colors just from hearing me talk.

In order to help her gain this feel I created a simple game called The Mallory Color Guessing Game.  The game is a webpage which shows you a large colored box and it is your job to guess what the hex color code is. 

image

 

After you guess it tells you how close you were to the actual color:

image

 

This game was a hit! Mallory loved it and she would compete with me to see who could guess the color the best.  Pretty quickly she gained a feel for what the hex digits meant and what color they represented. And that is how I taught my girlfriend hex!

 

NOTE: Mallory consistently gets over 80% at the Mallory Color Guessing Game. 

Posted in Personal | Leave a comment

Snippet Designer in April’s MSDN Magazine!

I am excited to announce that the Snippet Designer is featured in the April issue of MSDN Magazine. 

msdnMag

 

 

 

 

 

 

 

 

 

It is featured in the Toolbox column where they highlight useful tools and blogs. Here is a snippet of what it says:

Creating Code Snippets is a lot easier when using Snippet Designer (version 1.1), a free, open-source Add-In for Visual Studio 2008 for creating and editing Code Snippets directly within the IDE. Once you install it, creating a new Code Snippet is as easy as going to the File menu and creating a new Code Snippet File.

 

That is so cool! If you are interested go and download the Snippet Designer from the Codeplex website and give me more feedback.

 

Also, in the same article my friend Sara Ford had her blog featured.  When I found out the Snippet Designer and Sara’s blog were in the magazine I quickly emailed to ask Sara if she knew about it.  She already did and also had an extra copy of the magazine for me!

Posted in Personal, Snippet Designer | Leave a comment

A functional take on console program loop in F#

Often when learning a new technology I start with a simple console application in which the program is run in a loop it continues to prompt you for more input until you give some command like quit or exit or whatever you choose:

Enter input: someInput
someOutput
Enter input: otherInput
someoutPut
Enter input: quit
Thanks! Come again!

The code for this is in an imperative language is usually something like:

while(true)
{
    Console.Write("\nEnter input:");
    var line = Console.ReadLine();
    if(line == "quit") break;

    doSomething(line);
}

Console.WriteLine("Thanks! Come Again");

While reading some F# samples, I saw some code doing essentially the same thing which looked something like:

Console.Write "\nEnter input:"
let mutable input = Console.ReadLine()
while input <> "quit"
   do

   if input <> "quit"
   then
       doSomething input
       Console.Write "\nEnter input:"
       input <- Console.ReadLine()

Now this just feels dirty! In a functional language explicit loop constructs like a while loop feel wrong.  I different way of doing this which is more functional is to create an infinite list of actions.  Where each action represents one iteration of any of the above loops. Then you just execute each action until some condition is met (like seeing the input “quit”).

let action = fun _ ->
    Console.Write "\nEnter input: "
    Console.ReadLine()

let readlines = Seq.init_infinite (fun _ -> action())

let run item = if item = "quit"
                then Some(item)
                else
                    parse item
                    None

Seq.first run readlines |> ignore
Console.WriteLine "Thanks! Come Again"

This code makes use of the Seq.init_infinite which create a infinite sequence and Seq.first which enumerates the sequence until the passed in function returns Some.

Posted in F# | Leave a comment

Synchronizing Scrollbars using JQuery

I just wrote this simple plugin for JQuery which lets you synchronize the scroll bars of any collection of elements.  This lets you move the scrollbar of one div it have the scrollbars’ of the rest of the divs move the same exact amount.

Here is the code:

jQuery.fn.synchronizeScroll = function() {
    var elements = this;
    if (elements.length <= 1) return;

    elements.scroll(
    function() {
        var left = $(this).scrollLeft();
        var top = $(this).scrollTop();
        elements.each(
        function() {
            if ($(this).scrollLeft() != left) $(this).scrollLeft(left);
            if ($(this).scrollTop() != top) $(this).scrollTop(top);
        }
        );
    });
}

Using this is SUPER simple.  Lets say you have several divs defined as:

<div class=”scrollDiv” style=”overflow:auto;”> .. some large content</div>

To synchronize the scrollbars’ on all divs with the class scrollDiv all you need to write is:

$(“.scrollDiv”).synchronizeScroll();

Posted in JQuery, JavaScript | Leave a comment

Prime Factorization using Unfold in Haskell

I randomly yesterday started thinking about the unfoldr function in Haskell while working out at the gym (how nerdy is that, I am lifting iron but thinking of functional programming). Unfoldr take a single and an unfolding function and turns it into a list (the opposite of fold).  At the gym I was thinking about an application where I can use this and I decided that when I got home I would use it to write a prime factorization function.  This is a method that when given a number returns the list of its prime factors.

It was easy to write the only part I am not pleased about is the code I used to deal with tuples.  It seems clumsy and I am still looking for a way to clean that up.

One note: The code below references a list of prime numbers called primes , which is not shown.

Here is the code:

primeFactors x = unfoldr findFactor x
                where
                  first (a,b,c) = a
                  findFactor 1 = Nothing
                  findFactor b = (\(_,d,p)-> Just (p, d))
                                 $ head $ filter ((==0).first)
                                 $  map (\p -> (b `mod` p, b `div` p, p))  primes

This function will take any number which is greater than 1 and return a list of its prime factors.  But don’t take my word for it, I wrote a quickcheck property to ensure the prime factors multiply back to the original number:

prop_factors num =  num > 1 ==> num == (foldr1 (*) $ primeFactors num)

When running quickcheck on this property you see the following:

quickCheck prop_factors
OK, passed 100 tests.

(\(_,d,p)-> Just (p, d))
Posted in Haskell | Leave a comment