Git goodness (officially) available in Visual Studio

I have a great deal of admiration for the .NET dev teams at Microsoft. (This is in stark contrast to my opinions of the product marketing teams, but that’s another story.) In recent years, the teams working around Microsoft’s dev tools have moved away from closed, proprietary tools, to embrace a more open philosophy, where it is perfectly acceptable to incorporate open software such as JQuery their flagship product, Visual Studio.

In 2008 the dev team, led by Scott Gu, released the source code to the .NET framework – a feat (apparently) only possible after a protracted battle with the Microsoft legal department.

Well, it seems that Microsoft are continuing in the right direction, with the release of Visual Studio Tools for Git. It was about time, but it’s a good thing none-the-less!

So while I’m here with the Microsoft fanboi cap on, I’ll give kudos to a couple of game-changers who work, or have worked, at Microsoft:

  • Anders Hejlsberg, who has kept the C# ship on course for 13 years.
  • Scott Gu and Phil Haack, for their technical and cultural leadership. Without them we would have no (or a greatly inferior) MVC framework.
  • Scott Hanselman, who continues to be a force of positive change at Microsoft’s dev div.
  • I know there are many other well respected guys and gals working for the corporation, but the above mentioned have, in my view, kick-started a cultural change that has been good for all developers working around the .NET stack. Thanks to everyone involved for bringing us an awesome development platform!

    Advertisements

    IronPython Scripts and C# Interop

    I’m currently working on a project with requires scripts to execute within the .NET environment. After choosing IronPython as the scripting language, I began scouring the web for examples… Here is the code I cobbled together!

    [edit] I’ve updated the source code to allow instantiating a class with constructor arguments. [/edit]

    The code here demonstrates recipes for 3 types of interop:

    1. Create a dynamic instance of a script and call a method.
    2. Create a dynamic instance of a Python class and call a method.
    3. Imlement a .NET interface in Python and call it from C#.

    This example is split between a helper class and a test class:

    public class PythonScript
    {
        private string _script;
        private readonly ScriptEngine _engine = Python.CreateEngine();
    
        public PythonScript() { }
    
        public PythonScript(string script)
        {
            _script = script;
            _engine = Python.CreateEngine();
        }
    
        public PythonScript(params string[] script)
            : this(CreateScriptString(script))
        {
        }
    
        private static string CreateScriptString(string[] script)
        {
            StringBuilder scriptBuilder = new StringBuilder();
            foreach (string line in script)
            {
                scriptBuilder.AppendLine(line);
            }
            return scriptBuilder.ToString();
        }
    
        public string Script
        {
            get { return _script; }
            set { _script = value; }
        }
    
        public dynamic CreateScriptObject()
        {
            dynamic scriptScope = _engine.CreateScope();
    
            ScriptSource scriptSource = _engine.CreateScriptSourceFromString(_script, SourceCodeKind.Statements);
            scriptSource.Execute(scriptScope);
    
            return scriptScope;
        }
    
        public T CreateInstance<T>(string nameOfClass)
        {
            return CreateInstance(nameOfClass);
        }
    
        public dynamic CreateInstance(string nameOfClass)
        {
            ScriptScope scriptScope = _engine.CreateScope();
    
            ScriptSource scriptSource = _engine.CreateScriptSourceFromString(_script, SourceCodeKind.Statements);
            scriptSource.Execute(scriptScope);
    
            dynamic pythonClass = scriptScope.GetVariable(nameOfClass);
    
            return pythonClass();
        }
    }
    

     

    [TestFixture]
    public class PythonScriptTests
    {
        [Test]
        public void should_get_hello_message_from_scripted_python_method()
        {
            PythonScript script = new PythonScript(
                "def say_hello():",
                "    return 'Hello from Python!'"
                );
    
            dynamic helloScript = script.CreateScriptObject();
            string helloMessage = helloScript.say_hello();
    
            Assert.AreEqual("Hello from Python!", helloMessage);
        }
    
        [Test]
        public void should_get_hello_message_from_python_class()
        {
            PythonScript script = new PythonScript(
                "class HelloClass:",
                "    def say_hello(self):",
                "        return 'Hello from Python!'"
                );
    
            dynamic helloClass = script.CreateInstance("HelloClass");
            string helloMessage = helloClass.say_hello();
    
            Assert.AreEqual("Hello from Python!", helloMessage);
        }
    
        [Test]
        public void should_get_hello_message_from_python_class_implementing_a_dot_net_interface()
        {
            PythonScript script = new PythonScript(
                "import clr",
                "clr.AddReference('R22.Tests')",
                "from R22.Tests import ISayHello",
                "class HelloClass (ISayHello):",
                "    def SayHello(self):",
                "        return 'Hello from Python!'"
                );
    
            ISayHello helloClass = script.CreateInstance<ISayHello>("HelloClass");
            string helloMessage = helloClass.SayHello();
    
            Assert.AreEqual("Hello from Python!", helloMessage);
        }
    }
    
    public interface ISayHello
    {
        string SayHello();
    }
    

    Please note that you will need to reference the IronPython and Microsoft.Scripting dlls in order to run this code. For a working example, please refer to this VS2010 solution.

    Hope you find this useful. Happy coding!

    A Definition of Test Driven Development

    I just read a post by Jean-Paul Boodhoo in which he describes his view of TDD.

    From the post:

    I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it’s functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on.

    I think that is a pretty helpful definition. Thanks JP!

    Rounding numbers to the nearest x.

    Today we came across a very simple rounding problem: round a number up to the nearest 0.05.

    A quick search came up with quite a few hints, but no concrete answer. So we rolled our own. Here’s the code.

    using System;
    
    namespace Util
    {
        public class MathHelper
        {
            public static double RoundNumberUp(double number, double roundingFactor)
            {
                double rounded = RoundNumber(number, roundingFactor);
                if ((number - rounded) > 0)
                {
                    rounded = rounded + roundingFactor;
                }
    
                return rounded;
            }
    
            public static double RoundNumber(double number, double roundingFactor)
            {
                double rounded = Math.Round(number * (1 / roundingFactor)) / (1 / roundingFactor);
    
                return rounded;
            }
        }
    }
    

    And here are the tests, which show how to use the class.

    using NUnit.Framework;
    using Util;
    
    namespace Util.Tests
    {
        [TestFixture]
        public class MathHelperTests
        {
            [Test]
            public void Should_round_a_number_up_to_the_nearest_0_05()
            {
                double result = MathHelper.RoundNumberUp(6.66, 0.05);
                Assert.AreEqual(6.7, result, 0.001);
    
                result = MathHelper.RoundNumberUp(6.7, 0.05);
                Assert.AreEqual(6.7, result, 0.001);
    
                result = MathHelper.RoundNumberUp(6, 0.05);
                Assert.AreEqual(6, result, 0.001);
    
                result = MathHelper.RoundNumberUp(6.13, 0.05);
                Assert.AreEqual(6.15, result, 0.001);
    
                result = MathHelper.RoundNumberUp(6.18, 0.05);
                Assert.AreEqual(6.2, result, 0.001);
            }
        }
    }
    

    Hope this comes in handy! Bye for now.

    Get on the TDD bandwagon!

    Earlier this month me and a few guys at work decided to delve head first into test driven development. We had always done things the old fashioned way and decided it was time to catch up with more robust development techniques.

    We knew it would be painful at the beginning, but the rewards of TDD are too good to ignore. And painful it was… At first development was extremely slow! Thinking about what to test was difficult. Thinking about how to test was also hard! But we persevered, moving slowly from one test to the next, and testing each new class and method as we invented them.

    I think it was about one week in, that this experiment started to bear real fruit. We started to notice that, in the process of developing the tests, we were designing our program from the outside in. This reminded me of something Jean-Paul Boodhoo has repeated over and over in various screencasts: In writing the tests for our programs we are actually driving out the design of our programs!

    The most obvious benefit of the TDD approach is adherance to the YAGNI agile principle. It is often very tempting to write some code which solves a problem that you have anticipated. The problem with this is that you may well NOT need this code! TDD overcomes this anticipation by dictating that you write only the code needed to satisfy your tests. At the start this can feel restrictive, but as you move on this becomes liberating.

    The second obvious benefit of TDD is that you tend to write functional, loosely coupled code. By starting from class names, then filling in the gaps with the methods you need, I have found that I am creating more useful classes with less bloat. When you specify a method you are forced to think carefully what parameters you should be passing to it and what object, if any, it should return.

    The approach of designing classes from the outside is totally different than designing them from the inside. I’d say you get a birds eye view over your software when using TDD. This is far better than forever being bogged down by tiny details…

    All in all I’d say I’m now a huge fan of TDD!! I’m still taking baby steps, but the more I use agile development techniques the more I see the huge benefits!

    Recommendations:
    Agile Principles, Patterns, and Practices in C# by Robert C. Martin.
    dnrTV! – Check out the episodes with JP Boodhoo and Venkat Subramaniam!
    DotNetRocks! – A twice weekly .NET podcast.

    Compress and decompress strings in .NET

    I recently had the need to store strings in a database in a compressed format. I wanted to store some potentially long strings in a SQL server image type column. After some time searching the internet for solutions I came across a neat .NET namespace called System.IO.Compression which looked like it could be the answer to my problem…

    Here is the helper class I wrote to perform compression and decompression:

    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.Text;

    namespace Utility
    {
    public static class CompressionHelper
    {
    public static byte[] CompressText(string text)
    {
    byte[] buffer = Encoding.UTF8.GetBytes(text);
    MemoryStream compressedStream = new MemoryStream();
    DeflateStream compressedZipStream = new DeflateStream(compressedStream, CompressionMode.Compress, true);
    compressedZipStream.Write(buffer, 0, buffer.Length);
    compressedZipStream.Close();
    compressedStream.Position = 0;
    byte[] compressed = new byte[compressedStream.Length];
    compressedStream.Read(compressed, 0, (int)compressedStream.Length);
    return compressed;
    }

    public static string DecompressText(byte[] compressed)
    {
    MemoryStream compressedStream = new MemoryStream(compressed);
    DeflateStream zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress);
    List bytes = new List();
    int offset = 0;
    while (true)
    {
    byte[] temp = new byte[offset + 100];
    int bytesRead = zipStream.Read(temp, offset, 100);
    if (bytesRead == 0)
    {
    break;
    }
    for (int i = offset; i < offset + bytesRead; i++) { bytes.Add(temp[i]); } offset += bytesRead; } return Encoding.UTF8.GetString(bytes.ToArray()); } } } [/sourcecode] Of course you could argue that this class is too specialised right now. It served my purpose well, but you could take and return byte arrays or streams as parameters to make it more general and re-use friendly. Please let me know if you find any bugs... Enjoy!