Compartilhar via


Como: Manipular translation from VPE for Csharp projetos com o objeto VSProject2 e Visual Basic

The VSProject2 interface fornece acesso a métodos e propriedades que são específicas para Visual C#, Visual Basic, e Visual J# projetos. VSProject2 também fornece acesso para o DTE e Project objetos do modelo do ambiente geral por meio do DTE e Project Propriedades.

A maioria dos métodos e propriedades de VSProject2 se apliquem uniformemente ao Visual C#, Visual Basic, e Visual J# projetos. A única exceção é o Imports propriedade, que se aplica a Visual Basic e fornece acesso para o Imports objeto. Para obter mais informações, consulte Como: Manipular a propriedade de importações de projetos do Visual Basic.The Events propriedade oferece acesso a eventos específicos de projeto, tais sistema autônomo VSLangProjWebReferencesEvents e ReferencesEvents. As tarefas de tratamento de evento são abordadas em outros tópicos.Para obter mais informações, consulte Respondendo a eventos (Visual Basic e Visual translation from VPE for Csharp projetos).

As etapas a seguir ilustram como criar programaticamente um Visual C# aplicativos do Windows usando o modelo de automação Geral. Os métodos e propriedades de VSProject2 são usados para controlar programaticamente o projeto criado.

Observação:

As caixas de diálogo e comandos de menu que você vê podem diferir das descritas Hel p dependendo das configurações ativas ou edição.Esses procedimentos foram desenvolvidos com o Geral Development Settings ativo.Para alterar as configurações, escolher Importar e exportar configurações on the Ferramentas menu.Para obter mais informações, consulte Configurações do Visual Studio.

Para usar o objeto VSProject2 para projetos de controle de translation from VPE for Csharp e J#

  1. Criar um Visual Studio Projeto suplemento usando Visual C#.

  2. Sobre o Projeto menu, clicar Adicionar referência, clicar no NET guia, selecionar VSLangProj, VSLangProj2 e VSLangProj80 e, em seguida, clicar OK.

  3. Crie duas pastas em seu computador:

    • <Instalação Raiz > \UserFiles\MyProjects\MyTestProject.

    • <Instalação Raiz > \UserFiles\MyKeyFiles.

      Neste exemplo, o <Raiz de instalação> is "C:".

  4. Adicione as seguintes instruções using ao início do arquivo conectar.cs.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    
  5. Adicione a seguinte telefonar de método para o 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. Adicione a declaração de método CSVSProj2Manip diretamente abaixo o método OnConnection.

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. Adicione as seguintes declarações na parte superior do método.

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. Use AddFromTemplate Para criar um Visual C# projeto.

    • A sintaxe para obter os modelos é EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp"), onde o nome " WindowsApplication.zip " é obtido do arquivo WindowsApplication.zip localizado em <Instalação Raiz > \ programa Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033 pasta.Para todos os Visual Studio tipos de projeto, esses arquivos podem ser encontrados na <Instalação Raiz >\programa Files\Microsoft visual Studio 8\Common7\IDE\ProjectTemplates\linguagem pasta."CSharp" Especifica que este projeto é um Visual C# projeto.

    • Para um Visual Basic Projeto Windows aplicativo, a sintaxe é EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic"). For Visual Basic os modelos de arquivo zip de aplicativos do Windows encontram-se em projetos de <Instalação Raiz > \ Programa Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\1033 pasta.

    • Para um Visual J# Projeto Windows aplicativo, a sintaxe é EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "JSharp"). For Visual J# os modelos de arquivo zip de aplicativos do Windows encontram-se em projetos de <Instalação Raiz >Pasta \Arquivos de programas\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. Adicione o seguinte código para demonstrar o uso do VSProject2 métodos.

    Para adicionar um serviço Web por programação ao projeto, você deve substituir o texto do espaço reservado, <web service>, no código com o URL de um serviço Web real. Para localizar um URL de serviço Web, abra um projeto no Visual Studio ambiente de desenvolvimento integrado (IDE). Sobre o Projeto menu, clicar Adicionar referência da Web.Sobre o Adicionar referência diálogo, clicar no Diretório UDDI link e use o diretório para encontrar um serviço 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");
    

    O método CSVSProj2Manip usa o VSProject2 objeto para:

    A seção exemplo lista o código completo, incluindo um bloco try-catch para todo o método.

  10. Para criar o suplemento, clicar Criar solução on the Compilação menu.

  11. Abra um Visual C#, Visual J#, ou Visual Basic projeto na Visual Studio IDE.

  12. Sobre o Ferramentas menu, clicar Gerenciador de suplementoe selecionar seu suplemento a partir de Gerenciador de suplemento caixa de diálogo.clicar OK para executar seu suplemento.

  13. Exibir o arquivo emparelhar de chaves gerado no <Instalação Raiz >\UserFiles\MyKeyFiles pasta usando o Ferramenta Strong Name (Sn.exe).

Exemplo

O exemplo a seguir é um básico Visual Studio suplemento cria um Visual C# projeto e o manipula utilizando propriedades e métodos para o VSProject2 objeto.

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

Compilando o código

Para compilar este código criar um novo Visual Studio Projeto suplemento e substitua o código do método OnConnection com o código de exemplo. Para obter informações sobre como executar um suplemento, consulte Como: Controlarar Adicionar-ins com o Adicionar - in Gerente.

Consulte também

Conceitos

Introdução ao objeto VSProject2

Outros recursos

Estender Visual Basic e Visual translation from VPE for Csharp Projects