Comment : manipuler des projets Visual Basic et C# à l'aide de l'objet VSProject2

L'interface VSProject2 fournit un accès aux méthodes et aux propriétés qui sont spécifiques aux projets Visual C# et Visual Basic. VSProject2 fournit également un accès aux objets DTE et Project du modèle d'environnement général via les propriétés DTE et Project.

La plupart des méthodes et des propriétés de VSProject2 s'appliquent uniformément aux projets Visual C# et Visual Basic. La seule exception est la propriété Imports, qui s'applique à Visual Basic et donne accès à l'objet Imports. Pour plus d'informations, consultez Comment : manipuler la propriété Imports des projets Visual Basic. La propriété Events donne accès à des événements spécifiques au projet, tels que VSLangProjWebReferencesEvents et ReferencesEvents. Les tâches de gestion des événements sont examinées dans d'autres rubriques. Pour plus d'informations, consultez Réponse aux événements (projets Visual Basic et Visual C#).

Les étapes ci-dessous montrent comment créer par programmation une application Windows Visual C# en utilisant le modèle Automation général. Les méthodes et propriétés de VSProject2 sont utilisées pour contrôler le projet créé par programmation.

Notes

Il est possible que pour certains des éléments de l'interface utilisateur de Visual Studio, votre ordinateur affiche des noms ou des emplacements différents de ceux indiqués dans les instructions suivantes.Ces éléments dépendent de l'édition de Visual Studio dont vous disposez et des paramètres que vous utilisez.Pour plus d'informations, consultez Paramètres Visual Studio.

Pour utiliser l'objet VSProject2 pour contrôler des projets C#

  1. Créez un projet de complément Visual Studio en utilisant Visual C#.

  2. Dans le menu Projet, cliquez sur Ajouter une référence, cliquez sur l'onglet .NET, puis sélectionnez VSLangProj, VSLangProj2, VSLangProj80, VSLangProj90 et VSLangProj100. Cliquez ensuite sur OK.

  3. Créez deux dossiers sur votre ordinateur :

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

    • <Installation Root>\UserFiles\MyKeyFiles.

      (Dans cet exemple, la <Installation Root> est « C »

  4. Ajoutez les instructions d'utilisation suivantes au début du fichier Connect.cs :

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    using VSLangProj90;
    
  5. À l'aide de VSLangProj100, ajoutez l'appel de méthode suivant à la méthode OnConnection.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. Ajoutez la déclaration de méthode CSVSProj2Manip directement sous de la méthode OnConnection.

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. Ajoutez les déclarations suivantes au début de la méthode :

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. Utilisez AddFromTemplate pour créer un projet Visual C#.

    • La syntaxe pour obtenir les modèles est EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp"), où le nom " WindowsApplication.zip " est obtenu à partir du fichier WindowsApplication.zip enregistré dans le dossier <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033. Pour tous les types de projet Visual Studio, ces fichiers sont accessibles dans le dossier <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\Language. "CSharp" spécifie que ce projet est un projet Visual C#.

    • Pour un projet d'application Windows Visual Basic, la syntaxe est EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic"). Pour les projets Visual Basic, les modèles de fichiers zip d'applications Windows sont enregistrés dans le dossier <Installation Root>\ Program Files\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. Ajoutez le code suivant pour montrer l'utilisation des méthodes VSProject2.

    Pour ajouter par programmation un service Web au projet, vous devez remplacer le texte d'espace réservé, <web service>, placé dans le code par l'URL d'un véritable service Web. Pour localiser une URL de service Web, ouvrez un projet dans l'environnement de développement intégré (IDE) de Visual Studio. Dans le menu Projet, cliquez sur Ajouter une référence. Dans la boîte de dialogue Ajouter une référence, cliquez sur le lien Répertoire UDDI, puis utilisez le répertoire pour rechercher un service 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");
    

    La méthode CSVSProj2Manip utilise l'objet VSProject2 pour effectuer les tâches suivantes :

    • ajouter une référence à System.Security.dll en utilisant References ;

    • créer un dossier de références Web à l'aide de CreateWebReferencesFolder ;

    • ajouter une référence Web en utilisant AddWebReference ;

    • afficher les monikers de génération au moment du design en utilisant des méthodes obtenues par le biais de la propriété BuildManager ;

    • renommer un nouvel élément de projet en utilisant la méthode GetUniqueFilename. La méthode CSVSProj2Manip ajoute l'élément de projet en utilisant AddFromTemplate ;

    • générer un fichier de paire de clés en utilisant la méthode GenerateKeyPairFiles.

    La section Exemple fournit l'intégralité du code, y compris un bloc try-catch pour la méthode entière.

  10. Pour générer le complément, cliquez sur Générer la solution dans le menu Générer.

  11. Ouvrez un projet Visual C# dans l'IDE de Visual Studio.

  12. Dans le menu Outils, cliquez sur Gestionnaire de compléments, puis sélectionnez votre complément dans la boîte de dialogue Gestionnaire de compléments. Cliquez sur OK pour exécuter votre complément.

  13. Consultez le fichier de paire de clés que vous avez généré dans le dossier <Installation Root>\UserFiles\MyKeyFiles en utilisant Sn.exe (outil Strong Name Tool).

Exemple

L'exemple suivant est un complément Visual Studio de base qui crée un projet Visual C# et le manipule en utilisant les propriétés et les méthodes de l'objet 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

Compilation du code

Pour compiler ce code, créez un projet de complément Visual Studio et remplacez le code de la méthode OnConnection par celui de l'exemple. Pour plus d'informations sur l'exécution d'un complément, consultez Comment : contrôler des compléments avec le Gestionnaire de compléments.

Voir aussi

Concepts

Introduction à l'objet VSProject2

Autres ressources

Extension des projets Visual Basic et Visual C#