Compartir a través de


Cómo: Manipular proyectos de Visual Basic y C# con el objeto VSProject2

Actualización: noviembre 2007

La interfaz VSProject2 proporciona acceso a métodos y propiedades específicos de los proyectos de Visual C#, Visual Basic y Visual J#. VSProject2 también proporciona acceso a los objetos DTE y Project del modelo de entorno general a través de las propiedades DTE y Project.

La mayoría de los métodos y propiedades de VSProject2 se aplican de manera uniforme a los proyectos de Visual C#, Visual Basic y Visual J#. La única excepción es la propiedad Imports, que se aplica a Visual Basic y proporciona acceso al objeto Imports. Para obtener más información, vea Cómo: Manipular la propiedad Imports de los proyectos de Visual Basic. La propiedad Events otorga acceso a los eventos específicos de proyecto, como VSLangProjWebReferencesEvents y ReferencesEvents. Las tareas de control de eventos se explican en otros temas. Para obtener más información, vea Responder a eventos (Proyectos de Visual Basic y Visual C#).

Los siguientes pasos muestran cómo crear mediante programación una aplicación para Windows de Visual C# utilizando el modelo de automatización general. Los métodos y propiedades de VSProject2 se utilizan para controlar mediante programación el proyecto creado.

Nota:

Los cuadros de diálogo y comandos de menú que se ven pueden diferir de los descritos en la Ayuda, en función de los valores de configuración o de edición activos. Estos procedimientos se desarrollaron con la Configuración general de desarrollo activa. Para cambiar la configuración, elija la opción Importar y exportar configuraciones del menú Herramientas. Para obtener más información, vea Valores de configuración de Visual Studio.

Para utilizar el objeto VSProject2 con el fin de controlar proyectos de C# y J#

  1. Cree un proyecto de complemento de Visual Studio mediante Visual C#.

  2. En el menú Proyecto, haga clic en Agregar referencia y luego en la ficha .NET, seleccione VSLangProj, VSLangProj2 y VSLangProj80 y, a continuación, haga clic en Aceptar.

  3. Cree dos carpetas en el equipo:

    • <Installation Root>\UserFiles\MyProjects\MyTestProject.

    • <Installation Root>\UserFiles\MyKeyFiles.

      En este ejemplo, el <Installation Root> es "C":.

  4. Agregue las siguientes instrucciones using al principio del archivo Connect.cs.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    
  5. Agregue la llamada siguiente al método OnConnection.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. Agregue la declaración del método CSVSProj2Manip directamente después del método OnConnection.

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. Agregue las siguientes declaraciones al principio del método.

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. Utilice AddFromTemplate para crear un proyecto de Visual C#.

    • La sintaxis para obtener las plantillas es EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp"), donde el nombre " WindowsApplication.zip " se obtiene del archivo WindowsApplication.zip, que se encuentra en la carpeta <Installation Root>\Archivos de programa\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033. En todos los tipos de proyectos de Visual Studio, estos archivos se encuentran en la carpeta <Installation Root>\Archivos de programa\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\Language. "CSharp" especifica que éste es un proyecto de Visual C#.

    • En un proyecto de aplicación para Windows de Visual Basic, la sintaxis es EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic"). En los proyectos de Visual Basic, las plantillas del archivo zip de la aplicación para Windows se encuentran en la carpeta <Installation Root>\ Archivos de programa\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\1033.

    • En un proyecto de aplicación para Windows de Visual J#, la sintaxis es EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "JSharp"). En los proyectos de Visual J#, las plantillas del archivo zip de la aplicación para Windows se encuentran en la carpeta <Installation Root>\ Archivos de programa\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\JSharp\Windows\1033.

    // Make sure you create the folders that 
    // make up the file path
    // on your computer. You can replace 
    // this with your own file path.
    csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
    // Get the project template path for a C# windows 
    // application.
    csTemplatePath = soln.GetProjectTemplate("WindowsApplication.zip", "CSharp");
    // Create a new windows application by using the 
    // template obtained above.
    soln.AddFromTemplate(csTemplatePath, csPrjPath,
     "Test2CSProj", false);
    
  9. Agregue el siguiente código para mostrar el uso de los métodos VSProject2.

    Para agregar mediante programación un servicio Web al proyecto, debe reemplazar el texto del marcador de posición, <web service>, del código por la dirección URL de un servicio Web real. Para buscar la dirección URL de un servicio web, abra un proyecto en el entorno de desarrollo integrado (IDE) de Visual Studio. En el menú Proyecto, haga clic en Agregar referencia Web. En el cuadro de diálogo Agregar referencia, haga clic en el vínculo Directorio UDDI y utilice el directorio para buscar un servicio Web.

    proj = soln.Projects.Item(1);
    // Cast the project as a VSProject2 object.
    vsproj = (VSProject2)proj.Object;
    // Add a reference to System.Security.dll.
    MessageBox.Show("Adding a reference 
    to System.Security.dll");
    // Remove the <version number> in the following path
    // and replace it with one of the version 
    // number folders that appear 
    // in <installation root>\WINDOWS\Microsoft.NET\Framework
    // folder
    vsproj.References.Add
    ("C:\\WINDOWS\\Microsoft.NET\\Framework\\<version number>\\System.Security.dll");
    // Create a Web references folder.
    MessageBox.Show("Creating a Web references folder.");
    vsproj.CreateWebReferencesFolder();
    // Add a Web reference to the folder.
    MessageBox.Show("Adding a Web reference.");
    // Replace the placeholder, <web service>, with a
    // Web service URL.
    webServiceRef = "<web service>";
    vsproj.AddWebReference(webServiceRef);
    bldMgr = vsproj.BuildManager;
    Array monikers = null;
    // String moniker = null;
    String msg = null;
    Object obj = bldMgr.DesignTimeOutputMonikers;
    if (obj != null)
    {
        try
        {
            monikers = (System.Array)obj;
            foreach(String tempmoniker in monikers)
            {
                msg += bldMgr.BuildDesignTimeOutput
    (tempmoniker) + "\n";
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        MessageBox.Show("The build design-time output is:" 
    + "\n"  + msg);
    }
    // Change the MyHTML file name by using GetUniqueFilename.
    MessageBox.Show("Adding an HTML page named 'MyHTML'...");
    String itemTemplatePath = soln.GetProjectItemTemplate("HTMLPage",
     "CSharp");
    proj.ProjectItems.AddFromTemplate
    (itemTemplatePath, "MyHtml");
    MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
    vsproj.Project.ProjectItems.Item("MyHtml").Name =
     vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
    // Generate a key-pair file.
    MessageBox.Show("Generating a key-file...");
    vsproj.GenerateKeyPairFiles("C:\\UserFiles\\MyKeyFiles
    \\MyKeyText2.bin", "0");
    

    El método CSVSProj2Manip utiliza el objeto VSProject2 para:

    • Agregar una referencia a System.Security.dll utilizando References.

    • Crear una carpeta de referencias Web utilizando CreateWebReferencesFolder.

    • Agregar una referencia Web utilizando AddWebReference.

    • Mostrar los monikers en tiempo de diseño de generación, utilizando métodos obtenidos a través de la propiedad BuildManager.

    • Cambiar el nombre de un elemento de proyecto nuevo, utilizando el método GetUniqueFilename. El método CSVSProj2Manip agrega el elemento de proyecto utilizando AddFromTemplate.

    • Generar un archivo de pares de claves utilizando el método GenerateKeyPairFiles.

    La sección de ejemplo muestra el código completo, incluido un bloque try-catch para todo el método.

  10. Para generar el complemento, haga clic en la opción Generar solución del menú Generar.

  11. Abra un proyecto de Visual C#, Visual J# o Visual Basic en el IDE de Visual Studio.

  12. En el menú Herramientas, haga clic en Administrador de complementos y seleccione el complemento del cuadro de diálogo Administrador de complementos. Haga clic en Aceptar para ejecutar el complemento.

  13. Vea el archivo de pares de claves generado en la carpeta <Installation Root>\ArchivosdeUsuario\MisArchivosClave, mediante Herramienta de nombre seguro (Sn.exe).

Ejemplo

En el siguiente ejemplo de un complemento básico de Visual Studio se crea un proyecto de Visual C# y se manipula con las propiedades y métodos del objeto VSProject2.

using System;
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using VSLangProj;
using VSLangProj2;
using VSLangProj80;
public void OnConnection(object application, 
ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    CSVSProj2Manip(_applicationObject);
}
public void CSVSProj2Manip(DTE2 dte)
{
    try
    {
        Solution2 soln = (Solution2)_applicationObject.Solution;
        String csTemplatePath;
        String csPrjPath;
        Project proj;
        VSProject2 vsproj;
        String webServiceRef;
        BuildManager bldMgr;
        // Make sure you create the folders that make up the file path
        // on your computer.
        // You can replace this with your own file path.
        csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
        // Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate
("WindowsApplication.zip", "CSharp");
        // Create a new Windows application by using the template 
        // obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath,
 "Test2CSProj", false);
        proj = soln.Projects.Item(1);
        // Get a reference to the VSProject2 object.
        vsproj = (VSProject2)proj.Object;
        // Add a reference to System.Security.dll.
        MessageBox.Show("Adding a reference to System.Security.dll");
        // Remove the <version number> in the following path
        // and replace it with one of the version 
        // number folders that appear 
        // in <installation root>\WINDOWS\Microsoft.NET\Framework
        // folder
        vsproj.References.Add
("C:\\WINDOWS\\Microsoft.NET\\Framework\\<version number>\\System.Security.dll");
        // Create a Web references folder.
        MessageBox.Show("Creating a Web references folder.");
        vsproj.CreateWebReferencesFolder();
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        MessageBox.Show("Adding a Web reference.");
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        webServiceRef = "<web service>";
        vsproj.AddWebReference(webServiceRef);
        bldMgr = vsproj.BuildManager;
        Array monikers = null;
        // String moniker = null;
        String msg = null;
        Object obj = bldMgr.DesignTimeOutputMonikers;
        if (obj != null)
        {
            try
            {
                monikers = (System.Array)obj;
                foreach(String tempmoniker in monikers)
                {
                    msg += bldMgr.BuildDesignTimeOutput(tempmoniker) 
+ "\n";
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            MessageBox.Show("The build design-time output is:" + "\n"  
+ msg);
        }
        // Change the MyHTML file name by using GetUniqueFilename.
        MessageBox.Show("Adding an HTML page named 'MyHTML'...");
        String itemTemplatePath =
 soln.GetProjectItemTemplate("HTMLPage", "CSharp");
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml");
        MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
        vsproj.Project.ProjectItems.Item("MyHtml").Name =
 vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
        // Generate a key-pair file.
        MessageBox.Show("Generating a key-file...");
        vsproj.GenerateKeyPairFiles
("C:\\UserFiles\\MyKeyFiles\\MyKeyText2.bin", "0");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports EnvDTE80
Imports VSLangProj
Imports VSLangProj2
Imports VSLangProj80
Public Sub OnConnection(ByVal application As Object, _
 ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, _
 ByRef custom As Array) Implements IDTExtensibility2.OnConnection
    _applicationObject = CType(application, DTE2)
    _addInInstance = CType(addInInst, AddIn)
    CSVSProj2Manip(_applicationObject)
End Sub
Sub CSVSProj2Manip(ByVal dte As DTE2)
    Try
        Dim soln As Solution2 = CType(_applicationObject.Solution, _
         Solution2)
        Dim csTemplatePath As String
        Dim csPrjPath As String
        Dim proj As Project
        Dim vsproj As VSProject2
        Dim webServiceRef As String
        Dim bldMgr As BuildManager
        ' Create this or your own file path on your computer.
        ' The file path must exist before you run this add-in.
        csPrjPath = "C:\UserFiles\MyProjects\MyTestProject"
        ' Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate _
        ("WindowsApplication.zip","CSharp")
        ' Create a new Windows Application
        ' using the template obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath _
        , "Test2CSProj", False)
        proj = soln.Projects.Item(1)
        ' Cast the project to a VSProject2.
        vsproj = CType(proj.Object, VSProject2)
        ' Add a reference to System.Security.dll.
        MsgBox("Adding a reference to System.Security.dll")
        ' Remove the <version number> in the following path
        ' and replace it with one of the version 
        ' number folders that appear 
        ' in <installation root>\WINDOWS\Microsoft.NET\Framework
        ' folder
        vsproj.References.Add _
        ("C:\WINDOWS\Microsoft.NET\Framework\<version number>\System.Security.dll")
        ' Create a Web references folder.
        MsgBox("Creating a Web references folder.")
        vsproj.CreateWebReferencesFolder()
        ' Replace the placeholder, <web service>, with a
        ' web service URL.
        webServiceRef = "<web service>"
        MsgBox("Adding a Web reference.")
        vsproj.AddWebReference(webServiceRef)
        bldMgr = vsproj.BuildManager
        Dim monikers As String() = Nothing
        Dim moniker As String = Nothing
        Dim msg As String = ""
        Dim obj As Object = bldMgr.DesignTimeOutputMonikers
        If Not obj Is Nothing Then
            Try
                monikers = CType(obj, String())
                For Each moniker In monikers
                    msg &= bldMgr.BuildDesignTimeOutput(moniker) + vbCr
                Next
            Catch ex As System.Exception
                MsgBox(ex.ToString)
            End Try
            MsgBox("The build design-time output is:" + vbCr + msg)
        End If
        ' Use the UniqueFilename to rename a new project item.
        MsgBox("Adding an HTML page called 'MyHTML'...")
        Dim itemTemplatePath As String = _
        soln.GetProjectItemTemplate("HTMLPage", "CSharp")
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml")
        MsgBox("Renaming MyHtml' to 'MyTesthtml.htm'...")
        vsproj.Project.ProjectItems.Item("MyHtml").Name = _
        vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm")
        ' Generate a key-pair file.
        vsproj.GenerateKeyPairFiles _
        ("C:\UserFiles\MyKeyFiles\MyKeyText2.bin", "0")
    Catch ex As System.Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Compilar el código

Para compilar este código, cree un nuevo proyecto de complemento de Visual Studio y reemplace el código del método OnConnection por el código del ejemplo. Para obtener información sobre cómo ejecutar un complemento, vea Cómo: Controlar complementos con el Administrador de complementos.

Vea también

Conceptos

Introducción al objeto VSProject2

Otros recursos

Extensión de proyectos de Visual Basic y Visual C#