Question

I want to have a "manifest.json" file in my project, that contains a list of .cs and .dll files the project depends on, but are not part of the project. To compile those files also on build, I need to somehow tell Visual Studio to include those source files and assemblies into the build process.

Is there a way I could do this in the pre-build event?

Was it helpful?

Solution

I've made a custom ITaskItem now that adds the files before the build process.

Here's how I've done it:

1) Create custom ITaskItem

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 class "AddSourceFiles" is referenced in the task file.

3) The last step is to import this .targets file into every .csproj file that you want to include files using your 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 also very new to this, so feel free to improve this one ;)

OTHER TIPS

you should 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 contains an example that is similar to what you are trying to achieve:

AddDirAsSlnFolder — Imports a folder on disk into a solution folder structure.

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

i've just find out that Vs2012 has Macro functionality removed....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top