dotnet thoughts 

a dotnet developer's technical blog

Quick introduction to MS Test

Recently I started using MS Test, moved from NUnit tests to MS Test. Mainly the reason for adopting MS Test is the ability to measure code coverage from Visual Studio itself. In this post I am quickly introducing MS Test for developers.

  1. Created a class library – SampleCalcLib. And added a class file, which do two mathematical operations Addition and Division.
  2. using System;
    namespace SampleCalcLib
    {
        public class CalcLib
        {
            public int Addition(int a, int b)
            {
                return a + b;
            }
    
            public int Division(int a, int b)
            {
                if (b == 0)
                {
                    throw new DivideByZeroException();
                }
                return a / b;
            }
        }
    }
    
  3. Created a Test Project. – SampleCalcTest – This project contains the Test methods verify the Addition and Division methods.
  4. using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using SampleCalcLib;
    namespace SampleCalcTest
    {
        [TestClass]
        public class CalcLibTest
        {
            [TestMethod]
            public void TestAddition()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 20;
                int actual = a + b;
                int expected = calcLib.Addition(a, b);
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            public void TestDivision()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 20;
                int actual = a / b;
                int expected = calcLib.Division(a, b);
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            [ExpectedException(typeof(DivideByZeroException))]
            public void TestDivisionExpectingDivideByZeroExecption()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 0;
                int expected = calcLib.Division(a, b);
            }
        }
    }
    
  5. Now the solution explorer will look like the following.
  6. Solution Explorer

    Solution Explorer

  7. We can also right click on a method and select Create Unit Test option, which will create test project and add test method to it.
  8. You can find all the tests in the test project using Test View window. You can get Test View from Test menu Windows and then select Test View.
  9. Test View window

    Test View window

  10. To Run the test by right clicking on the project in the Test View window.
  11. You can view the Test Results from Test Results window.
  12. Test Results

    Test Results

I will post how to enable and view code coverage in the next post

How to Initialize a Dictionary with a Collection Initializer

You can initialize any list and add items to inline using like the following.

List<Person> Persons = new List<Person>
{
    new Person { Age = 20, Name = "Name" }
};

But this will not work Dictionary, if you try; you will get a compile time error like “No overload for method ‘Add’ takes 1 arguments”

You can fix this issue by putting a pair of curly braces.

Dictionary<int, Person> PersonsWithId = new Dictionary<int, Person>
{
    { 10, new Person { Age = 20, Name = "Name" } }
};

You can get more info about this MSDN

How to unit test asynchronous callbacks

The current project I am working, we are following TDD (Test Driven Development). Today I got a problem; I need write a unit test for verifying an asynchronous callback.

I need to invoke the method and need to wait for the callback handler to call. I thought of thread synchronization and various other methods, but .Net Framework comes with a handy class, AutoResetEvent; which we can initially set to false and wait for it to become true. And in the event handler we need set it to True.

using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class DemoCallback
{
    AutoResetEvent _autoResetEvent;

    [TestMethod]
    public void TestDemoClass()
    {
    //Setting the event to false.
    this._autoResetEvent = new AutoResetEvent(false);
    //Creating the instance of Unit Test object
    DemoClass _demoObject = DemoClassFactor.CreateInstance();
    _demoObject.DemoCallback(() =>
    {
	    //Do something in the callback
	    this._autoResetEvent.Set();
    });
    _demoObject.DoAsync();
    //Waiting indefinitely - can also put interval.
    Assert.IsTrue(this._autoResetEvent.WaitOne());
    }
}

You can also use ManualResetEvent; which will help more than one threads. You can get more information about AutoResetEvent in MSDN.

ASP.NET MVC 3 RTM Released

The ASP.NET team has released RTM version of ASP.NET MVC 3. You can download the ASP.NET MVC 3 RTM from here. Microsoft has released the following products along with ASP.NET MVC 3. You can find the source code of ASP.NET MVC 3 can download from here

  • NuGet
  • IIS Express 7.5
  • SQL Server Compact Edition 4
  • Web Deploy and Web Farm Framework 2.0
  • Orchard 1.0
  • WebMatrix 1.0

How to compile C# code snippet in runtime

Yesterday one of colleague called me and asked how I can compile code from a text source. I explored System.CodeDom classes. And I found one way to create executable (libraries too) using CSharpCodeProvider class.

using (CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider())
{
    this._OutPutFile = Path.ChangeExtension(Path.GetTempFileName(), ".exe");
    CompilerParameters parameters = new CompilerParameters()
    {
        //For creating DLLs it should be false
        GenerateExecutable = true,
        OutputAssembly = this._OutPutFile,
        //For displaying warnings in the compilerResults
        WarningLevel = 4
    };
    //I am reading the text from a WPF RichTextbox
    TextRange textRange =
        new TextRange(this.txtEditor.Document.ContentStart,
            this.txtEditor.Document.ContentEnd);
    CompilerResults compilerResults =
        csharpCodeProvider.CompileAssemblyFromSource(parameters, textRange.Text);
}

For more details you can found in MSDN

DotNet Snippet compiler (I created a WPF application which used to compile C# snippets, I will make it open source soon.) running on my system.

WPF Snippet compiler

WPF Snippet compiler

Older Posts »