Add source files and assembly references during prebuild

I want to have a "manifest.json" file in my project that contains a list of .cs and .dll files that the project depends on but is not part of the project. In order to compile these files in an assembly too, I need to somehow tell Visual Studio to include these source files and assemblies in the build process.

Is there a way to do this in a pre-build event?

+3


source to share


2 answers


I have now created a custom ITaskItem that adds files before the build process.

This is how I did it:

1) Create your own ITaskItem file

public class AddSourceFiles : Task
{
    private ITaskItem[] output = null;

    [Output]
    public ITaskItem[] Output
    {
        get
        {
            return output;
        }
    }

    public override bool Execute()
    {
        //gather a list of files to add:
        List<string> filepaths = new List<string>() { "a.cs", "b.cs", "d.cs" };

        //convert the list to a itaskitem array and set it as output
        output = new ITaskItem[filepaths.Count];
        int pos = 0;
        foreach (string filepath in filepaths)
        {
            output[pos++] = new TaskItem(filepath);
        }
    }
}

      

2) Create a * .targets file, for example "AddSourceFiles.targets":



<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <UsingTask AssemblyFile="AddSourceFiles.dll" TaskName="AddSourceFiles" />
    <PropertyGroup>
        <BuildDependsOn>
            AddSourceFiles;
            $(BuildDependsOn);
        </BuildDependsOn>
    </PropertyGroup>
    <Target Name="AddSourceFiles">
        <AddSourceFiles>
            <Output TaskParameter="Output" ItemName="Compile" />
        </AddSourceFiles>
    </Target>   
</Project>

      

As you can see, the resulting DLL of the "AddSourceFiles" class is referenced in the task file.

3) The final step is to import this .targets file into every .csproj file you want to include in the file using the AddSourceFiles class.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  .
  .
  <Import Project="c:\path\to\AddSourceFiles.targets" />
  .
  .
</Project>

      

I'm very new to this too, so feel free to improve this one;)

+2


source


you have to use VisualStudio macros:

http://msdn.microsoft.com/en-us/library/b4c73967(v=vs.100).aspx

http://msdn.microsoft.com/en-us/library/8h31zbch.aspx

The Macros IDE provides an example similar to what you are trying to achieve:



AddDirAsSlnFolder - Imports a folder on disk into the solution folder structure.

------ update -----

I just found out that Vs2012 has Macro functionality.

+1


source







All Articles