Must Read for Web Developers

Unit Testing Improvements in Visual Studio 2011

In the past, one big reason why people did not embrace MS Test (I think) is because Visual Studio 2008/2010 did not provide a good environment that supported Unit Testing. Sure it did had MS Test and its runner, but it was weak compared to Test Runner from Jet Brains ReShareper or TestDriven.net. I think someone at Microsoft listened to and as I result, there is many notable improvements in this area in Visual Studio 2011.

Below screenshot shows Visual Studio 2011 with Unit Testing related Menu marked.
Under Run Unit Tests, options are all self explanatory.

Menus shown below:

There is an option Unit Test > Unit Test Setting called “Run Tests after Build”, using by which you can always run all the unit tests after each time you build. This is a good practice, and if you manage it well i could be useful. Personally I think I would always kick off my test/s manually, its just my preference now. Also I would have a well scripted local build that can take care of building all components and running my unit and integration tests automatically.

BYO TF (Bring your own Test Framework)

I am not a fan of Ms Test (I think I made that clear earlier), I use NUnit and I have no idea to switch to another framework. What I like about this edition of Visual Studio, is that, it supports other testing frameworks like NUnit through test adapters. If you are using NUnit like me, download NUnit Test Adapter from here > Link
Visit this page for information on all available at this time > Link

Another way of getting third party frameworks is to use the Extension Manager, Click on Tools > Extension Manager to launch extension manager, then under Online Extensions, Expand Visual Studio Gallary, Select Tools, and click on Testing.

Test Explorer

Test Explorer lists all the Tests grouped by Failed, Passed, etc. You can right click and run individual tests, or debug tests.

Code Coverage

Visual Studio 2011 packs a code coverage tool also. This is a great feature addition. In the past, I had to purchase a tool like dotCover to do this for me. By double clicking on each line in the coverage results window, you can inspect the parts of your code that lacks coverage (or be proud to see every piece of code has 100% coverage and green)

More later, Happy Coding
Cheers!

Fast & Simple Data Access using Dapper.net

Dapper is a micro-ORM. It helps you to create a strongly typed result by providing you an easy way to work with your database. It is simple to use, it does simple stuff, essentially extends your IDBConnection interface. So if you are looking for a way to query your data real fast (yes, this is the fastest it gets barring pure ADO.net), you should checkout Dapper.net. It is developed by some smart folks over at Stackoverflow.com ! (Another good reason to try it out!)

Installing Dapper

It is simple to install Dapper, you could simply use Nuget Package Manager to add Dapper to your project. From Visual Studio, Click on Tools > Library Package Manager > Package Manager Console
Type in Install-Pacakage Dapper and hit Enter

In order to demonstrate Dapper, we will use the standard Microsoft sample database NorthWind.

In NorthWind database Customers table represent customers and Orders table represent Orders placed by all the customers.

Here are some POCOs we will use:

    internal class Customer
    {
        public string CustomerId { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public IEnumerable<Order> Orders { get; set; }   
    }

    internal class Order
    {
        public int OrderId { get; set; }
        public DateTime OrderDate { get; set; }
    }

A useful helper class that would get us a valid, opened SqlConnection object

    internal static class SqlHelper
    {
        public static SqlConnection GetOpenConnection()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["NorthWind"];
            var connection = new SqlConnection(connectionString.ToString());
            connection.Open();
            return connection;
        }
    }

And a Data Access class that actually does some work !!

    internal class CustomerDao
    {
        public IEnumerable<Customer> GetAll()
        {

            const string sql = "Select * from Customers";
            using (var connection = SqlHelper.GetOpenConnection())
            {
                return connection.Query<Customer>(sql);
            }
        }

        public IEnumerable<Customer> GetById(string customerId)
        {

            const string sql = "Select * from Customers where CustomerId = @id";
            using (var connection = SqlHelper.GetOpenConnection())
            {
                return connection.Query<Customer>(sql, new { Id = customerId });
            }
        } 

        public IEnumerable<Order> GetOrders(string customerId)
        {
            const string sql = @"select o.Orderid, o.OrderDate from Customers c inner join Orders o 
                                 on c.CustomerId = o.CustomerId and c.CustomerId = @Id";

            using (var connection = SqlHelper.GetOpenConnection())
            {
                return connection.Query<Order>(sql, new { Id = customerId });
            }
        }


    }

Above class illustrates some very a straight select and some simple joins. You can use the same strategy to run your insert and update queries. Dapper also supports multi-mappings where you can auto map your aggregates and multiple result sets also. For more visit Dapper page on Google code: http://code.google.com/p/dapper-dot-net/

Here is some tests that actually tests the code above:


    [TestFixture]
    public class DapperTest
    {
        private CustomerDao _customerDao;
        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            _customerDao = new CustomerDao();
        }
        [Test]
        public void CreateConnection_ReturnsNotNull()
        {
            var connection = SqlHelper.GetOpenConnection();
            Assert.That(connection, Is.Not.Null);
        }
        [Test]
        public void GetAllCustomers_Returns_Records()
        {
            var allCustomers = _customerDao.GetAll();
            Assert.That(allCustomers.Count(), Is.Not.EqualTo(0));
        }

        [Test] 
        public void GetCustomers_With_Where_Clause()
        {
            var testId = "BERGS";
            var allCustomers = _customerDao.GetById(testId);
            Assert.That(allCustomers.Count(), Is.Not.EqualTo(0));
        }

        [Test]
        public void GetOrders_For_Customer()
        {
            const string testId = "BERGS";
            var orders  = _customerDao.GetOrders(testId);
            Assert.That(orders.Count(), Is.Not.EqualTo(0));
        }



    }

Massive and Peta Poco are two other micro ORMs that competes with Dapper. You can find Massive here => https://github.com/robconery/massive and Peta Poco here => http://www.toptensoftware.com/petapoco/

(I haven’t tried Massive, but have played with Peta Poco. I find auto mapping features are better in Peta Poco compared to Dapper)

I hope you enjoyed this post! Happy Programming!
Cheers!

Nuget Package Manager update issues

Have you gotten this error when you were trying to install a nuget package (in my case NUnit) and it suggests that you upgrade NuGet to latest version.

My problem was when I tried to do this, I ended up getting error like the one shown below (I was using Visual Studio 2010 Premium)

Here are the steps to work around and get your NuGet upgraded.
1. Run Visual Studio 2010 as an Administrator
2. Use Tools > Extension Manager and Remove the existing Nuget Package Manager
3. This will restart the Visual Studio 2010, Close and start again as Administrator
4. Click on Online Gallery, Pick Nuget Package Manager and install
5. This will restart Visual Studio again, and you are good to go!!!


Cheers!

Temporary File Storage for Azure Web Role

First, make sure that you design for cloud operating system, this way your application will not require to write to some specific file path or directory etc. But there will be instances where you will need to write or save a file in a local path somewhere. Azure helps us to do this by means of “LocalResource”

To set this up, its simple, open your ServiceDefinition.csdef file,
Add under section,

<WebRole name="MyWebRole" vmsize="Small">
   ...
   ...
   <LocalResources>
       <LocalStorage name="MyLocalStorage" sizeInMB="10" />
   </LocalResources>
</WebRole>

One you have this, your role environment will get you a local resource when its running, (even when using an emulator on local)

Now you are ready to use local file system on Azure, here is how you access:

if (RoleEnvironment.IsAvailable) // this guard helps not to throw error when running outside emulator in local
{
LocalResource localResource = RoleEnvironment.GetLocalResource("MyLocalStorage");
Debug.WriteLine (localResource.RootPath);
}

Cheers!

Windows Azure Training Kit