Use environment variables to speed up your .NET Core build on VSTS

I’m using Visual Studio Team Services (hosted agent) to automate the builds and deployments of .NET Core solutions.

You probably noticed that .NET Core builds take much more time compared to the traditional .NET builds. For example, when you run the command dotnet restore you might have noticed something like this being logged:

2016-09-15T11:15:39.1510337Z A command is running to initially populate your local package cache, to improve restore speed and enable offline access. This command will take up to a minute to complete and will only happen once.
2016-09-15T11:15:44.7529135Z Decompressing 0%... Decompressing 1% ... (text removed for brevity) Decompressing 100% 5523 ms
2016-09-15T11:16:05.7899968Z Expanding 0%.... Expanding 1%... (text removed for brevity) Expanding 100% 20548 ms
2016-09-15T11:16:29.7176084Z log  : Restoring packages for C:\a\1\s\Development\Source\MyProject\UI\project.json...

As you can see, caching of the packages took almost 1 minute! As suggested in Stop wasting time during .NET Core builds, adding the following environment variables to your build definition can reduce the build time:

.NET Core environment variables

So basically DOTNET_SKIP_FIRST_TIME_EXPERIENCE will prevent the caching of the packages on the build machine, and NUGET_XMLDOC_MODE will prevent the download of the XML documentation for the packages. Unfortunately I couldn’t find much documentation about these variables, but check the blog post above for more details.

Visual Studio: Unable to start debugging on the web server

This happened to me today – I was getting the same error whenever I tried to debug an ASP.NET application using Visual Studio:

Unable to start debugging on the web server. Could not start ASP.NET debugging. More information may be available by starting the project without debugging.

debug1

My initial reaction was to check if there was something wrong in IIS, and I was right: the application pool used by the application I wanted to debug was stopped!

debug2

At that moment I realised that I changed my Windows password 2 or 3 hours before trying to debug the application. Given that the application pool was running under my credentials, all I had to do to fix the issue was to right-click the application pool and go to Advanced Settings > Identity and update my passwordūüôā

 

MSBuild – Access to the path is denied

The problem:

I was configuring a new build on Bamboo CI server for a ASP.NET application. The solution built locally just fine, but consistently failed on the build server. This was the error:

(BeforeBuild target) -> 
  C:\Bamboo\src\MC-BUILD-JOB1\MyProject.Web\MyProject.Web.csproj(1851,5):
 error : Could not write Destination file: 
Access to the path 'C:\Bamboo\src\MC-BUILD-JOB1\MyProject.Web\Config\AppSettings.config' is denied.

The problem was in the following line:

<TransformXml Source="Config\AppSettings.Base.config" 
              Transform="Config\AppSettings.$(Configuration).config" 
              Destination="Config\AppSettings.config" />

So basically the TransformXml task was failing because the file Config\AppSettings.config was checked out as read-only in the build server.

Fortunately there is an easy workaround. The trick is to apply the XML transformations to a temp file and then use the Copy task with the OverwriteReadOnlyFiles attribute set to “True” to overwrite the file Config\AppSettings.config:

<TransformXml Source="Config\AppSettings.Base.config" 
              Transform="Config\AppSettings.$(Configuration).config" 
              Destination="Config\AppSettings_temp.config" />
<Copy SourceFiles="Config\AppSettings_temp.config" 
      DestinationFiles="Config\AppSettings.config" 
      OverwriteReadOnlyFiles="True" />
<Delete Files="Config\AppSettings_temp.config" />

Powershell scripts running on Bamboo don’t return the correct exit code

As part of an deployment project on Bamboo CI, I was running a powershell script to deploy an ASP.NET application to a Cloud Service on Azure.

Even though there was an error executing the script, Bamboo was setting the status of the Deployment to Success. Why? Because the exit code returned by the powershell script is always 0 (zero means successful execution).

After some research I was able to find a way to return the correct exit code in case of failure. I added the following lines to the top of my powershell script:

trap
{
    write-output $_
    exit 1
}

The trap statement includes a list of statements to run when a terminating error occurs – in this case, every time an error occurs the error message will be displayed and then the script will return a correct exit code indicating a failure. I am returning 1 but any value different from 0 (zero) will do the trickūüôā

Refactoring tips and tricks: Exceptions

Consider the following class:

    public class FooService
    {
        private readonly ILogger _logger;

        public FooService(ILogger logger)
        {
            _logger = logger;
        }

        public void Foo()
        {
            try
            {
                // Foo code goes here...
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }

        public void Bar()
        {
            try
            {
                // Bar code goes here...
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }
    }
    

This is a very common scenario that I’ve seen in many different places over the last few years – each method has some code wrapped in a try-catch block. To get rid of the code duplication is easy, we can move the try-catch block to a new method that will take a delegate as a parameter (code to be executed):

    private void Try(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            _logger.LogException(ex);
        }
    }

Refactoring the class:

    public class FooService
    {
        private readonly ILogger _logger;

        public FooService2(ILogger logger)
        {
            _logger = logger;
        }

        public void Foo()
        {
            Try(() => {
                // Foo code goes here...
            });
        }

        public void Bar()
        {
            Try(() => {
                // Bar code goes here...
            });
        }

        private void Try(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
        }
    }

 

 

Using Resharper to detect localizable strings

A few months I had to estimate how much time/effort was involved in localizing one .NET application. As part of this task I had to search for all the hard-coded strings in the source code that should be localizable, which is a tedious and very time-consuming task.

The good thing is that Resharper has good localization support which can save you many hours or even days of work – imagine having to go through all files and search for the strings manually! In this post I’ll show you how you can use Resharper to detect localizable strings and how you can enable or disable localization for a particular project, class, method or even an individual string.

Continue reading

Using Dictionaries to replace long if or switch statements

Imagine the following scenario – you have created some validators for your models: Foo, Bar and Xyz.

    public interface IValidator
    {
        bool Validate(object model);
    }

    // Validator for Foo class
    public class FooValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

    // Validator for Bar class
    public class BarValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

    // Validator for Xyz class
    public class XyzValidator : IValidator
    {
        public bool Validate(object model)
        {
            // ...
        }
    }

You decide to create a factory class for the validators to prevent users from creating instances directly using the new keyword. For example, this code would create a validator for Foo:

    var model = new Foo();
    var validatorFactory = new ValidatorFactory();
    IValidator validator = validatorFactory.CreateValidatorFor<Foo>();

    if (validator.Validate(model))
    {
        // ...
    }

Implementation of the factory:

    using System;

    public class ValidatorFactory
    {
        public IValidator CreateValidatorFor<T>()
        {
            Type modelType = typeof (T);
            IValidator validator = CreateValidatorFor(modelType);

            return validator;
        }

        public IValidator CreateValidatorFor(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            if(modelType == typeof(Foo))
            {
                return new FooValidator();
            }
            else if(modelType == typeof(Bar))
            {
                return new BarValidator();
            }
            else if(modelType == typeof(Xyz))
            {
                return new XyzValidator();
            }

            string errorMessage = string.Concat("Could not find validator for type ", modelType.FullName);
            throw new ArgumentException("modelType", errorMessage);
        }
    }

As you can see, for each model you have an if statement. This works fine if you only need to create 2 or 3 validators but if you need more your code will get bigger and bigger and will be harder to read/maintain. The same applies to switch statements.

The first step to solve this problem is to create a Dictionary to store the validators. The key of the Dictionary will be the type of the model and the value will be a delegate that creates an instance of the validator for that model:

	var validators = new Dictionary<Type, Func<IValidator>>
	{
		{ typeof(Foo), () => new FooValidator() },
		{ typeof(Bar), () => new BarValidator() },
		{ typeof(Xyz), () => new XyzValidator() }
	};

Changing the implementation of the factory to use the dictionary:

    public class ValidatorFactory : IValidatorFactory
    {
        private static Dictionary<Type, Func<IValidator>> _validators =
			new Dictionary<Type, Func<IValidator>> {
            { typeof(Foo), () => new FooValidator() },
            { typeof(Bar), () => new BarValidator() },
            { typeof(Xyz), () => new XyzValidator() }
        };

        public IValidator CreateValidatorFor<T>()
        {
            Type modelType = typeof (T);
            IValidator validator = CreateValidatorFor(modelType);

            return validator;
        }

        public IValidator CreateValidatorFor(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            Func<IValidator> validatorFunc;

            if (_validators.TryGetValue(modelType, out validatorFunc))
            {
                IValidator validator = validatorFunc();

                return validator;
            }

            string errorMessage = string.Concat("Could not find validator for type ", modelType.FullName);
            throw new ArgumentException("modelType", errorMessage);
        }
    }

That’s it, code looks much nicer now! To configure a new validator just add a new key/value pair to the _validators Dictionary.

Finally, testing the code using NUnit:

	// arrange
	var factory = new ValidatorFactory();

	// act
	IValidator validator = factory.CreateValidatorFor<Foo>();

	// assert
	Assert.That(validator, Is.TypeOf<FooValidator>());

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

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