Updating Project References Programmatically

A host, or helper application, can programmatically update a reference in a project.  One instance where this is useful is when you want to ensure that a specific version of a proxy reference is used.

Below is an updated version of the OpenMacroProject from the ShapeAppMacroRecordingCSharp sample which updates the reference in the project to use second version of the ShapeAppCSharpProxy.  The proj file is updated prior to loading to avoid any messages indicating that the project file has been updated and needs to be reloaded.

private void OpenMacroProject()
{
    // See if the project is already loaded.
    foreach (EnvDTE.Project currProject in this.dte.Solution.Projects)
    {
        string projPath = currProject.FileName;
        if (String.Compare(projPath,
                           VstaDesignTimeIntegration.MacroProjectFilePath,
                           StringComparison.OrdinalIgnoreCase) == 0)
        {

            this.macroProject = currProject;

            // Set the post build-event to install the Macro AddIn assembly into the
            // user's Documents folder i.e. "...\Documents\ShapeAppCSharp\MacroAddIns"
            this.macroProject.Properties.Item("PostBuildEvent").Value =
                "cscript \"$(ProjectDir)InstallAddIn.js\" \"$(TargetPath)\" \"ShapeAppCSharp\\MacroAddIns\"";

            RegisterAsDebugHost();
            return;
        }
    }

    //SUMMIT- update the reference
    {
        //namespace for the project file
        XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";

        //load the proj file
        XDocument projDoc = XDocument.Load(VstaDesignTimeIntegration.MacroProjectFilePath);

        //get the node with the reference to update
        var oldRef = (from refs in projDoc.DescendantNodes()
                 where refs.ToString().StartsWith("<Reference") &&
                 refs.ToString().Contains("ShapeAppCSharpProxy")
                 select refs).First();

        //create the new version specific reference
        XElement updRef = new XElement(ns + "Reference",
            new XAttribute("Include", "ShapeAppCSharpProxy, Version=2.0.0.0"),
            new XElement(ns + "SpecificVersion", "true"));

        //update the node
        oldRef code.ReplaceWith(updRef);

        //save the document
        projDoc.Save(VstaDesignTimeIntegration.MacroProjectFilePath);
    }

    // Load the project as it is not currently loaded
    this.macroProject = this.dte.Solution.AddFromFile(
        VstaDesignTimeIntegration.MacroProjectFilePath, true);
    RegisterAsDebugHost();
}

To use this code to correct the side by side evaluation issue (both versions of the ShapeAppCSharp samples use the ShapeAppCSharpProxy) be sure to version the proxy assembly and add the above code.


Posted Aug 13 2008, 03:10 PM by Melody
Filed under: , ,
Copyright Summit Software Company, 2008. All rights reserved.