Category: .Net

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!

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!

Running Azure Web Role locally

There are a lot of good blogs explaining how to setup your Azure projects and how to convert your MVC web project (or create a new) to use Windows Azure. As part of this setup (Azure SDK installation), you will install Azure Emulators (Storage, Compute). These emulators are important part of your local development since it gives you an idea of how your application will behave once hosted in Azure Cloud platform.

You have a choice of running your MVC application and debugging in local (Click on MVC project, hit F5) or you could run and debug your Web Role project associated with your MVC project (Click on Azure Deployment Project that has the Web Role and hit F5)

If you have a setup like me, i.e., I am running a VM on my Mac Book Pro to host Windows 7 to do my Visual Studio work, and I have a named SQL Server instance, you might run into following error when you run your Web Role locally

Windows Azure Tools: Failed to initialize Windows Azure storage emulator. Unable to start Development Storage. Failed to start Storage Emulator: the SQL Server instance ‘localhost\SQLExpress’ could not be found.   Please configure the SQL Server instance for Storage Emulator using the ‘DSInit’ utility in the Windows Azure SDK.

Ok, this was a descriptive enough error message, and I promptly ran my Azure Command line and ran DSInit. That ended up giving me following error message.

DSInit-Error

If you had a default instance of SQL Server running, then I think running DSInit without any command line options would  have worked, a quick web search gave me all the options that DSInit supported (http://msdn.microsoft.com/en-us/library/windowsazure/gg433005.aspx).

With this new found information, I changed my command to:

DSInit /server:WIN-F3VL38TDD1B\MACSQL

Voila, it ran successfully and created the local database it required to run the emulator.

Now that I had my local storage emulator running successfully, I was able to hit F5 to debug and run the web role locally.

More Azure exploration ahead…tune in soon.

Cheers!

Binu