Как проверить вывод Debug.Writeline() в коде VS?C#

Место общения программистов C#
Ответить
Anonymous
 Как проверить вывод Debug.Writeline() в коде VS?

Сообщение Anonymous »

Я хочу знать, как точно проверить выходные данные Debug.Writeline() в VS Code с использованием расширения C#.

Я использовал .net core 2.2 в качестве платформа для запуска образца теста с этого веб-сайта
https://github.com/Azure/azure-sdk-for- ... s/samples/ Sample1_HelloWorld.cs.

Тест пройден, но я не увидел вывода Debug.Writeline() в терминале. Поэтому я погуглил и обнаружил, что обычным решением является включение следующего кода в мой файл .cs:

Код: Выделить всё

/* Create a listener that outputs to the console screen, and
add it to the debug listeners. */
TextWriterTraceListener myWriter = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(myWriter);
Однако после того, как я поместил код в файл, он не смог найти свойство «прослушиватели» в классе «Отладка». Я снова погуглил и понял, что это связано с тем, что это свойство включено только в .Net Framework 4.8. Поэтому я загрузил .Net Framework v4.8 и изменил TargetFramework следующим образом:
После изменений я снова запустил тест:

Код: Выделить всё

dotnet test
Но результат всё равно такой:

Код: Выделить всё

Microsoft (R) Test Execution Command Line Tool Version 16.2.0-preview-20190606-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...

Test Run Successful.
Total tests: 1
Passed: 1
Это мой файл .csproj:

Код: Выделить всё


Exe
net48









Это пример теста, который я выполнил без изменений:

Код: Выделить всё

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

using Azure.Identity;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Threading;

namespace Azure.Security.KeyVault.Keys.Samples
{
/// 
/// Sample demonstrates how to set, get, update and delete a key using the synchronous methods of the KeyClient.
/// 
[Category("Live")]
public partial class HelloWorld
{
[Test]
public void HelloWorldSync()
{
// Environment variable with the Key Vault endpoint.
string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

// Instantiate a key client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

// Let's create a RSA key valid for 1 year.  If the key
// already exists in the Key Vault, then a new version of the key is created.
string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
var rsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048)
{
Expires = DateTimeOffset.Now.AddYears(1)
};

client.CreateRsaKey(rsaKey);

// Let's Get the Cloud RSA Key from the Key Vault.
Key cloudRsaKey = client.GetKey(rsaKeyName);
Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}");

// After one year, the Cloud RSA Key is still required, we need to update the expiry time of the key.
// The update method can be used to update the expiry attribute of the key.
cloudRsaKey.Expires.Value.AddYears(1);
KeyBase updatedKey = client.UpdateKey(cloudRsaKey, cloudRsaKey.KeyMaterial.KeyOps);
Debug.WriteLine($"Key's updated expiry time is {updatedKey.Expires}");

// We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure
// it has the required size.
// Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault
// with the new specified size.
var newRsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 4096)
{
Expires = DateTimeOffset.Now.AddYears(1)
};

client.CreateRsaKey(newRsaKey);

// The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
client.DeleteKey(rsaKeyName);

// To ensure key is deleted on server side.
Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName));

// If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
client.PurgeDeletedKey(rsaKeyName);

}

private bool WaitForDeletedKey(KeyClient client, string keyName)
{
int maxIterations = 20;
for (int i = 0; i < maxIterations; i++)
{
try
{
client.GetDeletedKey(keyName);
return true;
}
catch
{
Thread.Sleep(5000);
}
}
return false;
}
}
}
Это тест после модификации:

Код: Выделить всё

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

using Azure.Identity;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Threading;

namespace Azure.Security.KeyVault.Keys.Samples
{
/// 
/// Sample demonstrates how to set, get, update and delete a key using the synchronous methods of the KeyClient.
/// 
[Category("Live")]
public partial class HelloWorld
{
[Test]
public static void Main()
{
/* Create a listener that outputs to the console screen, and
add it to the debug listeners. */
TextWriterTraceListener myWriter = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(myWriter);

// Environment variable with the Key Vault endpoint.
string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

// Instantiate a key client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

// Let's create a RSA key valid for 1 year.  If the key
// already exists in the Key Vault, then a new version of the key is created.
string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
var rsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048)
{
Expires = DateTimeOffset.Now.AddYears(1)
};

client.CreateRsaKey(rsaKey);
// Let's Get the Cloud RSA Key from the Key Vault.
Key cloudRsaKey = client.GetKey(rsaKeyName);
Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}");

// After one year, the Cloud RSA Key is still required, we need to update the expiry time of the key.
// The update method can be used to update the expiry attribute of the key.
cloudRsaKey.Expires.Value.AddYears(1);
KeyBase updatedKey = client.UpdateKey(cloudRsaKey, cloudRsaKey.KeyMaterial.KeyOps);
Debug.WriteLine($"Key's updated expiry time is {updatedKey.Expires}");

// We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure
// it has the required size.
// Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault
// with the new specified size.
var newRsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 4096)
{
Expires = DateTimeOffset.Now.AddYears(1)
};

client.CreateRsaKey(newRsaKey);

// The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
client.DeleteKey(rsaKeyName);

// To ensure key is deleted on server side.
// Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName));

// If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
// client.PurgeDeletedKey(rsaKeyName);

}

private bool WaitForDeletedKey(KeyClient client, string keyName)
{
int maxIterations = 20;
for (int i = 0; i < maxIterations; i++)
{
try
{
client.GetDeletedKey(keyName);
return true;
}
catch
{
Thread.Sleep(5000);
}
}
return false;
}
}
}
В конце концов я попытался набрать в терминале следующее:

Код: Выделить всё

dotnet run
Наконец-то я получил от терминала то, что ожидал, в таком формате:

Код: Выделить всё

Key is returned with name CloudRsaKey-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and type xxx
Key's updated expiry time is x/xx/20xx x:xx:xx AM +00:00
Но я хочу знать, является ли это единственным способом увидеть выходные данные Debug.Witeline().
Поскольку я не вводил команду dotnet test в терминале, я не думаю, что на самом деле запускал тест.
Я в полном замешательстве.

Подробнее здесь: https://stackoverflow.com/questions/575 ... in-vs-code
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»