Skip to content

Commit

Permalink
Simplify using statements and collection initializers
Browse files Browse the repository at this point in the history
  • Loading branch information
Evangelink committed Jan 18, 2022
1 parent 2bd0b50 commit 6fffbd8
Show file tree
Hide file tree
Showing 81 changed files with 1,791 additions and 1,655 deletions.
88 changes: 43 additions & 45 deletions src/DataCollectors/DumpMinitool/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,63 +29,61 @@ static int Main(string[] args)

var process = Process.GetProcessById(processId);

using (var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default;

NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal;
switch (type)
{
NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default;
case DumpTypeOption.Full:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation;
break;
case DumpTypeOption.WithHeap:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation;
break;
case DumpTypeOption.Mini:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo;
break;
}

NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal;
switch (type)
// Retry the write dump on ERROR_PARTIAL_COPY
for (int i = 0; i < 5; i++)
{
// Dump the process!
if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero))
{
case DumpTypeOption.Full:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation;
break;
case DumpTypeOption.WithHeap:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo |
NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation;
break;
case DumpTypeOption.Mini:
dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo;
break;
Console.WriteLine("Dumped process.");
return 0;
}

// Retry the write dump on ERROR_PARTIAL_COPY
for (int i = 0; i < 5; i++)
else
{
// Dump the process!
if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero))
int err = Marshal.GetHRForLastWin32Error();
if (err != NativeMethods.ERROR_PARTIAL_COPY)
{
Console.WriteLine("Dumped process.");
return 0;
Console.WriteLine($"Error dumping process {err}");
Marshal.ThrowExceptionForHR(err);
}
else
{
int err = Marshal.GetHRForLastWin32Error();
if (err != NativeMethods.ERROR_PARTIAL_COPY)
{
Console.WriteLine($"Error dumping process {err}");
Marshal.ThrowExceptionForHR(err);
}
else
{
Console.WriteLine($"Error dumping process, was ERROR_PARTIAL_COPY, retrying.");
}
Console.WriteLine($"Error dumping process, was ERROR_PARTIAL_COPY, retrying.");
}
}

Console.WriteLine($"Error dumping process after 5 retries.");
return 1;
}

Console.WriteLine($"Error dumping process after 5 retries.");
return 1;
}

private static class NativeMethods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,55 +34,51 @@ internal static class EventLogXmlWriter
/// </param>
public static void WriteEventLogEntriesToXmlFile(string xmlFilePath, List<EventLogEntry> eventLogEntries, IFileHelper fileHelper)
{
using (DataTable dataTable = new DataTable())
{
dataTable.Locale = CultureInfo.InvariantCulture;
using DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.InvariantCulture;

// The MaxLength of the Type and Source columns must be set to allow indices to be created on them
DataColumn typeColumn = new DataColumn("Type", typeof(string));
typeColumn.MaxLength = EventLogConstants.TypeColumnMaxLength;
dataTable.Columns.Add(typeColumn);
// The MaxLength of the Type and Source columns must be set to allow indices to be created on them
DataColumn typeColumn = new DataColumn("Type", typeof(string));
typeColumn.MaxLength = EventLogConstants.TypeColumnMaxLength;
dataTable.Columns.Add(typeColumn);

dataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));
dataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));

DataColumn sourceColumn = new DataColumn("Source", typeof(string));
sourceColumn.MaxLength = EventLogConstants.SourceColumnMaxLength;
dataTable.Columns.Add(sourceColumn);
DataColumn sourceColumn = new DataColumn("Source", typeof(string));
sourceColumn.MaxLength = EventLogConstants.SourceColumnMaxLength;
dataTable.Columns.Add(sourceColumn);

dataTable.Columns.Add(new DataColumn("Category", typeof(string)));
dataTable.Columns.Add(new DataColumn("EventID", typeof(long)));
dataTable.Columns.Add(new DataColumn("Description", typeof(string)));
dataTable.Columns.Add(new DataColumn("User", typeof(string)));
dataTable.Columns.Add(new DataColumn("Computer", typeof(string)));
dataTable.ExtendedProperties.Add("TimestampColumnName", "DateTime");
dataTable.ExtendedProperties.Add("IndexColumnNames", "Source,Type");
dataTable.Columns.Add(new DataColumn("Category", typeof(string)));
dataTable.Columns.Add(new DataColumn("EventID", typeof(long)));
dataTable.Columns.Add(new DataColumn("Description", typeof(string)));
dataTable.Columns.Add(new DataColumn("User", typeof(string)));
dataTable.Columns.Add(new DataColumn("Computer", typeof(string)));
dataTable.ExtendedProperties.Add("TimestampColumnName", "DateTime");
dataTable.ExtendedProperties.Add("IndexColumnNames", "Source,Type");

foreach (EventLogEntry entry in eventLogEntries)
{
DataRow row = dataTable.NewRow();
row["Type"] = entry.EntryType.ToString();
row["DateTime"] = entry.TimeGenerated;
row["Source"] = entry.Source;
row["Category"] = entry.Category;
row["EventID"] = entry.InstanceId;
row["Description"] = entry.Message;
row["User"] = entry.UserName;
row["Computer"] = entry.MachineName;
dataTable.Rows.Add(row);
}
foreach (EventLogEntry entry in eventLogEntries)
{
DataRow row = dataTable.NewRow();
row["Type"] = entry.EntryType.ToString();
row["DateTime"] = entry.TimeGenerated;
row["Source"] = entry.Source;
row["Category"] = entry.Category;
row["EventID"] = entry.InstanceId;
row["Description"] = entry.Message;
row["User"] = entry.UserName;
row["Computer"] = entry.MachineName;
dataTable.Rows.Add(row);
}

DataSet dataSet = new DataSet();
dataSet.Locale = CultureInfo.InvariantCulture;
dataSet.Tables.Add(dataTable);
DataSet dataSet = new DataSet();
dataSet.Locale = CultureInfo.InvariantCulture;
dataSet.Tables.Add(dataTable);

// Use UTF-16 encoding
StringBuilder stringBuilder = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(stringBuilder))
{
dataSet.WriteXml(stringWriter, XmlWriteMode.WriteSchema);
fileHelper.WriteAllTextToFile(xmlFilePath, stringBuilder.ToString());
}
}
// Use UTF-16 encoding
StringBuilder stringBuilder = new StringBuilder();
using StringWriter stringWriter = new StringWriter(stringBuilder);
dataSet.WriteXml(stringWriter, XmlWriteMode.WriteSchema);
fileHelper.WriteAllTextToFile(xmlFilePath, stringBuilder.ToString());
}
}
#endregion
Expand Down
14 changes: 6 additions & 8 deletions src/Microsoft.TestPlatform.Build/Tasks/VSTestForwardingApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,13 @@ public int Execute()
Tracing.Trace("VSTest: Starting vstest.console...");
Tracing.Trace("VSTest: Arguments: " + processInfo.FileName + " " + processInfo.Arguments);

using (var activeProcess = new Process { StartInfo = processInfo })
{
activeProcess.Start();
this.activeProcessId = activeProcess.Id;
using var activeProcess = new Process { StartInfo = processInfo };
activeProcess.Start();
this.activeProcessId = activeProcess.Id;

activeProcess.WaitForExit();
Tracing.Trace("VSTest: Exit code: " + activeProcess.ExitCode);
return activeProcess.ExitCode;
}
activeProcess.WaitForExit();
Tracing.Trace("VSTest: Exit code: " + activeProcess.ExitCode);
return activeProcess.ExitCode;
}

public void Cancel()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ internal sealed class TestPlatformDataCollectionEvents : DataCollectionEvents
/// </summary>
internal TestPlatformDataCollectionEvents()
{
this.eventArgsToEventInvokerMap = new Dictionary<Type, EventInvoker>(4);

this.eventArgsToEventInvokerMap[typeof(TestHostLaunchedEventArgs)] = this.OnTestHostLaunched;
this.eventArgsToEventInvokerMap[typeof(SessionStartEventArgs)] = this.OnSessionStart;
this.eventArgsToEventInvokerMap[typeof(SessionEndEventArgs)] = this.OnSessionEnd;
this.eventArgsToEventInvokerMap[typeof(TestCaseStartEventArgs)] = this.OnTestCaseStart;
this.eventArgsToEventInvokerMap[typeof(TestCaseEndEventArgs)] = this.OnTestCaseEnd;
this.eventArgsToEventInvokerMap = new Dictionary<Type, EventInvoker>(4)
{
[typeof(TestHostLaunchedEventArgs)] = this.OnTestHostLaunched,
[typeof(SessionStartEventArgs)] = this.OnSessionStart,
[typeof(SessionEndEventArgs)] = this.OnSessionEnd,
[typeof(TestCaseStartEventArgs)] = this.OnTestCaseStart,
[typeof(TestCaseEndEventArgs)] = this.OnTestCaseEnd
};
}

/// <summary>
Expand Down
24 changes: 9 additions & 15 deletions src/Microsoft.TestPlatform.Common/RunSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,9 @@ public void LoadSettingsXml(string settings)
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, settings);
}

using (var stringReader = new StringReader(settings))
{
var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings);
this.ValidateAndSaveSettings(reader);
}
using var stringReader = new StringReader(settings);
var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings);
this.ValidateAndSaveSettings(reader);
}

/// <summary>
Expand All @@ -113,11 +111,9 @@ public void LoadSettingsXml(string settings)
Justification = "XmlReaderSettings.XmlResolver is not available in core. Suppress until fxcop issue is fixed.")]
public void InitializeSettingsProviders(string settings)
{
using (var stringReader = new StringReader(settings))
{
var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings);
this.ReadRunSettings(reader);
}
using var stringReader = new StringReader(settings);
var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings);
this.ReadRunSettings(reader);
}

#endregion
Expand All @@ -137,11 +133,9 @@ private void ValidateAndSaveSettings(XmlReader reader)
{
var dom = new XmlDocument();
dom.Load(reader);
using (var writer = new StringWriter(CultureInfo.InvariantCulture))
{
dom.Save(writer);
this.SettingsXml = writer.ToString();
}
using var writer = new StringWriter(CultureInfo.InvariantCulture);
dom.Save(writer);
this.SettingsXml = writer.ToString();
}
catch (Exception e)
{
Expand Down
24 changes: 11 additions & 13 deletions src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,19 @@ public AssemblyType GetAssemblyType(string filePath)

try
{
using (var fileStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var peReader = new PEReader(fileStream))
{
// Resources for PEReader:
// 1. https://msdn.microsoft.com/library/windows/desktop/ms680547(v=vs.85).aspx?id=19509
// 2. https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata
using var fileStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var peReader = new PEReader(fileStream);
// Resources for PEReader:
// 1. https://msdn.microsoft.com/library/windows/desktop/ms680547(v=vs.85).aspx?id=19509
// 2. https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata

var peHeaders = peReader.PEHeaders;
var corHeader = peHeaders.CorHeader;
var corHeaderStartOffset = peHeaders.CorHeaderStartOffset;
var peHeaders = peReader.PEHeaders;
var corHeader = peHeaders.CorHeader;
var corHeaderStartOffset = peHeaders.CorHeaderStartOffset;

assemblyType = (corHeader != null && corHeaderStartOffset >= 0) ?
AssemblyType.Managed :
AssemblyType.Native;
}
assemblyType = (corHeader != null && corHeaderStartOffset >= 0) ?
AssemblyType.Managed :
AssemblyType.Native;
}
catch (Exception ex)
{
Expand Down
Loading

0 comments on commit 6fffbd8

Please sign in to comment.