Przykładowy projekt do tworzenia adaptera danych diagnostycznych
Opublikowano: czerwiec 2016
"MyDiagnosticDataAdapter" to prosty adapter danych diagnostycznych, który umożliwia dołączenie pliku dziennika do wyników testów po ich uruchomieniu.
Niezbędne są uprawnienia administracyjne na dowolnym komputerze, na którym zainstalowany jest kolektor danych diagnostycznych lub edytor konfiguracji.
Przykład
Ta próbka przedstawia sposób przeprowadzania następujących zadań:
Zastosuj atrybuty, aby klasa stała się wykrywalna dla Microsoft Test Manager jako adapter danych diagnostycznych.
Zastosuj atrybuty do klasy formantu użytkownika, aby stał się wykrywalny dla Microsoft Test Manager jako edytor, którego można używać do zmiany konfiguracji dla adaptera danych diagnostycznych.
Dostępu do danych konfiguracji domyślnej.
Zarejestruj się, aby uczestniczyć w określonych zdarzeniach zbierania danych diagnostycznych.
Załącz plik dziennika przez wysłanie go do DataCollectionSink.
// 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;
}
}
}
Przykład
Jest to Edytor konfiguracji próbek dla karty danych diagnostycznych. Dodaj kontrolkę użytkownika do projektu i utwórz bardzo prosty formularz z etykietą („nazwa pliku dziennika”) i pole tekstowe o nazwie „FileTextBox”.
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;
}
}
}
Przykład
Oto przykładowy plik konfiguracji dla edytora konfiguracji modułów zbierających dane diagnostyczne.
<?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/11">
<DataCollector
typeUri="datacollector://MyCompany/MyDataCollector/1.0">
<DefaultConfiguration>
<!-- Your default config settings-->
<File FullPath="c:\temp\logfile1.txt" />
</DefaultConfiguration>
</DataCollector>
</DataCollectorConfiguration>
</configuration>
Kompilowanie kodu
Aby utworzyć projekt kodu dla tej karty diagnostycznej
Utwórz nowy projekt biblioteki klas o nazwie „MyDataCollector”.
W oknie Eksplorator rozwiązań kliknij projekt prawym przyciskiem myszy, a następnie wybierz Właściwości. Aby wybrać folder do dodania, wybierz Odniesienia ścieżki, a następnie wybierz wielokropek (...).
Wyświetlane jest okno dialogowe Wybierz ścieżkę odwołania.
Wybierz następującą ścieżkę, oparte na katalogu instalacji: Program Files\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies. Wybierz przycisk OK.
Aby dodać folder do ścieżki odniesienia, wybierz Dodaj Folder.
Folder jest wyświetlany na liście ścieżek odniesienia.
Wybierz ikonę Zapisz wszystko, aby zapisać ścieżki odwołania.
Dodaj zestaw Microsoft.VisualStudio.QualityTools.ExecutionCommon.
W Eksploratorze rozwiązań kliknij prawym przyciskiem myszy pozycję Odwołania i wybierz polecenie Dodaj odwołanie.
Wybierz Przeglądaj i zlokalizuj Microsoft.VisualStudio.QualityTools.ExecutionCommon.dll.
Ten zestaw, znajdują się w Program Files\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies.
Wybierz przycisk OK.
Dodaj zestaw Microsoft.VisualStudio.QualityTools.Common.
W Eksploratorze rozwiązań kliknij prawym przyciskiem myszy pozycję Odwołania i wybierz polecenie Dodaj odwołanie.
Wybierz Przeglądaj i zlokalizuj Microsoft.VisualStudio.QualityTools.Common.dll.
Ten zestaw, znajdują się w Program Files\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies.
Wybierz przycisk OK.
Kopiuj klasę adaptera danych diagnostycznych, która została wymieniona we wcześniejszej części tego dokumentu do klasy dla biblioteki klas. Zapisz tę klasę.
Aby dodać formant użytkownika do projektu, kliknij prawym przyciskiem myszy projekt MyDataCollector w Eksploratorze rozwiązań, wskaż Dodaj, a następnie wybierz Formant użytkownika. Wybierz Dodaj.
Za pomocą przybornika można dodawać etykiety do formantu użytkownika i zmienić właściwość Tekst na Nazwa pliku.
Za pomocą przybornika można dodawać pola tekstowe do formantu użytkownika i zmienić nazwę na textBoxFileName.
W Eksploratorze rozwiązań kliknij prawym przyciskiem myszy formant użytkownika, a następnie wybierz polecenie Pokaż kod. Zastąp tę klasę formantu użytkownika klasą formantu użytkownika wymienioną we wcześniejszej części tego dokumentu. Zapisz tę klasę.
Uwaga
Domyślnie formant użytkownika nazywa się UserControl1.Upewnij się, że kod klasy formantu użytkownika używa nazwy Twojego formantu użytkownika.
Aby utworzyć plik konfiguracji, w Eksploratorze rozwiązań, kliknij prawym przyciskiem myszy, wybierz Dodaj a następnie wybierz Nowy element. Wybierz Plik konfiguracyjny aplikacji, a następnie wybierz polecenie Dodaj. Doda to plik o nazwie App.config do rozwiązania.
Skopiuj plik XML z próbki, która została dostarczona wcześniej do pliku XML. Zapisz plik.
Tworzenie rozwiązania, a następnie skopiuj wbudowanego zestawu i App.config plik do Program Files\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\DataCollectors katalogu.
Utwórz ustawienia testu, które korzystają z niestandardowego adaptera danych diagnostycznych. Konfigurowanie ustawień testu do zbierania pliku, który istnieje.
W przypadku uruchamiania testów z programu Microsoft Test Manager można przypisać te ustawienia testów do planu testów przed uruchomieniem testów lub użyć polecenia Uruchom z opcjami w celu przypisywania ustawień testów i zastępowania ustawień testów. Aby uzyskać więcej informacji na temat ustawień testowych, zobacz Konfigurowanie maszyn i zbieranie informacji diagnostycznych za pomocą ustawień testowych.
Uruchom testy przy użyciu ustawień testowych z wybraną kartą danych diagnostycznych.
Plik danych, który określiłeś, zostanie dołączony do wyników testu podczas wykonywania testu.
Zobacz też
Porady: tworzenie adaptera danych diagnostycznych
Porady: tworzenie edytora niestandardowego dla danych dla Twojego adaptera danych diagnostycznych
Porady: instalowanie niestandardowego adaptera danych diagnostycznych
Tworzenie adaptera danych diagnostycznych w celu zbierania danych niestandardowych lub wywierania wpływu na maszynę testową