Share via


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

La interfaz VSProject2 proporciona acceso a las propiedades y los métodos específicos de los proyectos de Visual C# y Visual Basic. VSProject2 también proporciona acceso a los objetos Project y DTE 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# y Visual Basic. 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.

NotaNota

Es posible que su equipo muestre nombres o ubicaciones diferentes para algunos de los elementos de la interfaz de usuario de Visual Studio en las siguientes instrucciones.La edición de Visual Studio que tenga y la configuración que esté usando determinan estos elementos.Para obtener más información, vea Personalizar la configuración de desarrollo en Visual Studio.

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

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

  2. En el menú Proyecto, haga clic en Agregar referencia, haga clic en la pestaña .NET, seleccione VSLangProj, VSLangProj2, VSLangProj80, VSLangProj90, y VSLangProj100 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, <Installation Root> es "C:".

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

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    using VSLangProj90;
    
  5. Mediante VSLangProj100, agregue la siguiente llamada 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. Para todos los tipos de proyecto 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 este proyecto 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.

    // 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. En el cuadro de diálogo Agregar referencia, haga clic en el vínculo Directorio UDDI y use 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 compilació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 compilar el complemento, haga clic en la opción Generar solución del menú Generar.

  11. Abra un proyecto de Visual C# 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. Use la herramienta Sn.exe (Herramienta de nombre seguro) para ver el archivo de pares de claves generado en la carpeta <Installation Root>\UserFiles\MyKeyFiles.

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;
using VSLangProj90;
using VSLangProj100;
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
Imports VSLangProj90
Imports VSLangProj100
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#