public async Task VerifyCancelCertificateOperation() { // Log details why this fails often for live tests on net461. using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); string certName = Recording.GenerateId(); CertificatePolicy certificatePolicy = DefaultPolicy; CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy); RegisterForCleanup(certName); try { await operation.CancelAsync(); } catch (RequestFailedException e) when(e.Status == 403) { Assert.Inconclusive("The create operation completed before it could be canceled."); } OperationCanceledException ex = Assert.ThrowsAsync <OperationCanceledException>(() => WaitForCompletion(operation)); Assert.AreEqual("The operation was canceled so no value is available.", ex.Message); Assert.IsTrue(operation.HasCompleted); Assert.IsFalse(operation.HasValue); Assert.AreEqual(200, operation.GetRawResponse().Status); }
public async Task ConsoleListener() { await using var scope = await EventHubScope.CreateAsync(1); #region Snippet:EventHubs_Sample10_ConsoleListener #if SNIPPET var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>"; var eventHubName = "<< NAME OF THE EVENT HUB >>"; #else var connectionString = EventHubsTestEnvironment.Instance.EventHubsConnectionString; var eventHubName = scope.EventHubName; #endif var producer = new EventHubProducerClient(connectionString, eventHubName); using AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.LogAlways); try { using var eventBatch = await producer.CreateBatchAsync(); var eventData = new EventData("This is an event body"); if (!eventBatch.TryAdd(eventData)) { throw new Exception($"The event could not be added."); } } finally { await producer.CloseAsync(); } #endregion }
public void LoggingLevel() { #region Snippet:LoggingLevel using AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Warning); using AzureEventSourceListener traceListener = AzureEventSourceListener.CreateTraceLogger(EventLevel.Informational); #endregion }
public void Logging() { #region Snippet:ConsoleLogging // Setup a listener to monitor logged events. using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); #endregion }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var rc = new TokenRequestContext(new string[] { "https://graph.microsoft.com/.default" }); AzureEventSourceListener.CreateConsoleLogger(); services.AddControllersWithViews(); services.AddRazorPages(); // Configure the credential options var options = new DefaultAzureCredentialOptions { ExcludeVisualStudioCodeCredential = true, ExcludeVisualStudioCredential = true, Diagnostics = { IsLoggingEnabled = true } }; // Create a DefaultAzureCredential var cred = new DefaultAzureCredential(options); // Initialize a BlobContainerClient with the credential. services.AddSingleton(new BlobContainerClient(new Uri(Configuration["BlobUri"]), cred)); // Initialize a Graph client with the credential. GraphServiceClient graphServiceClient = new GraphServiceClient( new DelegateAuthenticationProvider((requestMessage) => { requestMessage .Headers .Authorization = new AuthenticationHeaderValue("Bearer", cred.GetToken(rc).Token); return(Task.CompletedTask); })); services.AddSingleton(graphServiceClient); }
public async Task ConsoleListener() { await using var scope = await EventHubScope.CreateAsync(1); #region Snippet:EventHubs_Sample10_ConsoleListener #if SNIPPET var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>"; var eventHubName = "<< NAME OF THE EVENT HUB >>"; #else var connectionString = EventHubsTestEnvironment.Instance.EventHubsConnectionString; var eventHubName = scope.EventHubName; #endif var producer = new EventHubProducerClient(connectionString, eventHubName); using AzureEventSourceListener consoleListener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.LogAlways); try { var events = new[] { new EventData("EventOne"), new EventData("EventTwo") }; await producer.SendAsync(events); } finally { await producer.CloseAsync(); } #endregion }
/// <summary> /// Creates a new instance of the <see cref="SynapseTestEventListener"/> class. /// </summary> public SynapseTestEventListener() { // Log responses when running live tests for diagnostics. if ("Live".Equals(Environment.GetEnvironmentVariable("AZURE_SYNAPSE_TEST_MODE"), StringComparison.OrdinalIgnoreCase)) { _listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); } }
private static CommandLineBuilder GetCommandLine() { RootCommand root = new RootCommand("parent") { Description = $"Microsoft IoT Models Repository CommandLine v{Outputs.CommandLineVersion}" }; root.Name = Outputs.RootCommandName; root.Add(BuildExportCommand()); root.Add(BuildValidateCommand()); root.Add(BuildImportModelCommand()); root.Add(BuildRepoIndexCommand()); root.Add(BuildRepoExpandCommand()); root.AddGlobalOption(CommonOptions.Debug); root.AddGlobalOption(CommonOptions.Silent); CommandLineBuilder builder = new CommandLineBuilder(root); builder.UseMiddleware(async(context, next) => { AzureEventSourceListener listener = null; try { if (context.ParseResult.Tokens.Any(x => x.Type == TokenType.Option && x.Value == "--debug")) { Outputs.WriteHeader(); listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); Outputs.WriteDebug(context.ParseResult.ToString()); } if (context.ParseResult.Tokens.Any(x => x.Type == TokenType.Option && x.Value == "--silent")) { System.Console.SetOut(TextWriter.Null); } await next(context); } finally { if (listener != null) { listener.Dispose(); } } }); return(builder); }
public void Logging() { // Retrieve the connection string from the configuration store. // You can get the string from your Azure portal. var connectionString = Environment.GetEnvironmentVariable("APPCONFIGURATION_CONNECTION_STRING"); var client = new ConfigurationClient(connectionString); // Setup a listener to monitor logged events. using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.LogAlways); Response <ConfigurationSetting> setResponse = client.Set(new ConfigurationSetting("some_key", "some_value")); if (setResponse.GetRawResponse().Status != 200) { throw new Exception("could not set configuration setting"); } // Delete the setting when you don't need it anymore. client.Delete("some_key"); }
public async Task VerifyCancelCertificateOperation() { // Log details why this fails often for live tests on net461. using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); string certName = Recording.GenerateId(); CertificatePolicy certificatePolicy = DefaultPolicy; CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, certificatePolicy); RegisterForCleanup(certName); try { await Client.CancelCertificateOperationAsync(certName); } catch (RequestFailedException ex) when(ex.Status == 403) { Assert.Inconclusive("The create operation completed before it could be canceled."); } Assert.ThrowsAsync <OperationCanceledException>(() => WaitForCompletion(operation)); }
public static void Main(string[] args) { using var listener = AzureEventSourceListener.CreateConsoleLogger(); CreateHostBuilder(args).Build().Run(); }
public KeyVaultProxyTests(SecretsFixture fixture) { _fixture = fixture ?? throw new ArgumentNullException(nameof(fixture)); _logger = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); }
static async Task Main(string[] args) { // Listen to events produced from all Azure SDK clients using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); // We don't want to use connection string, since it is highly insecure //string connectionString = Environment.GetEnvironmentVariable("ITPRODEV_STORAGE_ACCOUNT_CONNECTION_STRING"); //BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); // We can configure and extend the HTTP pipeline through XxxClientOptions BlobClientOptions options = new BlobClientOptions(); options.Retry.MaxRetries = 10; options.Diagnostics.IsTelemetryEnabled = false; options.AddPolicy(new MyCustomPolicy(), HttpPipelinePosition.PerCall); // Get a reference to our storage account. We use the public Uri and DefaultAzureCredential for authentication Uri blobServiceUri = new Uri("https://itprodev2020storage.blob.core.windows.net/"); BlobServiceClient blobServiceClient = new BlobServiceClient(blobServiceUri, new DefaultAzureCredential(), options); // Get a reference to "itprodev-container" container. This clients inherits the HTTP Pipeline options from BlobServiceClient BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("itprodev-container"); // Create container if not exists await blobContainerClient.CreateIfNotExistsAsync(); // Create a dummy file string path = Utilities.CreateTempFile(); // Get a reference to a blob BlobClient blob = blobContainerClient.GetBlobClient(Utilities.RandomName()); // Upload file to blob await blob.UploadAsync(path); // Delete local file Utilities.DeleteFile(path); // asynchronously iterate through all blobs await foreach (BlobItem item in blobContainerClient.GetBlobsAsync()) { // Get a path on disk where we can download the file string downloadPath = $"{item.Name}.txt"; // Get a reference to blob and download its contents BlobDownloadInfo download = await blobContainerClient.GetBlobClient(item.Name).DownloadAsync(); // Copy its contents to disk using FileStream file = File.OpenWrite(downloadPath); await download.Content.CopyToAsync(file); } // When a service call fails Azure.RequestFailedException would get thrown. // The exception type provides a Status property with an HTTP status code an an ErrorCode property with a service-specific error code. try { //... } // handle exception with status code 404 catch (RequestFailedException e) when(e.Status == 404) { Console.WriteLine("ErrorCode " + e.ErrorCode); } }
public void LoggingLevel() { #region Snippet:ConsoleLoggingLevel using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Warning); #endregion }
public async Task UpdatingCacheLogsEvents() { using var logger = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose); var client = CreateClient(); var groupName = TestEnvironment.SchemaRegistryGroup; var serializer = new SchemaRegistryAvroSerializer(client, groupName, new SchemaRegistryAvroSerializerOptions { AutoRegisterSchemas = true }); var employee = new Employee { Age = 42, Name = "Caketown" }; EventData eventData = await serializer.SerializeAsync <EventData, Employee>(employee); Assert.IsFalse(eventData.IsReadOnly); string[] contentType = eventData.ContentType.Split('+'); Assert.AreEqual(2, contentType.Length); Assert.AreEqual("avro/binary", contentType[0]); Assert.IsNotEmpty(contentType[1]); Employee deserialized = await serializer.DeserializeAsync <Employee>(eventData); // decoding should not alter the message contentType = eventData.ContentType.Split('+'); Assert.AreEqual(2, contentType.Length); Assert.AreEqual("avro/binary", contentType[0]); Assert.IsNotEmpty(contentType[1]); // verify the payload was decoded correctly Assert.IsNotNull(deserialized); Assert.AreEqual("Caketown", deserialized.Name); Assert.AreEqual(42, deserialized.Age); // Use different schema so we can see the cache updated eventData = await serializer.SerializeAsync <EventData, Employee_V2>(new Employee_V2 { Age = 42, Name = "Caketown", City = "Redmond" }); Assert.IsFalse(eventData.IsReadOnly); eventData.ContentType.Split('+'); Assert.AreEqual(2, contentType.Length); Assert.AreEqual("avro/binary", contentType[0]); Assert.IsNotEmpty(contentType[1]); await serializer.DeserializeAsync <Employee>(eventData); // decoding should not alter the message contentType = eventData.ContentType.Split('+'); Assert.AreEqual(2, contentType.Length); Assert.AreEqual("avro/binary", contentType[0]); Assert.IsNotEmpty(contentType[1]); // verify the payload was decoded correctly Assert.IsNotNull(deserialized); Assert.AreEqual("Caketown", deserialized.Name); Assert.AreEqual(42, deserialized.Age); var events = _listener.EventsById(SchemaRegistryAvroEventSource.CacheUpdatedEvent).ToArray(); Assert.AreEqual(2, events.Length); // first log entry should have 2 as the total number of entries as we maintain two caches for each schema Assert.AreEqual(2, events[0].Payload[0]); // the second payload element is the total schema length Assert.AreEqual(334, events[0].Payload[1]); // second entry will include both V1 and V2 schemas - so 4 total entries Assert.AreEqual(4, events[1].Payload[0]); Assert.AreEqual(732, events[1].Payload[1]); }