AWS code-library documentation change
Summary
Added comprehensive C# code examples for Amazon CloudWatch operations including listing metrics, creating dashboards, setting alarms, anomaly detection, and cleanup procedures.
Security assessment
The changes demonstrate general CloudWatch monitoring capabilities but don't address specific security vulnerabilities or explicitly document security features. While alarm creation and SNS integration are shown, these are standard operational practices rather than security-specific mitigations.
Diff
diff --git a/code-library/latest/ug/csharp_4_cloudwatch_code_examples.md b/code-library/latest/ug/csharp_4_cloudwatch_code_examples.md index f365e97cc..f1894dd53 100644 --- a//code-library/latest/ug/csharp_4_cloudwatch_code_examples.md +++ b//code-library/latest/ug/csharp_4_cloudwatch_code_examples.md @@ -4,0 +5,2 @@ +BasicsActions + @@ -10,0 +13,4 @@ The following code examples show you how to perform actions and implement common +_Basics_ are code examples that show you how to perform the essential operations within a service. + +_Actions_ are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios. + @@ -74,0 +81,2225 @@ There's more on GitHub. Find the complete example and learn how to set up and ru +###### Topics + + * Basics + + * Actions + + + + +## Basics + +The following code example shows how to: + + * List CloudWatch namespaces and metrics. + + * Get statistics for a metric and for estimated billing. + + * Create and update a dashboard. + + * Create and add data to a metric. + + * Create and trigger an alarm, then view alarm history. + + * Add an anomaly detector. + + * Get a metric image, then clean up resources. + + + + +**SDK for .NET (v4)** + + +###### Note + +There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples). + +Run an interactive scenario at a command prompt. + + + public class CloudWatchScenario + { + /* + Before running this .NET code example, set up your development environment, including your credentials. + + To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account: + https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics + + This .NET example performs the following tasks: + 1. List and select a CloudWatch namespace. + 2. List and select a CloudWatch metric. + 3. Get statistics for a CloudWatch metric. + 4. Get estimated billing statistics for the last week. + 5. Create a new CloudWatch dashboard with two metrics. + 6. List current CloudWatch dashboards. + 7. Create a CloudWatch custom metric and add metric data. + 8. Add the custom metric to the dashboard. + 9. Create a CloudWatch alarm for the custom metric. + 10. Describe current CloudWatch alarms. + 11. Get recent data for the custom metric. + 12. Add data to the custom metric to trigger the alarm. + 13. Wait for an alarm state. + 14. Get history for the CloudWatch alarm. + 15. Add an anomaly detector. + 16. Describe current anomaly detectors. + 17. Get and display a metric image. + 18. Clean up resources. + */ + + private static ILogger logger = null!; + private static CloudWatchWrapper _cloudWatchWrapper = null!; + private static IConfiguration _configuration = null!; + private static readonly List<string> _statTypes = new List<string> { "SampleCount", "Average", "Sum", "Minimum", "Maximum" }; + private static SingleMetricAnomalyDetector? anomalyDetector = null!; + + static async Task Main(string[] args) + { + // Set up dependency injection for the Amazon service. + using var host = Host.CreateDefaultBuilder(args) + .ConfigureLogging(logging => + logging.AddFilter("System", LogLevel.Debug) + .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) + .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) + .ConfigureServices((_, services) => + services.AddAWSService<IAmazonCloudWatch>() + .AddTransient<CloudWatchWrapper>() + ) + .Build(); + + _configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("settings.json") // Load settings from .json file. + .AddJsonFile("settings.local.json", + true) // Optionally, load local settings. + .Build(); + + logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) + .CreateLogger<CloudWatchScenario>(); + + _cloudWatchWrapper = host.Services.GetRequiredService<CloudWatchWrapper>(); + + Console.WriteLine(new string('-', 80)); + Console.WriteLine("Welcome to the Amazon CloudWatch example scenario."); + Console.WriteLine(new string('-', 80)); + + try + { + var selectedNamespace = await SelectNamespace(); + var selectedMetric = await SelectMetric(selectedNamespace); + await GetAndDisplayMetricStatistics(selectedNamespace, selectedMetric); + await GetAndDisplayEstimatedBilling(); + await CreateDashboardWithMetrics(); + await ListDashboards(); + await CreateNewCustomMetric(); + await AddMetricToDashboard(); + await CreateMetricAlarm(); + await DescribeAlarms(); + await GetCustomMetricData(); + await AddMetricDataForAlarm(); + await CheckForMetricAlarm(); + await GetAlarmHistory(); + anomalyDetector = await AddAnomalyDetector(); + await DescribeAnomalyDetectors(); + await GetAndOpenMetricImage(); + await CleanupResources(); + } + catch (Exception ex) + { + logger.LogError(ex, "There was a problem executing the scenario."); + await CleanupResources(); + } + + } + + /// <summary> + /// Select a namespace. + /// </summary> + /// <returns>The selected namespace.</returns> + private static async Task<string> SelectNamespace() + { + Console.WriteLine(new string('-', 80)); + Console.WriteLine($"1. Select a CloudWatch Namespace from a list of Namespaces."); + var metrics = await _cloudWatchWrapper.ListMetrics(); + // Get a distinct list of namespaces. + var namespaces = metrics.Select(m => m.Namespace).Distinct().ToList(); + for (int i = 0; i < namespaces.Count; i++) + { + Console.WriteLine($"\t{i + 1}. {namespaces[i]}"); + } + + var namespaceChoiceNumber = 0; + while (namespaceChoiceNumber < 1 || namespaceChoiceNumber > namespaces.Count) + { + Console.WriteLine( + "Select a namespace by entering a number from the preceding list:"); + var choice = Console.ReadLine(); + Int32.TryParse(choice, out namespaceChoiceNumber); + } + + var selectedNamespace = namespaces[namespaceChoiceNumber - 1]; + + Console.WriteLine(new string('-', 80)); + + return selectedNamespace; + } + + /// <summary> + /// Select a metric from a namespace. + /// </summary> + /// <param name="metricNamespace">The namespace for metrics.</param> + /// <returns>The metric name.</returns> + private static async Task<Metric> SelectMetric(string metricNamespace) + { + Console.WriteLine(new string('-', 80)); + Console.WriteLine($"2. Select a CloudWatch metric from a namespace."); + + var namespaceMetrics = await _cloudWatchWrapper.ListMetrics(metricNamespace); + + for (int i = 0; i < namespaceMetrics.Count && i < 15; i++) + { + var dimensionsWithValues = namespaceMetrics[i].Dimensions + .Where(d => !string.Equals("None", d.Value)); + Console.WriteLine($"\t{i + 1}. {namespaceMetrics[i].MetricName} " + + $"{string.Join(", :", dimensionsWithValues.Select(d => d.Value))}"); + } + + var metricChoiceNumber = 0;