Aracılığıyla paylaş


Nasıl yapılır: VSProject2 Nesnesini Kullanarak Visual Basic ve C# Projelerini İşleme

VSProject2 arabirimi, Visual C# ve Visual Basic projelerine özgü yöntemlere ve özelliklere erişim sağlar.VSProject2 ayrıca genel ortam modelinin DTE ve Project nesnelerine DTE ve Project özellikleri vasıtasıyla erişim sağlar.

Çoğu VSProject2 yöntem ve özellikleri, Visual C# ve Visual Basic projelerine eşit olarak uygulanır.Tek özel durum Visual Basic öğesine uygulanan ve Imports nesnesine erişim sağlayan Imports özelliğidir.Daha fazla bilgi için bkz. Nasıl yapılır: Visual Basic Projelerinin Imports Özelliğini İşleme.Events özelliği, projeye özgü olaylara (örneğin, VSLangProjWebReferencesEvents ve ReferencesEvents) erişim verir.Olay işleme görevleri diğer konularda ele alınmaktadır.Daha fazla bilgi için bkz. Olaylara Yanıt Verme (Visual Basic ve Visual C# Projeleri).

Aşağıdaki adımlar, genel otomasyon modelini kullanarak bir Visual C# pencereleri uygulamasının program aracılığıyla nasıl oluşturulacağını göstermektedir.Oluşturulan projeyi program aracılığıyla denetlemek için VSProject2 yöntemleri ve özellikleri kullanılır.

[!NOT]

Bilgisayarınız, aşağıdaki yönergelerde yer alan Visual Studio kullanıcı arabirimi öğelerinden bazıları için farklı adlar veya konumlar gösterebilir.Sahip olduğunuz Visual Studio sürümü ve kullandığınız ayarlar bu öğeleri belirler.Daha fazla bilgi için bkz. Visual Studio'da Geliştirme Ayarlarını özelleştirme.

C# projelerini denetleyecek VSProject2 nesnesini kullanmak için

  1. Visual C# kullanarak Visual Studio eklenti projesi oluşturun.

  2. Proje menüsünde, Başvuru Ekle'ye tıklayın, .NET sekmesine tıklayın, VSLangProj, VSLangProj2, ve VSLangProj80, VSLangProj90, ve VSLangProj100 öğelerini seçin ve sonra Tamama tıklayın.

  3. Bilgisayarınızda iki klasör oluşturun:

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

    • <Installation Root>\UserFiles\MyKeyFiles.

      Bu örnekte, <Installation Root> öğesi "C"dir.

  4. Connects.ts dosyasının en üstüne aşağıdaki kullanım açıklamalarını ekleyin.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    using VSLangProj90;
    
  5. VSLangProj100 kullanma;Aşağıdaki yöntem çağrısını OnConnection yöntemine ekleyin.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. CSVSProj2Manip yöntemi bildirimini doğrudan OnConnection yöntemi altına ekleyin.

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. Aşağıdaki bildirimleri yöntemin en üstüne ekleyin.

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. Bir proje oluşturmak için AddFromTemplate to create a Visual C# kullanın.

    • Şablonları almak için kullanılan sözdizimi şudur: EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp"); burada " WindowsApplication.zip " adı <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\1033 klasöründe bulunan WindowsApplication.zip dosyasından alınır.Tüm Visual Studio proje türleri için bu dosyalar <Installation Root>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\Language klasöründe bulunabilir."CSharp", bu projenin Visual C# projesi olduğunu belirtir.

    • Bir Visual BasicWindows Uygulaması projesi için söz dizimi EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic") olur.Visual Basic projelerinde, Windows Application zip dosyası şablonları <Installation Root>\ Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\1033 klasöründe bulunur.

    // 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. VSProject2 yöntemlerinin kullanımını göstermek için aşağıdaki kodu ekleyin.

    Projeye programsal olarak bir Web hizmeti eklemek için, koddaki <web service> yer tutucu metnini gerçek bir Web hizmetinin URL'siyle değiştirmelisiniz.Bir Web hizmeti URL'sini bulmak için, bir projeyi Visual Studio tümleşik geliştirme ortamında (IDE) açın.Proje menüsünde, Başvuru Ekle'yi tıklatın.Başvuru Ekle iletişim kutusunda UDDI Dizini bağlantısını tıklayın ve dizini kullanarak bir Web hizmeti bulun.

    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");
    

    CSVSProj2Manip yöntemi aşağıdakileri yapmak için VSProject2 nesnesini kullanır:

    Örnek bölümünde, tüm yöntem için try-catch bloğu dahil olmak üzere tüm kod gösterilmektedir.

  10. Eklentiyi derlemek için, Derle menüsünde Çözümü Derle'yi tıklayın.

  11. Visual Studio IDE öğesinde bir Visual C# projesi açın.

  12. Araçlar menüsünde Eklenti Yöneticisi'ni tıklayın ve Eklenti Yöneticisi iletişim kutusundan eklentinizi seçin.Eklentinizi çalıştırmak için Tamam'ı tıklayın.

  13. Sn.exe (Tanımlayıcı Ad Aracı) kullanarak <Installation Root>\UserFiles\MyKeyFiles klasöründe oluşturulan anahtar çifti dosyasını görüntüleyin.

Örnek

Aşağıdaki örnek, bir Visual C# projesi oluşturan ve VSProject2 nesnesinin özellikleri ve yöntemleri yoluyla onu kullanan temel bir Visual Studio eklentisidir.

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

Kod Derleniyor

Bu kodu derlemek için, yeni bir Visual Studio eklentisi projesi oluşturun ve OnConnection yönteminin kodunu örnekteki kodla değiştirin.Eklenti çalıştırmak hakkında daha fazla bilgi edinmek için bkz. Nasıl yapılır: Eklenti Yöneticisini Kullanarak Eklentileri Denetleme.

Ayrıca bkz.

Kavramlar

VSProject2 Nesnesine Giriş

Diğer Kaynaklar

Visual Basic ve Visual C# Projelerini Genişletme