Aracılığıyla paylaş


Tanılama Veri Bağdaştırıcısı Oluşturmak için Örnek Proje

"MyDiagnosticDataAdapter" testlerinizi yürüttüğünüzde test sonuçlarına bir günlük dosyası ekleyebilen temel bir tanılama verisi bağdaştırıcısıdır.

Tanı veri toplayıcısının veya yapılandırma düzenleyicisinin yüklü olduğu herhangi bir makinedeki yönetimsel izinlere ihtiyacınız olacak.

Örnek

Bu örnek, aşağıdaki görevlerin nasıl gerçekleştirileceğini gösterir:

  • Bir sınıfı Microsoft Test Yöneticisi tanılama veri bağdaştırıcısı olarak oluşturulabilir olması için öznitelik uygulayın.

  • Bir tanılama veri bağdaştırıcısının yapılandırmasını değiştirmekte kullanmak üzere kullanıcı denetleme sınıfını bir düzenleyici olarak Microsoft Test Yöneticisi tarafından bulunabilir hale getirmek için öznitelikleri uygulayın.

  • Varsayılan yapılandırma verilerine erişin.

  • Belirli Diagnostic Data Collection (Tanılama Veri Kolleksiyonu) olayları için kaydolun.

  • Günlük dosyasını DataCollectionSink'e göndererek ekler.

// My Data Collector Class
using Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.Execution;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System;

namespace MyCompany.MyDiagnosticDataAdapters
{
    // Provide a URI and friendly name for your diagnostic data adapter
    [DataCollectorTypeUri("datacollector://MyCompany/MyDataCollector/1.0")]
    [DataCollectorFriendlyName("Collect Log Files sample", false)]
    // Designate your chosen configuration editor
    [DataCollectorConfigurationEditor(
        "configurationeditor://MyCompany/MyDataConfigEditor/1.0")]
    public class MyDataCollector : DataCollector
    {
        private DataCollectionEvents dataEvents;
        private DataCollectionLogger dataLogger;
        private DataCollectionSink dataSink;
        private XmlElement configurationSettings;

        // Required method called by the testing framework
        public override void Initialize(
            XmlElement configurationElement, 
            DataCollectionEvents events, 
            DataCollectionSink sink, 
            DataCollectionLogger logger, 
            DataCollectionEnvironmentContext environmentContext)
        {
            dataEvents = events; // The test events
            dataLogger = logger; // The error and warning log
            dataSink = sink;     // Saves collected data
            // Configuration from the test settings
            configurationSettings = configurationElement;

            // Register common events for the data collector
            // Not all of the events are used in this class
            dataEvents.SessionStart +=
                new EventHandler<SessionStartEventArgs>(OnSessionStart);
            dataEvents.SessionEnd +=
                new EventHandler<SessionEndEventArgs>(OnSessionEnd);
            dataEvents.TestCaseStart +=
                new EventHandler<TestCaseStartEventArgs>(OnTestCaseStart);
            dataEvents.TestCaseEnd +=
                new EventHandler<TestCaseEndEventArgs>(OnTestCaseEnd);
            dataEvents.DataRequest +=
                new EventHandler<DataRequestEventArgs>(OnDataRequest);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                dataEvents.SessionStart -=
                    new EventHandler<SessionStartEventArgs>(OnSessionStart);
                dataEvents.SessionEnd -=
                    new EventHandler<SessionEndEventArgs>(OnSessionEnd);
                dataEvents.TestCaseStart -=
                    new EventHandler<TestCaseStartEventArgs>(OnTestCaseStart);
                dataEvents.TestCaseEnd -=
                    new EventHandler<TestCaseEndEventArgs>(OnTestCaseEnd);
                dataEvents.DataRequest -=
                    new EventHandler<DataRequestEventArgs>(OnDataRequest);
            }
        }

        #region Event Handlers
        public void OnSessionStart(object sender, SessionStartEventArgs e)
        {
            // TODO: Provide implementation
        }

        public void OnSessionEnd(object sender, SessionEndEventArgs e)
        {
            // TODO: Provide implementation
        }

        public void OnTestCaseStart(object sender, TestCaseEventArgs e)
        {
            // TODO: Provide implementation
        }

        public void OnTestCaseEnd(object sender, TestCaseEndEventArgs e)
        {
            // Get any files to be collected that are
            // configured in your test settings
            List<string> files = getFilesToCollect();

            // For each of the files, send the file to the data sink
            // which will attach it to the test results or to a bug
            foreach (string file in files)
            {
                dataSink.SendFileAsync(e.Context, file, false);
            }
        }

        public void OnDataRequest(object sender, DataRequestEventArgs e)
        {
            // TODO: Provide implementation
            // Most likely this occurs because a bug is being filed
        }
        #endregion

        // A private method to collect the configured file names
        private List<string> getFilesToCollect()
        {
            // Seetup namespace manager with our namespace
            XmlNamespaceManager nsmgr =
                new XmlNamespaceManager(
                    configurationSettings.OwnerDocument.NameTable);
            nsmgr.AddNamespace("ns", 
                "http://MyCompany/schemas/MyDataCollector/1.0");

            // Find all of the "File" elements under our configuration
            XmlNodeList files =
                configurationSettings.SelectNodes(
                    "//ns:MyDataCollector/ns:File");
            
            // Build the list of files to collect from the 
            // "FullPath" attributes of the "File" nodes.
            List<string> result = new List<string>();
            foreach (XmlNode fileNode in files)
            {
                XmlAttribute pathAttribute = 
                    fileNode.Attributes["FullPath"];
                if (pathAttribute != null &&
                    !String.IsNullOrEmpty(pathAttribute.Value))
                {
                    result.Add(pathAttribute.Value);
                }
            }

            return result;
        }
    }
}

Bu, tanılama veri bağdaştırıcınız için örnek bir yapılandırma düzenleyicisidir. Projenize Kullanıcı Denetimi ekleyin ve etiketi ("Günlük Dosyasının Adı:") olan çok basit bir formla birlikte "FileTextBox" adlı bir metin kutusu oluşturun.

using Microsoft.VisualStudio.TestTools.Common;
using Microsoft.VisualStudio.TestTools.Execution;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System;

namespace MyCompany.DiagnosticDataAdapters.ConfigurationEditors
{
    [DataCollectorConfigurationEditorTypeUri(
        "configurationeditor://MyCompany/MyConfigEditor/1.0")]
    public partial class MyDataConfigEditor :
        UserControl, IDataCollectorConfigurationEditor
    {
        private DataCollectorSettings collectorSettings;

        // Create a private property for the service provider
        private IServiceProvider ServiceProvider { get; set; }

        // Constructor
        public MyConfigurationEditor()
        {
            InitializeComponent();
        }

        // Required method called by the testing framework
        public void Initialize(
            IServiceProvider svcProvider,
            DataCollectorSettings settings)
        {
            ServiceProvider = svcProvider;
            collectorSettings = settings;

            // Display the file name as listed in the settings file.
            // If the configuration has not been updated before, this
            // data will be provided by the default configuration
            // section from <nameofcollector>.dll.config:
            // <DefaultConfiguration>
            //   <MyCollectorName 
            //       xmlns="http://MyCompany/schemas/ProductName/Version");
            //     <File FullPath="C:\temp\logfile1.txt" />
            //   </MyCollectorName>
            // </DefaultConfiguration>
            this.SuspendLayout();
            this.FileTextBox.Text = GetText(collectorSettings.Configuration);
            this.ResumeLayout();
        }

        // Can be used to verify data before saving it
        public bool VerifyData()
        {
            // Not currently verifying data
            return true;
        }

        // Reset to default value from XML configuration
        // using a custom method
        public void ResetToAgentDefaults()
        {
            this.FileTextBox.Text = 
                getText(collectorSettings.DefaultConfiguration);
        }

        // Saves data changed in the editor to the test configuration
        // settings. Does not change the default value.
        public DataCollectorSettings SaveData()
        {
            collectorSettings.Configuration.InnerXml =
                String.Format(
                    @"<MyCollectorName
      http://MyCompany/schemas/MyDataCollector/1.0"">
  <File FullPath=""{0}"" />
</MyCollectorName>",
                    FileTextBox.Text);
            return collectorSettings;
        }

        // Reads the configuration settings
        private string getText(XmlElement element)
        {
            // Setup namespace manager with our namespace
            XmlNamespaceManager nsmgr =
                new XmlNamespaceManager(
                    element.OwnerDocument.NameTable);

            // Find all the "File" elements under our configuration
            XmlNodeList files = element.SelectNodes("//ns:MyDataCollector/ns:File", nsmgr);
            
            string result = String.Empty;
            if (files.Count > 0)
            {
                XmlAttribute pathAttribute = files[0].Attributes["FullPath"];
                if (pathAttribute != null &&
                    !String.IsNullOrEmpty(pathAttribute.Value))
                {
                    result = pathAttribute.Value;
                }
            }

            return result;
        }
    }
}

Aşağıdaki tanılama veri toplayıcısı yapılandırma düzenleyiciniz için örnek bir yapılandırma dosyası.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section 
      name="DataCollectorConfiguration"
      type="Microsoft.VisualStudio.QualityTools.Execution.DataCollectorConfigurationSection,
        Microsoft.visualStudio.QualityTools.ExecutionCommon,
        Version=4.0.0.0, Culture=neutral,
        PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <DataCollectorConfiguration
      xmlns="https://microsoft.com/schemas/VisualStudio/TeamTest/2010">
    <DataCollector 
        typeUri="datacollector://MyCompany/MyDataCollector/1.0">
      <DefaultConfiguraton>
        <!-- Your default config settings-->
        <File FullPath="c:\temp\logfile1.txt" />
      </DefaultConfiguration>
    </DataCollector>
  </DataCollectorConfiguration>
</configuration>

Kod Derleme

Bu tanılama bağdaştırıcısı için proje kodu oluşturmak üzere

  1. "MyDataCollector" adlı yeni bir sınıf kitaplık projesi oluşturun.

  2. Çözüm Gezgini'nde projeye sağ tıklayın ve sonra Özellikler'i tıklayın. Eklemek için bir klasör seçmek üzere Reference Paths (Başvuru Yolu)'nu ve ardından üç noktayı ( ) tıklatın.

    Select Reference Path (Başvuru Yolu Seç) iletişim kutusu görüntülenir.

  3. Yükleme dizinine göre aşağıdaki yolu seçin: Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies. Tamam düğmesini tıklatın.

  4. Başvuru yolunuza dosya eklemek için, Dosya Ekle'yi tıklatın.

    Dosya, başvuru yolu listesinde görüntülenir.

  5. Başvuru yollarını kaydetmek için Tümünü Kaydet simgesini tıklatın.

  6. Microsoft.VisualStudio.QualityTools.ExecutionCommon derleyiciyi ekleyin.

    1. Çözüm Gezgini'nde, Başvurular'ı sağ tıklatın ve sonra Başvuru Ekle'yi tıklatın.

    2. Gözat'ı tıklatın ve Microsoft.VisualStudio.QualityTools.ExecutionCommon.dll'i bulun.

      Derleyici Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies içinde bulunur.

    3. Tamam düğmesini tıklatın.

  7. Microsoft.VisualStudio.QualityTools.Common derleyiciyi ekleyin.

    1. Çözüm Gezgini'nde, Başvurular'a sağ tıklatın ve Başvuru Ekle'yi tıklatın.

    2. Gözat'ı tıklatın ve Microsoft.VisualStudio.QualityTools.Common.dll'i bulun.

      Derleyici Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies içinde bulunur.

    3. Tamam düğmesini tıklatın.

  8. Bu belgede daha önceden listelenen tanılama veri bağdaştırıcısını sınıf kitaplığınızdaki sınıfa kopyalayın. Bu sınıfı kaydedin.

  9. Projeye kullanıcı denetimi eklemek için, Çözüm Gezginindeki MyDataCollector projesini sağ tıklatın, Ekle'ye gelin ve Kullanıcı Denetimi'ni tıklatın. Ekle‘yi tıklatın.

  10. Araç kutusunu kullanarak, kullanıcı denetimine etiket ekleyin ve metin özelliğini Dosya adı:'na değiştirin.

  11. Araç kutusunu kullanarak, kullanıcı denetimine metin kutusu ekleyin ve adı textBoxFileName'e değiştirin.

  12. Çözüm Gezgini'nde, kullanıcı denetimini sağ tıklatın ve Kodu Göster'i tıklatın. Bu kullanıcı denetimi sınıfını, bu belgenin önceki bölümlerinde listelenmiş kullanıcı denetimi sınıfıyla değiştirin. Bu sınıfı kaydedin.

    Not

    Varsayılan değer olarak, kullanıcı denetimine UserControl1 (Kullanıcı Denetimi 1) denir. Kullanıcı denetimi sınıf kodunun kullanıcı denetiminin adını kullandığından emin olun.

  13. Yapılandırma dosyası oluşturmak için Çözüm Gezgini'nde sağ tıklatın, Ekle'nin üzerine gelin ve sonra Yeni Öğe'yi tıklatın. Uygulama Yapılandırma Dosyası öğesini seçmek için tıklatın ardından Ekle seçeneğini tıklatın. Bu, çözümünüze App.config adında bir dosya ekleyecektir.

  14. Daha önce sağlanmış olan örnek üzerindeki XML'i XML dosyasına kopyalayın. Dosyayı kaydedin.

  15. Çözümü oluşturun ve ardından yapı derlemesi App.config doyasını Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\DataCollectors dizinine kopyalayın.

  16. Bu özel tanılama veri bağdaştırıcısını kullanan test ayarlarını oluşturun. Varolan dosyayı toplamak için test ayarlarını yapılandırın.

    Testlerinizi Microsoft Test Yöneticisi'dan çalıştırıyorsanız, test ayarlarınızı atamak ve yok saymak için Özellikler ile Çalıştır komutunu kullanmadan veya testlerinizi çalıştırmadan önce bu test ayarlarını test planınıza atayabilirsiniz. Test ayarları hakkında daha fazla bilgi için bkz. Test Ayarlarını Kullanarak Makinaları Ayarlama ve Tanı Bilgisi Toplama.

  17. Seçilen tanılama veri bağdaştırıcısıyla test ayarlarını kullanarak testlerinizi çalıştırın.

    Test yürütüldüğü zaman belirttiğiniz veri dosyası test sonuçlarınıza eklenecektir.

Ayrıca bkz.

Kavramlar

Tanı Veri Bağdaştırıcısı Nasıl Oluşturulur

Tanılama Veri Bağdaştırıcısı Verileriniz için bir Özel Düzenleyici Nasıl Oluşturulur

Nasıl yapılır: Özel Tanılama Veri Bağdaştırıcısı Yükleme

Özel Veri Toplayan veya Test Makinasını Etkileyen Tanı Veri Bağdaştırıcısı Oluşturma