Managing deployments to Azure

 The scenario – I am working on an ASP.NET web site that is hosted on Azure as a Cloud Service.

I have automated both the build and the deployment to the cloud using the Bamboo build server. The build compiles the solution, runs the unit tests and generates the deployment packages that are used by Bamboo to deploy the site to Azure.

I could use Bamboo to manage all deployments but given that Cloud Services offer out-of-the-box support for blue-green deployments I decided to take advantage of both systems. This is how I have organised things:

1. Deployment to Staging

Deployment to Staging is performed by Bamboo. Automated tests are executed as part of the deployment to check if everything is working as expected. Additional manual tests should be executed as well before deploying to Production.

bamboo-to-cloud-service

2. Deployment to Production

This is done using the Azure Management Portal – simply click on the Swap button and traffic will be routed to the Staging environment, which now becomes the Production environment.

swap-to-production

3. Rolling Back

Something went wrong? No problem, click on the Swap button again to switch the environments – it’s just as simple as that.

rollback-deployment

Final thoughts

Azure Web Sites or Cloud Services offer out-of-the-box support for blue-green deployments, which provide a simple and powerful way to test a deployment before going to production and roll it back, if necessary.

You can use your Continuous Delivery server in conjunction with Azure Management Portal to manage your deployments to the cloud – consider all the advantages and disadvantages and use the functionalities of each system that makes your life easier 🙂

 

Automate, automate, automate!

keep-calm-and-automate-244

What is usually the first thing that comes to mind when a software developer mentions the words “automate” or “automation“? You might think of automated tests, builds, and deployments. With the rise of Continuous Integration (CI) and Continuous Delivery (CD) in the last few years these are now common practices in many IT companies all over the world.

But it’s not only in the context of CI or CD that we should automate tasks, by the contrary. You should consider automating as much as possible – not only builds and deployments but also other tasks such as installing or configuring applications and services.

 

Continue reading

Using build events to create nuget packages

In this post I’ll show you how to automate the creation of nuget packages using Build Events in Visual Studio.

Table of contents

The Problem

You want to create a nuget package for a class library in order to use it in different applications. You want to execute this task every time you build the project/solution.

The solution

In short, you need to create a .nuspec file for the project and then use a Post-Build Event Command Line to create the package.

For demonstration purposes I created a small class library project that contains my XmlSerializer class. I’ll show you step by step how to create a nuget package for that project.

Continue reading

Code Kata – Numbers to Words, using javascript and TDD

This code kata is based on the KataNumbersInWords kata – convert numbers into words:

  • 3: “three”
  • 159: “one hundred and fifty-nine”
  • 2400: “two thousand and four hundred”

Katas are a good way to learn/practice TDD and/or learn more about a particular technology – in my particular case I decided to to this kata to improve my javascript skills.

The purpose of the exercise is to write the code incrementally, one step at a time – starting with the simplest case scenario (1 digit numbers) and then adding the code to handle the other scenarios (2 digit numbers, 3 digit numbers, etc).

Assume that the input is valid (number).

Test cases:

  • 1 digit numbers
    • 0 should return “zero”
    • 3 should return “three”
    • 7 should return “seven”
  • 2 digit numbers
    • 10 should return “ten”
    • 14 should return “fourteen”
    • 20 should return “twenty”
    • 21 should return “twenty-one”
    • 56 should return “fifty-six”
  • 3 digit numbers
    • 209 should return “two hundred and nine”
    • 300 should return “three hundred”
    • 417 should return “four hundred and seventeen”
    • 560 should return “five hundred and sixty”
    • 698 should return “six hundred and ninety-eight”
  • 4 digit numbers
    • 3004 should return “three thousand and four”
    • 4000 should return “four thousand”
    • 5020 should return “five thousand and twenty”
    • 6300 should return “six thousand and three hundred”
    • 7111 should return “seven thousand and one hundred and eleven”
  • 5 digit numbers
    • 40000 should return “forty thousand”
    • 70393 should return “seventy thousand and three hundred and ninety-three”
    • 87654 should return “eighty-seven thousand and six hundred and fifty-four”
  • 6 digit numbers
    • 500000 should return “five hundred thousand”
    • 803308 should return “eight hundred and three thousand and three hundred and eight”
    • 999999 should return “nine hundred and ninety-nine thousand and nine hundred and ninety-nine”

You can see my implementation here (I’m using WebStorm v8 and JS Test Driver):

Download the code (WebStorm project): NumbersToWords.zip

Implementing a basic IoC container using C#

Implementing a basic IoC container using C#, step by step.

Table of contents

  • References
  • Downloads
  • Continue reading

    Use extension methods to keep your code simple and DRY

    In this article I’ll show you why and how to use generic extension methods to keep your code simple and DRY.

    Table of contents

    The Problem

    Consider this simple model:

    public class Format
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }   
        
    public class Product 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    
        public IEnumerable<Category> Categories { get; set; }
        public IEnumerable<Format> Formats { get; set; }
    
        public bool HasCategories
        {
            get
            {
                if(Categories == null)
                    return false;
    
                return Categories.Any();
            }
        }
    
        public bool HasFormats
        {
            get
            {
                if(Formats == null)
                    return false;
    
                return Formats.Any();
            }
        }
    }
    

    As you can see, I have created to properties HasCategories and HasFormats in the Product class to check if the collections Categories and Formats have any element, respectively.
    The following ASP.NET MVC view shows how these properties can be used:

    @model Product
    
    <h1>@Model.Name</h1>
    
    <p>@Html.DisplayFor(model => model.Description)</p>
    
    <h2>Product Categories</h2>
    
    <ul>
    @if(Model.HasCategories)
        {
            foreach(var category in Model.Categories)
            {
            <li>@category.Name</li>
            }
        }
        else
        {
            <li>This product has no categories</li>
        }
    </ul>
    
    <h2>Formats Available</h2>
    <ul>
    @if(Model.HasFormats)
        {
            foreach(var format in Model.Formats)
            {
            <li>@format.Name</li>
            }
        }
        else
        {
            <li>No formats available</li>
        }
    </ul>
    
    

    There is a problem with this code though – the properties improve the code readability and can be reused, but you may have dozens or hundreds of classes that may need properties like these. It is a verious tedious and time consuming task to create such properties in all the classes we need – a better option would be to create an extension method to do that work for us.

    Extension methods to the rescue

    If you take a good look into the HasCategories and HasFormats properties you can see that the code is similar, the only thing that changes is the type of the properties.

    We can then create a generic extension method to check if any object that implements IEnumerable (List, etc) is null or empty:

    namespace Extensions
    {
        public static class IEnumerableExtensions
        {
            /// <summary>
            /// Determines whether an enumerable is null or empty.
            /// </summary>
            /// <typeparam name="T">Type of the enumerable</typeparam>
            /// <param name="collection">The collection.</param>
            /// <returns>
            ///   <c>true</c> if the enumerable is null or empty; otherwise, <c>false</c>.
            /// </returns>
            public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
            {
                if(collection == null)
                    return true;
    
                return !collection.Any();
            }
        }
    }
    

    There’s no more need to have the properties HasCategories and HasFormats so they can be removed from the Product class. The code now looks simpler and cleaner:

    public class Product 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    
        public IEnumerable<Category> Categories { get; set; }
        public IEnumerable<Format> Formats { get; set; }
    }
    

    Finally, we can change the ASP.NET MVC view to use the extension method:

    @using Extensions
    @model Product
    
    <h1>@Model.Name</h1>
    <p>@Html.DisplayFor(model => model.Description)</p>
    
    <h2>Product Categories</h2>
    <ul>
    @if(Model.Categories.IsNullOrEmpty())
    {
        foreach(var category in Model.Categories)
        {
        <li>@category.Name</li>
        }
    }
    else
    {
        <li>This product has no categories</li>
    }
    </ul>
    
    <h2>Formats Available</h2>
    <ul>
    @if(Model.Formats.IsNullOrEmpty())
    {
        foreach(var format in Model.Formats)
        {
        <li>@format.Name</li>
        }
    }
    else
    {
        <li>No formats available</li>
    }
    </ul>
    
    

    Final thoughts

    In short, you can (and should) use extension methods to keep your code DRY.

    Basically you need to identity pieces of code that are generic enough and replace them with an extension method, if possible. You will have code that is easier to maintain and also more time to develop other funcionalities.

    References

    .NET Guidelines: Should I have one class per file?

    I had this discussion many times over the last few years:

    • Should we have a class per file?
    • What about other types such as interfaces, enums, …?

    Opinions on this subject vary a lot. This purpose of this article is to provide you some basic guidelines and why you should follow them.

    Table of contents

    Continue reading

    Improving LINQ code reusability: Select method

    Select method is used to project each element of a sequence into a new form, i.e. it can be used to map a collection of one type to a collection of another type. In this article I’ll show you a simple approach that will allow you to reuse the code used in the Select method.

    Table of contents

    The Problem

    Consider the following model:

    Let’s suppose that you have a services layer, so you don’t want to expose your domain objects directly to the client applications. Instead you create a set of data contracts (or DTOs, if you prefer):

    At some stage you’ll have to convert those Domain objects to data contracts. This is a common way of doing it:

    var details = repository.All<Album>().Select(album => new AlbumDetail {
        AlbumId = album.AlbumId,
        Price = album.Price,
        Title = album.Title,
    
        ArtistId = album.ArtistId,
        GenreId = album.GenreId,
        ArtistName = (album.Artist == null) ? null : album.Artist.Name,
        GenreName = (album.Genre == null) ? null : album.Genre.Name
    });
    

    There is a problem with this approach – if you need to query the same collection but using different criteria you have to duplicate the code inside the Select method.

    Solution 1 – Creating a method for the mapping

    In order to reuse the code, we can create a method that converts Album objects (Domain) to data contract objects:

    private static AlbumSummary CreateAlbumSummary(Album album)
    {
        return new AlbumSummary {
            AlbumId = album.AlbumId,
            Title = album.Title,
    
            ArtistName = (album.Artist == null) ? null : album.Artist.Name
        };
    }
    
    private static AlbumDetail CreateAlbumDetail(Album album)
    {
        return new AlbumDetail {
            AlbumId = album.AlbumId,
            Price = album.Price,
            Title = album.Title,
    
            ArtistId = album.ArtistId,
            GenreId = album.GenreId,
            ArtistName = (album.Artist == null) ? null : album.Artist.Name,
            GenreName = (album.Genre == null) ? null : album.Genre.Name
        };
    }
    

    Using the code:

    var albums = Albums.Select(CreateAlbumDetail);
    var albumsByGenre = Albums.Where(x => x.GenreId == genreId).Select(CreateAlbumDetail);
    
    // alternative way
    var albums2 = Albums.Select(x => CreateAlbumDetail(x));
    var albumsByGenre2 = Albums.Where(x => x.GenreId == genreId).Select(x => CreateAlbumDetail(x));
    

    Solution 2 – Creating a generic ObjectMapper object

    The previous solution solves the code reusability problem, but there’s still a tight coupling between components. Abstractions should be used to implement loose coupling between components – in this case, to abstract the mapping code.

    Step 1: define a contract (interface) with a method that converts one object of type TSource to an object of type TDestination:

    public interface IObjectMapper
    {
        TDestination Map<TSource, TDestination>(TSource source);
    }
    

    Step 2: create a class that implements IObjectMapper (click to expand):

    public class ObjectMapper : IObjectMapper
    {
        private Dictionary<Type, Func<object, object>> Mappers = new Dictionary<Type, Func<object, object>>
        {
            { typeof(Tuple<Album, AlbumDetail>), CreateAlbumDetail },
            { typeof(Tuple<Album, AlbumSummary>), CreateAlbumSummary }
    
            // more mappings here
            // ....
        };
    
    
        public TDestination Map<TSource, TDestination>(TSource source)
        {
            if(source == null)
                return default(TDestination);
    
            Func<object, object> mapper = null;
            Type key = typeof(Tuple<TSource, TDestination>);
    
            if(Mappers.TryGetValue(key, out mapper))
            {
                var newObject = mapper(source);
                return (TDestination) newObject;
            }
    
            string errorMessage = string.Format("Invalid mapping (Source: {0}, Destination: {1})";,
                                                typeof(TSource).FullName, 
                                                typeof(TDestination).FullName);
            
            throw new InvalidOperationException(errorMessage);
        }
    
    
        private static object CreateAlbumDetail(object source)
        {
            var album = source as Album;
    
            return new AlbumDetail {
                AlbumId = album.AlbumId,
                Price = album.Price,
                Title = album.Title,
    
                ArtistId = album.ArtistId,
                GenreId = album.GenreId,
                ArtistName = (album.Artist == null) ? null : album.Artist.Name,
                GenreName = (album.Genre == null) ? null : album.Genre.Name
            };
        }
    
        private static object CreateAlbumSummary(object source)
        {
            var album = source as Album;
    
            return new AlbumSummary {
                AlbumId = album.AlbumId,
                Title = album.Title,
                
                ArtistName = (album.Artist == null) ? null : album.Artist.Name
            };
        }
    }
    

    Example 1: Using LINQ

    Using the mapper in a LINQ expression – convert an Album collection to an AlbumSummary collection:

    IObjectMapper mapper = new ObjectMapper();
    
    IEnumerable<AlbumSummary> summaries = repository.All<Album>()
                                            .Select(mapper.Map<Album, AlbumSummary>);
    

    Example 1: Mapping a single object

    Using the mapper for a single object:

    var album = new Album {
        AlbumId = 1,
        Price = 10.0m,
        Title = "The Dreamer",
        Artist = new Artist { ArtistId = 1, Name = "José James" },
        Genre = new Genre { GenreId = 1, Name = "Jazz" }
    };
    
    IObjectMapper mapper = new ObjectMapper();
    
    AlbumDetail albumDetail = mapper.Map<Album, AlbumDetail>(album);
    

    Unit Testing

    Some NUnit tests:

    [Test]
    public void Given_a_non_existing_mapping_when_mapping_object_then_should_throw_InvalidOperationException()
    {
        // arrange
        IObjectMapper mapper = new ObjectMapper();
        var albumDetail = new AlbumDetail();
    
        // act/assert
        Assert.Throws<InvalidOperationException>(() => 
            // non-existing mapping
            mapper.Map<AlbumDetail, AlbumSummary>(albumDetail)
        );
    }
    
    [Test]
    public void Given_an_album_when_mapping_to_album_summary_should_equals_expected_album_summary()
    {
        // arrange
        IObjectMapper mapper = new ObjectMapper();
        
        var album = new Album {
            AlbumId = 4,
            Price = 10.0m,
            Title = "Heritage",
            Artist = new Artist { ArtistId = 4, Name = "Opeth" },
            Genre = new Genre { GenreId = 4, Name = "Metal" }
        };
    
        var expectedAlbumSummary = new AlbumSummary {
            AlbumId = 4,
            ArtistName = "Opeth",
            Title = "Heritage"
        };
        
        // act
        AlbumSummary albumSummary = mapper.Map<Album, AlbumSummary>(album);
        
        // assert
        Assert.AreEqual(albumSummary, expectedAlbumSummary);
    }
    

    Final thoughts

    In this article you learned how to reuse the code used in the Select method, and how you can use that code to map single objects. But writing mapping code is tedious and time consuming. There are mapping tools out there that can make your life easier – AutoMapper is one of them. I’ve used it in the past and I definitely recommend it. So, why use Automapper? Quoting their website:

    “What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types”

    “Mapping code is boring. Testing mapping code is even more boring. AutoMapper provides simple configuration of types, as well as simple testing of mappings”

    References

    Downloads

    Download the demo project (VS2010): LINQ-Select.zip

    Technorati Tags: , , ,