Building a simple MSBuild Task

On the “Using Studio’s “Custom Tool” in MSBuild” question, I was prompted to share the code. Here is a stripped down skeleton where I removed the actual calls to the custom tool. Since it is open source I didn’t really need to access the Visual Studio’s registry keys.


    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class ArebisGenTask
        : Task
    {
        [Required]
        public ITaskItem[] Templates { get; set; }

        [Output]
        public ITaskItem[] GeneratedFiles { get; set; }

        public override bool Execute()
        {
            var generatedFileNames = new List<string>();
            foreach (var task in this.Templates)
            {
                string inputFileName = task.ItemSpec;
                string outputFileName = Path.ChangeExtension(inputFileName, ".Designer.cs");
                string result;

                try
                {
                    // Build code string
                    result = Builder.CreateCode(inputFileName);

                    using (var destination = new FileStream(outputFileName, FileMode.Create))
                    {
                        var bytes = Encoding.UTF8.GetBytes(result);
                        destination.Write(bytes, 0, bytes.Length);
                    }
                    generatedFileNames.Add(outputFileName);
                }
                catch (Exception ex)
                {
                    Log.LogError("Error while compiling [{0}]", inputFileName);
                    Log.LogErrorFromException(ex, true, true, inputFileName);
                }
            }
            GeneratedFiles = generatedFileNames.Select(name => new TaskItem(name)).ToArray();
            Log.LogMessage("Finished Generation");
            return !Log.HasLoggedErrors;
        }
    }

Leave a Reply