repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello sam accelerate!!" }, { "extra_message", "hello"}, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
51
aws-sam-cli-app-templates
aws
C#
using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace HelloWorld { public class Function { private static async Task Main() { Func<APIGatewayHttpApiV2ProxyRequest, ILambdaContext, Task<APIGatewayHttpApiV2ProxyResponse>> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<MyCustomJsonSerializerContext>()) .Build() .RunAsync(); } private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public static async Task<APIGatewayHttpApiV2ProxyResponse> FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location } }; return new APIGatewayHttpApiV2ProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))] [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyResponse))] public partial class MyCustomJsonSerializerContext : JsonSerializerContext { // By using this partial class derived from JsonSerializerContext, we can generate reflection free JSON Serializer code at compile time // which can deserialize our class and properties. However, we must attribute this class to tell it what types to generate serialization code for // See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-source-generation } }
69
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld.Tests { public class FunctionTest { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); var msg = await stringTask; return msg.Replace("\n",""); } [Fact] public async Task TestHelloWorldFunctionHandler() { var request = new APIGatewayHttpApiV2ProxyRequest(); var context = new TestLambdaContext(); string location = GetCallingIP().Result; Dictionary<string, string> body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location }, }; var expectedResponse = new APIGatewayHttpApiV2ProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; var response = await Function.FunctionHandler(request, context); Console.WriteLine("Lambda Response: \n" + response.Body); Console.WriteLine("Expected Response: \n" + expectedResponse.Body); Assert.Equal(expectedResponse.Body, response.Body); Assert.Equal(expectedResponse.Headers, response.Headers); Assert.Equal(expectedResponse.StatusCode, response.StatusCode); } } }
57
aws-sam-cli-app-templates
aws
C#
using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.CloudWatchEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace {{cookiecutter.project_name}}; public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(CloudWatchEvent<dynamic> evnt, ILambdaContext context) { // All log statements are written to CloudWatch by default. For more information, see // https://docs.aws.amazon.com/lambda/latest/dg/csharp-logging.html context.Logger.LogLine(JsonSerializer.Serialize(evnt)); return "Done"; } }
28
aws-sam-cli-app-templates
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.CloudWatchEvents; namespace {{cookiecutter.project_name}}.Tests; public class FunctionTest { [Fact] public void TestToUpperFunction() { // Invoke the lambda function and confirm the string was upper cased. var function = new Function(); var context = new TestLambdaContext(); var eventPayload = new CloudWatchEvent<dynamic>() { Id = "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", DetailType = "Scheduled Event", Source = "aws.events", Account = "", Time = Convert.ToDateTime("1970-01-01T00:00:00Z"), Region = "us-west-2", Resources = new List<string>() { "arn:aws:events:us-west-2:123456789012:rule/ExampleRule" }, Detail = new { } }; var functionResult = function.FunctionHandler(eventPayload, context); Assert.Equal("Done", functionResult); } }
34
aws-sam-cli-app-templates
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
50
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld.Tests { public class FunctionTest { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); var msg = await stringTask; return msg.Replace("\n",""); } [Fact] public async Task TestHelloWorldFunctionHandler() { var request = new APIGatewayProxyRequest(); var context = new TestLambdaContext(); string location = GetCallingIP().Result; Dictionary<string, string> body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location }, }; var expectedResponse = new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; var function = new Function(); var response = await function.FunctionHandler(request, context); Console.WriteLine("Lambda Response: \n" + response.Body); Console.WriteLine("Expected Response: \n" + expectedResponse.Body); Assert.Equal(expectedResponse.Body, response.Body); Assert.Equal(expectedResponse.Headers, response.Headers); Assert.Equal(expectedResponse.StatusCode, response.StatusCode); } } }
58
aws-sam-cli-app-templates
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
50
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld.Tests { public class FunctionTest { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); var msg = await stringTask; return msg.Replace("\n",""); } [Fact] public async Task TestHelloWorldFunctionHandler() { var request = new APIGatewayProxyRequest(); var context = new TestLambdaContext(); string location = GetCallingIP().Result; Dictionary<string, string> body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location }, }; var expectedResponse = new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; var function = new Function(); var response = await function.FunctionHandler(request, context); Console.WriteLine("Lambda Response: \n" + response.Body); Console.WriteLine("Expected Response: \n" + expectedResponse.Body); Assert.Equal(expectedResponse.Body, response.Body); Assert.Equal(expectedResponse.Headers, response.Headers); Assert.Equal(expectedResponse.StatusCode, response.StatusCode); } } }
58
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; {%- if cookiecutter["Powertools for AWS Lambda (.NET) Tracing"] == "enabled"%} using Amazon.XRay.Recorder.Handlers.AwsSdk; using AWS.Lambda.Powertools.Tracing; {%- endif %} {%- if cookiecutter["Powertools for AWS Lambda (.NET) Metrics"] == "enabled"%} using AWS.Lambda.Powertools.Metrics; {%- endif %} {%- if cookiecutter["Powertools for AWS Lambda (.NET) Logging"] == "enabled"%} using AWS.Lambda.Powertools.Logging; {%- endif %} // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); {%- if cookiecutter["Powertools for AWS Lambda (.NET) Tracing"] == "enabled"%} public Function() { AWSSDKHandler.RegisterXRayForAllServices(); } {%- endif %} {%- if cookiecutter["Powertools for AWS Lambda (.NET) Tracing"] == "enabled"%} [Tracing(SegmentName = "Get Calling IP")] {%- endif %} private static async Task<string> GetCallingIP() { try { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); {%- if cookiecutter["Powertools for AWS Lambda (.NET) Metrics"] == "enabled"%} // Custom Metric // https://awslabs.github.io/aws-lambda-powertools-dotnet/core/metrics/ Metrics.AddMetric("ApiRequestCount", 1, MetricUnit.Count); {%- endif %} return msg.Replace("\n",""); } catch (Exception ex) { {%- if cookiecutter["Powertools for AWS Lambda (.NET) Logging"] == "enabled" %} Logger.LogError(ex); {%- endif %} throw; } } {%- if cookiecutter["Powertools for AWS Lambda (.NET) Tracing"] == "enabled"%} [Tracing(CaptureMode = TracingCaptureMode.ResponseAndError)] {%- endif %} {%- if cookiecutter["Powertools for AWS Lambda (.NET) Metrics"] == "enabled"%} [Metrics(CaptureColdStart = true)] {%- endif %} {%- if cookiecutter["Powertools for AWS Lambda (.NET) Logging"] == "enabled"%} [Logging(CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest)] {%- endif %} public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location } }; {%- if cookiecutter["Powertools for AWS Lambda (.NET) Logging"] == "enabled" %} // Structured logging // https://awslabs.github.io/aws-lambda-powertools-dotnet/core/logging/ Logger.LogInformation("Hello world API - HTTP 200"); {%- endif %} return new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
100
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld.Tests { public class FunctionTest { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); var msg = await stringTask; return msg.Replace("\n",""); } [Fact] public async Task TestHelloWorldFunctionHandler() { Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE", "AWSLambdaPowertools"); // set dummy metrics namespace if env is unavailable var request = new APIGatewayProxyRequest(); var context = new TestLambdaContext(); string location = GetCallingIP().Result; Dictionary<string, string> body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location }, }; var expectedResponse = new APIGatewayProxyResponse { Body = JsonSerializer.Serialize(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; var function = new Function(); var response = await function.FunctionHandler(request, context); Console.WriteLine("Lambda Response: \n" + response.Body); Console.WriteLine("Expected Response: \n" + expectedResponse.Body); Assert.Equal(expectedResponse.Body, response.Body); Assert.Equal(expectedResponse.Headers, response.Headers); Assert.Equal(expectedResponse.StatusCode, response.StatusCode); } } }
58
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using Amazon.S3.Util; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace {{cookiecutter.project_name}} { public class Function { IAmazonS3 S3Client { get; set; } /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { S3Client = new AmazonS3Client(); } /// <summary> /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment. /// </summary> /// <param name="s3Client"></param> public Function(IAmazonS3 s3Client) { this.S3Client = s3Client; } /// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context) { var s3Event = evnt.Records?[0].S3; if(s3Event == null) { return null; } try { var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key); context.Logger.LogLine($"S3 Object Key: {s3Event.Object.Key}"); context.Logger.LogLine(JsonSerializer.Serialize(response)); return response.Headers.ContentType; } catch(Exception e) { context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogLine(e.Message); context.Logger.LogLine(e.StackTrace); throw; } } } }
72
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Moq; using Amazon.Lambda; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.S3Events; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using {{cookiecutter.project_name}}; namespace {{cookiecutter.project_name}}.Tests { public class FunctionTest { [Fact] public async Task TestS3EventLambdaFunction() { var context = new TestLambdaContext(); var bucketName = "lambda-S3JsonLogger-".ToLower() + DateTime.Now.Ticks; var key = "text.txt"; // BEGIN mocking s3Client var s3ClientMock = new Mock<IAmazonS3>(); s3ClientMock.Setup(x => x.Config) .Returns(new AmazonS3Config { RegionEndpoint = RegionEndpoint.USWest2 }); var response = new GetObjectMetadataResponse(); response.Headers.ContentType = "text/plain"; response.Expires = DateTime.Now; s3ClientMock.Setup(x => x.GetObjectMetadataAsync( It.Is<string>(_bucketName => _bucketName == bucketName), // Mock with the given bucket name It.Is<string>(_key => _key == key), // Mock with the given key It.IsAny<CancellationToken>()) ) .Returns(Task.FromResult(response)); var s3Client = s3ClientMock.Object; // END mocking s3Client // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function. var s3Event = new S3Event { Records = new List<S3EventNotification.S3EventNotificationRecord> { new S3EventNotification.S3EventNotificationRecord { S3 = new S3EventNotification.S3Entity { Bucket = new S3EventNotification.S3BucketEntity { Name = bucketName }, Object = new S3EventNotification.S3ObjectEntity { Key = key } } } } }; // Invoke the lambda function and confirm the content type was returned. var function = new Function(s3Client); var contentType = await function.FunctionHandler(s3Event, context); Assert.Equal("text/plain", contentType); } } }
77
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace {{cookiecutter.project_name}} { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { var message = input ?? "Hello from Lambda!"; // All log statements are written to CloudWatch by default. For more information, see // https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html context.Logger.LogLine($"Processed message: {message}"); return message.ToUpper(); } } }
32
aws-sam-cli-app-templates
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using {{cookiecutter.project_name}}; namespace {{cookiecutter.project_name}}.Tests { public class FunctionTest { [Fact] public void TestToUpperFunction() { // Invoke the lambda function and confirm the string was upper cased. var function = new Function(); var context = new TestLambdaContext(); var upperCase = function.FunctionHandler("hello world", context); Assert.Equal("HELLO WORLD", upperCase); } } }
29
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace {{cookiecutter.project_name}}; public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SNS event object and can be used /// to respond to SNS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach(var record in evnt.Records) { await ProcessRecordAsync(record, context); } } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }
45
aws-sam-cli-app-templates
aws
C#
using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SNSEvents; namespace {{cookiecutter.project_name}}.Tests; public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var snsEvent = new SNSEvent { Records = new List<SNSEvent.SNSRecord> { new SNSEvent.SNSRecord { Sns = new SNSEvent.SNSMessage() { Message = "foobar" } } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(snsEvent, context); Assert.Contains("Processed record foobar", logger.Buffer.ToString()); } }
37
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace {{cookiecutter.project_name}} { public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used /// to respond to SQS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task<string> FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach(var message in evnt.Records) { await ProcessMessageAsync(message, context); } return "done"; } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { // All log statements are written to CloudWatch by default. For more information, see // https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html context.Logger.LogLine($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } } }
51
aws-sam-cli-app-templates
aws
C#
using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SQSEvents; using {{cookiecutter.project_name}}; namespace {{cookiecutter.project_name}}.Tests { public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var sqsEvent = new SQSEvent { Records = new List<SQSEvent.SQSMessage> { new SQSEvent.SQSMessage { Body = "foobar" } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(sqsEvent, context); Assert.Contains("Processed message foobar", logger.Buffer.ToString()); } } }
38
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.Core; using System; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.CamelCaseLambdaJsonSerializer))] namespace StockBuyer { public class StockEvent { public int StockPrice { get; set; } } public class TransactionResult { public string Id { get; set; } = string.Empty; public string Price { get; set; } = string.Empty; public string Type { get; set; } = string.Empty; public string Qty { get; set; } = string.Empty; public string Timestamp { get; set; } = string.Empty; } public class Function { private static readonly Random rand = new Random((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); public TransactionResult FunctionHandler(StockEvent stockEvent, ILambdaContext context) { // Sample Lambda function which mocks the operation of buying a random number // of shares for a stock. // For demonstration purposes, this Lambda function does not actually perform any // actual transactions. It simply returns a mocked result. // Parameters // ---------- // stockEvent: StockEvent, required // Input event to the Lambda function // context: ILambdaContext // Lambda Context runtime methods and attributes // Returns // ------ // TransactionResult: Object containing details of the stock buying transaction return new TransactionResult { Id = rand.Next().ToString(), Type = "Buy", Price = stockEvent.StockPrice.ToString(), Qty = (rand.Next() % 10 + 1).ToString(), Timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff") }; } } }
59
aws-sam-cli-app-templates
aws
C#
using System; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.CamelCaseLambdaJsonSerializer))] namespace StockChecker { public class StockEvent { public int StockPrice { get; set; } } public class Function { private static readonly Random rand = new Random((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); public StockEvent FunctionHandler(ILambdaContext context) { // Sample Lambda function which mocks the operation of checking the current price // of a stock. // For demonstration purposes this Lambda function simply returns // a random integer between 0 and 100 as the stock price. // Parameters // ---------- // context: ILambdaContext // Lambda Context runtime methods and attributes // Returns // ------ // StockEvent: Object containing the current price of the stock return new StockEvent { StockPrice = rand.Next() % 100 }; } } }
43
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.Core; using System; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.CamelCaseLambdaJsonSerializer))] namespace StockSeller { public class StockEvent { public int StockPrice; } public class TransactionResult { public string Id { get; set; } = string.Empty; public string Price { get; set; } = string.Empty; public string Type { get; set; } = string.Empty; public string Qty { get; set; } = string.Empty; public string Timestamp { get; set; } = string.Empty; } public class Function { private static readonly Random rand = new Random((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); public TransactionResult FunctionHandler(StockEvent stockEvent, ILambdaContext context) { // Sample Lambda function which mocks the operation of selling a random number // of shares for a stock. // For demonstration purposes, this Lambda function does not actually perform any // actual transactions. It simply returns a mocked result. // Parameters // ---------- // stockEvent: StockEvent, required // Input event to the Lambda function // context: ILambdaContext // Lambda Context runtime methods and attributes // Returns // ------ // TransactionResult: Object containing details of the stock selling transaction return new TransactionResult { Id = rand.Next().ToString(), Type = "Sell", Price = stockEvent.StockPrice.ToString(), Qty = (rand.Next() % 10 + 1).ToString(), Timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff") }; } } }
59
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.TestUtilities; using Xunit; namespace StockBuyer.Tests { public class FunctionTest { [Fact] public void TestStockBuyerFunctionHandler() { var testStockPrice = 34; var request = new StockEvent { StockPrice = testStockPrice }; var context = new TestLambdaContext(); var function = new Function(); var response = function.FunctionHandler(request, context); Assert.True(response.Id is string); Assert.Equal(testStockPrice.ToString(), response.Price); Assert.Equal("Buy", response.Type); Assert.True(response.Timestamp is string); int quantity; if(int.TryParse(response.Qty, out quantity)) { Assert.True(quantity >= 1); Assert.True(quantity <= 10); } else { Assert.True(false, "Quantity was not a valid number."); } } } }
36
aws-sam-cli-app-templates
aws
C#
using Amazon.Lambda.TestUtilities; using Xunit; namespace StockChecker.Tests { public class FunctionTest { [Fact] public void TestStockCheckerFunctionHandler() { var context = new TestLambdaContext(); var function = new Function(); var response = function.FunctionHandler(context); Assert.True(response.StockPrice >= 0); Assert.True(response.StockPrice <= 99); } } }
21
aws-sam-cli-app-templates
aws
C#
using System; using Amazon.Lambda.TestUtilities; using Xunit; namespace StockSeller.Tests { public class FunctionTest { [Fact] public void TestStockSellerFunctionHandler() { var testStockPrice = 86; var request = new StockEvent { StockPrice = testStockPrice }; var context = new TestLambdaContext(); var function = new Function(); var response = function.FunctionHandler(request, context); Assert.True(response.Id is string); Assert.Equal(testStockPrice.ToString(), response.Price); Assert.Equal("Sell", response.Type); Assert.True(response.Timestamp is string); int quantity; if(int.TryParse(response.Qty, out quantity)) { Assert.True(quantity >= 1); Assert.True(quantity <= 10); } else { Assert.True(false, "Quantity was not a valid number."); } } } }
37
aws-sam-cli-app-templates
aws
C#
using System.Text.Json; using Amazon; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using {{cookiecutter.project_name}}.Repositories; var builder = WebApplication.CreateBuilder(args); //Logger builder.Logging .ClearProviders() .AddJsonConsole(); // Add services to the container. builder.Services .AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }); string region = Environment.GetEnvironmentVariable("AWS_REGION") ?? RegionEndpoint.USEast2.SystemName; builder.Services .AddSingleton<IAmazonDynamoDB>(new AmazonDynamoDBClient(RegionEndpoint.GetBySystemName(region))) .AddScoped<IDynamoDBContext, DynamoDBContext>() .AddScoped<IBookRepository, BookRepository>(); // Add AWS Lambda support. When running the application as an AWS Serverless application, Kestrel is replaced // with a Lambda function contained in the Amazon.Lambda.AspNetCoreServer package, which marshals the request into the ASP.NET Core hosting framework. builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda"); app.Run();
43
aws-sam-cli-app-templates
aws
C#
using Amazon.DynamoDBv2.DataModel; using Microsoft.AspNetCore.Mvc; using {{cookiecutter.project_name}}.Entities; using {{cookiecutter.project_name}}.Repositories; namespace {{cookiecutter.project_name}}.Controllers; [Route("api/[controller]")] [Produces("application/json")] public class BooksController : ControllerBase { private readonly ILogger<BooksController> logger; private readonly IBookRepository bookRepository; public BooksController(ILogger<BooksController> logger, IBookRepository bookRepository) { this.logger = logger; this.bookRepository = bookRepository; } // GET api/books [HttpGet] public async Task<ActionResult<IEnumerable<Book>>> Get([FromQuery] int limit = 10) { if (limit <= 0 || limit > 100) return BadRequest("The limit should been between [1-100]"); return Ok(await bookRepository.GetBooksAsync(limit)); } // GET api/books/5 [HttpGet("{id}")] public async Task<ActionResult<Book>> Get(Guid id) { var result = await bookRepository.GetByIdAsync(id); if (result == null) { return NotFound(); } return Ok(result); } // POST api/books [HttpPost] public async Task<ActionResult<Book>> Post([FromBody] Book book) { if (book == null) return ValidationProblem("Invalid input! Book not informed"); var result = await bookRepository.CreateAsync(book); if (result) { return CreatedAtAction( nameof(Get), new { id = book.Id }, book); } else { return BadRequest("Fail to persist"); } } // PUT api/books/5 [HttpPut("{id}")] public async Task<IActionResult> Put(Guid id, [FromBody] Book book) { if (id == Guid.Empty || book == null) return ValidationProblem("Invalid request payload"); // Retrieve the book. var bookRetrieved = await bookRepository.GetByIdAsync(id); if (bookRetrieved == null) { var errorMsg = $"Invalid input! No book found with id:{id}"; return NotFound(errorMsg); } book.Id = bookRetrieved.Id; await bookRepository.UpdateAsync(book); return Ok(); } // DELETE api/books/5 [HttpDelete("{id}")] public async Task<IActionResult> Delete(Guid id) { if (id == Guid.Empty) return ValidationProblem("Invalid request payload"); var bookRetrieved = await bookRepository.GetByIdAsync(id); if (bookRetrieved == null) { var errorMsg = $"Invalid input! No book found with id:{id}"; return NotFound(errorMsg); } await bookRepository.DeleteAsync(bookRetrieved); return Ok(); } }
105
aws-sam-cli-app-templates
aws
C#
using Amazon.DynamoDBv2.DataModel; namespace {{cookiecutter.project_name}}.Entities; // <summary> /// Map the Book Class to DynamoDb Table /// To learn more visit https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DeclarativeTagsList.html /// </summary> [DynamoDBTable("{{cookiecutter.project_name}}BookCatalog")] public class Book { ///<summary> /// Map c# types to DynamoDb Columns /// to learn more visit https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MidLevelAPILimitations.SupportedTypes.html /// <summary> [DynamoDBHashKey] //Partition key public Guid Id { get; set; } = Guid.Empty; [DynamoDBProperty] public string Title { get; set; } = string.Empty; [DynamoDBProperty] public string? ISBN { get; set; } [DynamoDBProperty] //String Set datatype public List<string>? Authors { get; set; } [DynamoDBIgnore] public string? CoverPage { get; set; } }
31
aws-sam-cli-app-templates
aws
C#
using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using {{cookiecutter.project_name}}.Entities; namespace {{cookiecutter.project_name}}.Repositories { public class BookRepository : IBookRepository { private readonly IDynamoDBContext context; private readonly ILogger<BookRepository> logger; public BookRepository(IDynamoDBContext context, ILogger<BookRepository> logger) { this.context = context; this.logger = logger; } public async Task<bool> CreateAsync(Book book) { try { book.Id = Guid.NewGuid(); await context.SaveAsync(book); logger.LogInformation("Book {} is added", book.Id); } catch (Exception ex) { logger.LogError(ex, "fail to persist to DynamoDb Table"); return false; } return true; } public async Task<bool> DeleteAsync(Book book) { bool result; try { // Delete the book. await context.DeleteAsync<Book>(book.Id); // Try to retrieve deleted book. It should return null. Book deletedBook = await context.LoadAsync<Book>(book.Id, new DynamoDBContextConfig { ConsistentRead = true }); result = deletedBook == null; } catch (Exception ex) { logger.LogError(ex, "fail to delete book from DynamoDb Table"); result = false; } if (result) logger.LogInformation("Book {Id} is deleted", book); return result; } public async Task<bool> UpdateAsync(Book book) { if (book == null) return false; try { await context.SaveAsync(book); logger.LogInformation("Book {Id} is updated", book); } catch (Exception ex) { logger.LogError(ex, "fail to update book from DynamoDb Table"); return false; } return true; } public async Task<Book?> GetByIdAsync(Guid id) { try { return await context.LoadAsync<Book>(id); } catch (Exception ex) { logger.LogError(ex, "fail to update book from DynamoDb Table"); return null; } } public async Task<IList<Book>> GetBooksAsync(int limit = 10) { var result = new List<Book>(); try { if (limit <= 0) { return result; } var filter = new ScanFilter(); filter.AddCondition("Id", ScanOperator.IsNotNull); var scanConfig = new ScanOperationConfig() { Limit = limit, Filter = filter }; var queryResult = context.FromScanAsync<Book>(scanConfig); do { result.AddRange(await queryResult.GetNextSetAsync()); } while (!queryResult.IsDone && result.Count < limit); } catch (Exception ex) { logger.LogError(ex, "fail to list books from DynamoDb Table"); return new List<Book>(); } return result; } } }
130
aws-sam-cli-app-templates
aws
C#
using {{cookiecutter.project_name}}.Entities; namespace {{cookiecutter.project_name}}.Repositories { /// <summary> /// Sample DynamoDB Table book CRUD /// </summary> public interface IBookRepository { /// <summary> /// Include new book to the DynamoDB Table /// </summary> /// <param name="book">book to include</param> /// <returns>success/failure</returns> Task<bool> CreateAsync(Book book); /// <summary> /// Remove existing book from DynamoDB Table /// </summary> /// <param name="book">book to remove</param> /// <returns></returns> Task<bool> DeleteAsync(Book book); /// <summary> /// List book from DynamoDb Table with items limit (default=10) /// </summary> /// <param name="limit">limit (default=10)</param> /// <returns>Collection of books</returns> Task<IList<Book>> GetBooksAsync(int limit = 10); /// <summary> /// Get book by PK /// </summary> /// <param name="id">book`s PK</param> /// <returns>Book object</returns> Task<Book?> GetByIdAsync(Guid id); /// <summary> /// Update book content /// </summary> /// <param name="book">book to be updated</param> /// <returns></returns> Task<bool> UpdateAsync(Book book); } }
45
aws-sam-cli-app-templates
aws
C#
using {{cookiecutter.project_name}}.Entities; using {{cookiecutter.project_name}}.Repositories; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Net.Http.Json; using System.Threading.Tasks; using Xunit; namespace {{cookiecutter.project_name}}.Tests { public class BookControllerTest { private readonly WebApplicationFactory<Program> webApplication; public BookControllerTest() { webApplication = new WebApplicationFactory<Program>() .WithWebHostBuilder(builder => { builder.ConfigureServices(services => { //Mock the repository implementation //to remove infra dependencies for Test project services.AddScoped<IBookRepository, MockBookRepository>(); }); }); } [Theory] [InlineData(10)] [InlineData(20)] public async Task Call_GetApiBooks_ShouldReturn_LimitedListOfBooks(int limit) { var client = webApplication.CreateClient(); var books = await client.GetFromJsonAsync<IList<Book>>($"/api/Books?limit={limit}"); Assert.NotEmpty(books); Assert.Equal(limit, books?.Count); } [Theory] [InlineData(0)] [InlineData(101)] public async Task Call_GetApiBook_ShouldReturn_BadRequest(int limit) { var client = webApplication.CreateClient(); var result = await client.GetAsync($"/api/Books?limit={limit}"); Assert.Equal(System.Net.HttpStatusCode.BadRequest, result?.StatusCode); } } }
54
aws-sam-cli-app-templates
aws
C#
using Bogus; using {{cookiecutter.project_name}}.Entities; using {{cookiecutter.project_name}}.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace {{cookiecutter.project_name}}.Tests { internal class MockBookRepository : IBookRepository { private readonly Faker<Book> fakeEntity; public MockBookRepository() { fakeEntity = new Faker<Book>() .RuleFor(o => o.Authors, f => { return new List<string>() { f.Name.FullName(), f.Name.FullName() }; }) .RuleFor(o => o.CoverPage, f => f.Image.LoremPixelUrl()) .RuleFor(o => o.Id, f => Guid.NewGuid()); } public Task<bool> CreateAsync(Book book) { return Task.FromResult(true); } public Task<bool> DeleteAsync(Book book) { return Task.FromResult(true); } public Task<IList<Book>> GetBooksAsync(int limit = 10) { IList<Book> books = fakeEntity.Generate(limit).ToList(); return Task.FromResult(books); } public Task<Book?> GetByIdAsync(Guid id) { _ = fakeEntity.RuleFor(o => o.Id, f => id); var book = fakeEntity.Generate() ?? null; return Task.FromResult(book); } public Task<bool> UpdateAsync(Book book) { return Task.FromResult(true); } } }
54
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers { public static class DiagnosticIds { // Category: AwsSdkRules public const string PreventMD5UseRuleId = "CR1000"; public const string PreventHashAlgorithmCreateRuleId = "CR1001"; public const string PreventStaticLoggersRuleId = "CR1002"; public const string PreventDateTimeNowUseRuleId = "CR1003"; public const string PreventRegionEndpointUseRuleId = "CR1004"; } }
17
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CustomRoslynAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PreventDateTimeNowUseAnalyzer : DiagnosticAnalyzer { private const string Title = "Do not use DateTime.Now or DateTime.UtcNow, use AWSSDKUtils.CorrectedNow or AWSSDKUtils.CorrectedUtcNow"; private const string MessageFormat = "Method {0} of member {1} gets {2}. This property should not be used within the SDK, and instead AWSSDKUtils.CorrectedNow or AWSSDKUtils.CorrectedUtcNow should be used."; private const string Category = "AwsSdkRules"; private const string Description = "Checks code for DateTime.Now or DateTime.UtcNow uses."; private readonly List<string> DateTimeEnumeration = new List<string> { "Now", "UtcNow", "Today"}; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.PreventDateTimeNowUseRuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.SimpleMemberAccessExpression); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { var memberAccessExpr = context.Node as MemberAccessExpressionSyntax; if (memberAccessExpr == null) { return; } // memberAccessExpr.Name == Now || UtcNow var memberAccessExprName = memberAccessExpr.Name.ToString(); if (DateTimeEnumeration.Contains(memberAccessExprName)) { var memberSymbol = context.SemanticModel.GetSymbolInfo(context.Node).Symbol; // check the method is a member of the class DateTime if (memberSymbol?.ContainingType.SpecialType == SpecialType.System_DateTime) { var ancestorsResult = FindAncestors(context.Node.Ancestors()); var diagnostic = Diagnostic.Create(Rule, memberAccessExpr.GetLocation(), ancestorsResult.MethodIdentifier ?? "null", ancestorsResult.ClassIdentifier, "System.DateTime." + memberAccessExprName); context.ReportDiagnostic(diagnostic); } } } // Find the Method and Class that declares the DateTime.Now or DateTime.Today private (string MethodIdentifier, string ClassIdentifier) FindAncestors(IEnumerable<SyntaxNode> ancestors) { string methodIdentifier = null; string classIdentifier = null; foreach (var ancestor in ancestors) { var type = ancestor.GetType(); if (type.Equals(typeof(MethodDeclarationSyntax))) { var methodDeclarationSyntax = ancestor as MethodDeclarationSyntax; methodIdentifier = methodDeclarationSyntax.Identifier.Text; } if (type.Equals(typeof(ClassDeclarationSyntax))) { var classDeclarationSyntax = ancestor as ClassDeclarationSyntax; classIdentifier = classDeclarationSyntax.Identifier.Text; } } return (methodIdentifier, classIdentifier); } } }
81
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CustomRoslynAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PreventHashAlgorithmCreateAnalyzer : DiagnosticAnalyzer { private const string Title = "Do not use HashAlgorithm.Create"; private const string MessageFormat = "Method {0} of member {1} invokes {2}. This method should not be used within the SDK, as it may lead to MD5 use, which is not FIPS compliant."; private const string Category = "AwsSdkRules"; private const string Description = "Checks code for HashAlgorithm.Create uses."; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.PreventHashAlgorithmCreateRuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.InvocationExpression); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { var invocationExpr = (InvocationExpressionSyntax)context.Node; if (invocationExpr == null) { return; } // memeberAccessExpr equals the expression before "(", which is HashAlgorithm.Create var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax; if (memberAccessExpr?.Name.ToString() == "Create") { var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol; var returnType = memberSymbol?.ReturnType.ToString(); if (returnType == "HashAlgorithm" || returnType == "System.Security.Cryptography.HashAlgorithm") { var ancestorsResult = FindAncestors(context.Node.Ancestors()); var diagnostic = Diagnostic.Create(Rule, invocationExpr.GetLocation(), ancestorsResult.MethodIdentifier ?? "null", ancestorsResult.ClassIdentifier, "System.Security.Cryptography." + invocationExpr.ToString()); context.ReportDiagnostic(diagnostic); } } } // Find the Method and Class that use the HashAlgorithm.Create private (string MethodIdentifier, string ClassIdentifier) FindAncestors(IEnumerable<SyntaxNode> ancestors) { string methodIdentifier = null; string classIdentifier = null; foreach (var ancestor in ancestors) { var type = ancestor.GetType(); if (type.Equals(typeof(MethodDeclarationSyntax))) { var methodDeclarationSyntax = ancestor as MethodDeclarationSyntax; methodIdentifier = methodDeclarationSyntax.Identifier.Text; } if (type.Equals(typeof(ClassDeclarationSyntax))) { var classDeclarationSyntax = ancestor as ClassDeclarationSyntax; classIdentifier = classDeclarationSyntax.Identifier.Text; } } return (methodIdentifier, classIdentifier); } } }
81
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CustomRoslynAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PreventMD5UseAnalyzer : DiagnosticAnalyzer { private const string Title = "Do not use MD5"; private const string MessageFormat = "Type {0} of member {1} is a subclass of MD5. MD5 should not be used within the SDK, as it is not FIPS compliant."; private const string Category = "AwsSdkRules"; private const string Description = "Checks code for MD5 uses."; private const string MD5FullName = "System.Security.Cryptography.MD5"; private const string MD5ShortName = "MD5"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.PreventMD5UseRuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzePropertyNode, SyntaxKind.PropertyDeclaration); context.RegisterSyntaxNodeAction(AnalyzeFieldNode, SyntaxKind.FieldDeclaration); context.RegisterSyntaxNodeAction(AnalyzeMethodNode, SyntaxKind.MethodDeclaration); context.RegisterSyntaxNodeAction(AnalyzeInvocationExpressionNode, SyntaxKind.InvocationExpression); } // Analyze the Property Declaration private void AnalyzePropertyNode(SyntaxNodeAnalysisContext context) { var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; if (propertyDeclaration == null) { return; } var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration); if (propertySymbol != null) { CheckType(propertySymbol.Type, context, propertyDeclaration.Type.GetLocation()); } } // Analyze the Field Declaration private void AnalyzeFieldNode(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; if (fieldDeclaration == null) { return; } var fieldSymbol = context.SemanticModel.GetSymbolInfo(fieldDeclaration.Declaration.Type).Symbol as INamedTypeSymbol; if (fieldSymbol != null) { // Check for Lambda expression's type var genericTypeofLambdaFunc = fieldDeclaration.Declaration.Type as GenericNameSyntax; if (genericTypeofLambdaFunc != null) { AnalyzeLambdaExpressionType(context, genericTypeofLambdaFunc); } // Check for the rest of field symbol CheckType(fieldSymbol, context, fieldDeclaration.GetLocation()); } } // Analyze the Method private void AnalyzeMethodNode(SyntaxNodeAnalysisContext context) { var methodDeclaration = (MethodDeclarationSyntax)context.Node; // Analyze the parameter foreach (var parameter in methodDeclaration.ParameterList.Parameters) { var typeSymbol = context.SemanticModel.GetSymbolInfo(parameter.Type).Symbol as INamedTypeSymbol; if (typeSymbol != null) { CheckType(typeSymbol, context, parameter.GetLocation()); } } // Analyze the method body if (methodDeclaration.Body != null) { var methodBodyStatement = methodDeclaration.Body.Statements; foreach (var statement in methodBodyStatement) { var localDeclaration = statement as LocalDeclarationStatementSyntax; if (localDeclaration != null) { var typeSymbol = context.SemanticModel.GetSymbolInfo(localDeclaration.Declaration.Type).Symbol as INamedTypeSymbol; if (typeSymbol != null && !localDeclaration.Declaration.Type.ToString().Equals("var")) { CheckType(typeSymbol, context, localDeclaration.Declaration.Type.GetLocation()); } } } } } // Analyze the extra senario - Invocation Expression private void AnalyzeInvocationExpressionNode(SyntaxNodeAnalysisContext context) { var invocationExpr = context.Node as InvocationExpressionSyntax; // memeberAccessExpr equals the expression before "(", which is MD5 var memberAccessExpr = invocationExpr?.Expression as MemberAccessExpressionSyntax; if (memberAccessExpr == null) { return; } if (memberAccessExpr.Name.ToString() == "Create") { var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol; if (memberSymbol == null) { return; } var memberSymbolSpecialType = memberSymbol.ContainingType; if (memberSymbolSpecialType != null) { CheckType(memberSymbolSpecialType, context, invocationExpr.GetLocation()); } } } // Analyze the Lambda expression's generic type private void AnalyzeLambdaExpressionType(SyntaxNodeAnalysisContext context, GenericNameSyntax genericTypeofLambdaFunc) { if (genericTypeofLambdaFunc.GetType().Equals(typeof(GenericNameSyntax))) { foreach (var argument in genericTypeofLambdaFunc.TypeArgumentList.Arguments) { var argumentNameSyntax = argument as IdentifierNameSyntax; if (argumentNameSyntax?.Identifier.Text == "MD5") { var argumentSymbol = context.SemanticModel.GetSymbolInfo(argument).Symbol as INamedTypeSymbol; CheckType(argumentSymbol, context, argument.GetLocation()); } } } } private void CheckType(ITypeSymbol type, SyntaxNodeAnalysisContext context, Location location) { if (IsAssignableToMD5(type)) { var ancestorsResult = FindAncestors(context.Node); var diagnostic = Diagnostic.Create(Rule, location, type.ToString(), ancestorsResult); context.ReportDiagnostic(diagnostic); } } private bool IsAssignableToMD5(ITypeSymbol type) { if (string.Equals(type.Name, MD5FullName) || string.Equals(type.Name, MD5ShortName)) { return true; } var baseType = type.BaseType; if (baseType == null) { return false; } return IsAssignableToMD5(baseType); } // Find the Method and Class that uees the MD5 private string FindAncestors(SyntaxNode node) { var ancestors = node.Ancestors(); foreach (var ancestor in ancestors) { var type = ancestor.GetType(); if (type.Equals(typeof(ClassDeclarationSyntax))) { if (node.GetType().Equals(typeof(MethodDeclarationSyntax))) { return (node as MethodDeclarationSyntax).Identifier.Text; } if (node.GetType().Equals(typeof(FieldDeclarationSyntax)) || node.GetType().Equals(typeof(PropertyDeclarationSyntax)) || node.GetType().Equals(typeof(InvocationExpressionSyntax))) { return (ancestor as ClassDeclarationSyntax).Identifier.Text; } } if (type.Equals(typeof(MethodDeclarationSyntax))) { var methodDeclarationSyntax = ancestor as MethodDeclarationSyntax; return methodDeclarationSyntax.Identifier.Text; } } return ""; } } }
208
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CustomRoslynAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PreventRegionEndpointUseAnalyzer : DiagnosticAnalyzer { private const string Title = "Do not use static readonly RegionEndpoint members from within the SDK."; private const string MessageFormat = "Target member uses {0}. This member {1} be used within the SDK. {2}"; private const string Category = "AwsSdkRules"; private const string Description = "Makes sure none of the static readonly RegionEndpoint members are used directly within the SDK itself."; private const string ExtraResolutionMessage = "Evaluate whether this usage is safe and add a suppression if it is."; private const string RegionEndpointTypeName = "RegionEndpoint"; private const string USEast1EndpointName = "USEast1"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.PreventRegionEndpointUseRuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.SimpleMemberAccessExpression); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { var memberAccessExpr = context.Node as MemberAccessExpressionSyntax; var memberSymbol = context.SemanticModel.GetSymbolInfo(context.Node).Symbol as IFieldSymbol; var memberSymbolTypeName = memberSymbol?.ContainingType.Name; if (memberSymbolTypeName?.ToString() == RegionEndpointTypeName) { var memberAccessExpressionString = memberAccessExpr.ToString(); if (memberAccessExpressionString.EndsWith(USEast1EndpointName)) { var diagnostic = Diagnostic.Create(Rule, memberAccessExpr.GetLocation(), memberAccessExpressionString, "shouldn't usually", ExtraResolutionMessage); context.ReportDiagnostic(diagnostic); } // To check if it is a static readonly member except USEast1 and not a method else if (memberSymbol.IsStatic && memberSymbol.IsReadOnly) { var diagnostic = Diagnostic.Create(Rule, memberAccessExpr.GetLocation(), memberAccessExpressionString, "should never", ExtraResolutionMessage); context.ReportDiagnostic(diagnostic); } } } } }
62
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CustomRoslynAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PreventStaticLoggersAnalyzer : DiagnosticAnalyzer { private const string Title = "Do not store ILogger instances in static members."; private const string MessageFormat = "Static member {0} of type {1} implements {2}. Instances of {2} should not be stored in static variables. Logger configuration can change during SDK use, but static references are not impacted by this."; private const string Category = "AwsSdkRules"; private const string Description = "Checks code for static ILogger variables."; private const string LoggerInterfaceFullName = "ILogger"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.PreventStaticLoggersRuleId, Title, MessageFormat, Category, DiagnosticSeverity.Error, true, Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldNode, SyntaxKind.FieldDeclaration); context.RegisterSyntaxNodeAction(AnalyzePropertyNode, SyntaxKind.PropertyDeclaration); } // Analyze field private void AnalyzeFieldNode(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; if (fieldDeclaration == null) { return; } // Check the modifiers of the node contains static if (fieldDeclaration.Modifiers.SingleOrDefault(m => m.Text.Contains("static")).Text != "") { var fieldSymbol = context.SemanticModel.GetSymbolInfo(fieldDeclaration.Declaration.Type).Symbol as INamedTypeSymbol; if (fieldSymbol != null && ImplementsILogger(fieldSymbol)) { var findAncestorsResult = FindAncestors(context.Node.Ancestors()); var diagnostic = Diagnostic.Create(Rule, fieldDeclaration.GetLocation(), findAncestorsResult, fieldSymbol.ToString(), LoggerInterfaceFullName); context.ReportDiagnostic(diagnostic); } } } // check for property that have a setter private void AnalyzePropertyNode(SyntaxNodeAnalysisContext context) { var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; if (propertyDeclaration == null) { return; } var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration); if (propertySymbol != null && propertySymbol.IsStatic && propertySymbol.SetMethod != null && ImplementsILogger(propertySymbol.Type)) { var ancestorsResult = FindAncestors(context.Node.Ancestors()); var diagnostic = Diagnostic.Create(Rule, propertyDeclaration.GetLocation(), ancestorsResult, propertySymbol.Type.ToString(), LoggerInterfaceFullName); context.ReportDiagnostic(diagnostic); } } private bool ImplementsILogger(ITypeSymbol typeSymbol) { if (typeSymbol == null) { return false; } return IsILogger(typeSymbol.Name) || typeSymbol.Interfaces.Any(i => IsILogger(i.Name)) || ImplementsILogger(typeSymbol.BaseType); } private bool IsILogger(string name) { return string.Equals(name, LoggerInterfaceFullName); } // Find the Property and Field that declares the ILogger instance private string FindAncestors(IEnumerable<SyntaxNode> ancestors) { var ancestor = ancestors.SingleOrDefault(tmpAncestor => tmpAncestor.GetType().Equals(typeof(ClassDeclarationSyntax))); if (ancestor == null) { return "No Ancestors"; } var classDeclarationSyntax = ancestor as ClassDeclarationSyntax; return classDeclarationSyntax.Identifier.Text; } } }
105
aws-sdk-net
aws
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CustomRoslynAnalyzers { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CustomRoslynAnalyzers.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
64
aws-sdk-net
aws
C#
using System; using System.Composition; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace CustomRoslynAnalyzers.CodeFix { public class BaseClassofCodeFix : CodeFixProvider { protected string DiagnosticId = "DefaultDiagnosticId"; protected string Title = "DefaultTitle"; public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(DiagnosticId); } } public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // This variable is for using the method of CodeFixHelper.cs var codeFixHelper = new CodeFixHelper(); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; // Find the type declaration identified by the diagnostic. var fieldDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<FieldDeclarationSyntax>().FirstOrDefault(); var propertyDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault(); var methodDeclaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault(); // Register a code action that will invoke the fix. if (fieldDeclaration != null) { context.RegisterCodeFix( CodeAction.Create( title: Title, createChangedSolution: c => codeFixHelper.CodeFixHelperInFieldAsync(context.Document, fieldDeclaration, c, DiagnosticId), equivalenceKey: Title), diagnostic); } if (propertyDeclaration != null) { context.RegisterCodeFix( CodeAction.Create( title: Title, createChangedSolution: c => codeFixHelper.CodeFixHelperInPropertyAsync(context.Document, propertyDeclaration, c, DiagnosticId), equivalenceKey: Title), diagnostic); } if (methodDeclaration != null) { context.RegisterCodeFix( CodeAction.Create( title: Title, createChangedSolution: c => codeFixHelper.CodeFixHelperInMethodAsync(context.Document, methodDeclaration, c, DiagnosticId), equivalenceKey: Title), diagnostic); } } } }
79
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CustomRoslynAnalyzers.CodeFix { class CodeFixHelper { public async Task<Solution> CodeFixHelperInFieldAsync(Document document, FieldDeclarationSyntax fieldDeclaration, CancellationToken cancellationToken, string diagnosticId) { var root = await document.GetSyntaxRootAsync(cancellationToken); var attributes = fieldDeclaration.AttributeLists.Add(CreateSuppressMessageAttribute(diagnosticId)); return document.WithSyntaxRoot( root.ReplaceNode( fieldDeclaration, fieldDeclaration.WithAttributeLists(attributes) )).Project.Solution; } public async Task<Solution> CodeFixHelperInPropertyAsync(Document document, PropertyDeclarationSyntax propertyDeclaration, CancellationToken cancellationToken, string diagnosticId) { var root = await document.GetSyntaxRootAsync(cancellationToken); var attributes = propertyDeclaration.AttributeLists.Add(CreateSuppressMessageAttribute(diagnosticId)); return document.WithSyntaxRoot( root.ReplaceNode( propertyDeclaration, propertyDeclaration.WithAttributeLists(attributes) )).Project.Solution; } public async Task<Solution> CodeFixHelperInMethodAsync(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken, string diagnosticId) { var root = await document.GetSyntaxRootAsync(cancellationToken); var attributes = methodDeclaration.AttributeLists.Add(CreateSuppressMessageAttribute(diagnosticId)); return document.WithSyntaxRoot( root.ReplaceNode( methodDeclaration, methodDeclaration.WithAttributeLists(attributes) )).Project.Solution; } // Create Suppress Message by using diagnosticId private AttributeListSyntax CreateSuppressMessageAttribute(string diagnosticId) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList<AttributeSyntax>( SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("SuppressMessage")) .WithArgumentList(SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList<AttributeArgumentSyntax>( new SyntaxNodeOrToken[]{ SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("AWSSDKRules"))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.AttributeArgument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnosticId))) } ))).NormalizeWhitespace())); } } }
62
aws-sdk-net
aws
C#
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.CodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreventDateTimeNowUseAnalyzerCodeFix)), Shared] public class PreventDateTimeNowUseAnalyzerCodeFix : BaseClassofCodeFix { public PreventDateTimeNowUseAnalyzerCodeFix() { DiagnosticId = DiagnosticIds.PreventDateTimeNowUseRuleId; Title = "Suppress Message of DateTime"; } } }
19
aws-sdk-net
aws
C#
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.CodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreventHashAlgorithmCreateAnalyzerCodeFix)), Shared] public class PreventHashAlgorithmCreateAnalyzerCodeFix : BaseClassofCodeFix { public PreventHashAlgorithmCreateAnalyzerCodeFix() { DiagnosticId = DiagnosticIds.PreventHashAlgorithmCreateRuleId; Title = "Suppress Message of HashAlgorithm.Create()"; } } }
18
aws-sdk-net
aws
C#
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.CodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreventMD5UseAnalyzerCodeFix)), Shared] public class PreventMD5UseAnalyzerCodeFix : BaseClassofCodeFix { public PreventMD5UseAnalyzerCodeFix() { DiagnosticId = DiagnosticIds.PreventMD5UseRuleId; Title = "Suppress Message of MD5"; } } }
18
aws-sdk-net
aws
C#
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.CodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreventRegionEndpointUseAnalyzerCodeFixProvider)), Shared] public class PreventRegionEndpointUseAnalyzerCodeFixProvider : BaseClassofCodeFix { public PreventRegionEndpointUseAnalyzerCodeFixProvider() { DiagnosticId = DiagnosticIds.PreventRegionEndpointUseRuleId; Title = "Suppress Message of RegionEndpoint"; } } }
17
aws-sdk-net
aws
C#
using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.CodeFix { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreventStaticLoggerAnalyzerCodeFix)), Shared] public class PreventStaticLoggerAnalyzerCodeFix : BaseClassofCodeFix { public PreventStaticLoggerAnalyzerCodeFix() { DiagnosticId = DiagnosticIds.PreventStaticLoggersRuleId; Title = "Suppress Message of Logger/ILogger"; } } }
18
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using CustomRoslynAnalyzers.Test.TestHelper; using Xunit; using CustomRoslynAnalyzers.CodeFix; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.Test { public partial class PreventDateTimeNowUseAnalyzerTests : CodeFixVerifier { private const string MessageFormat = "Method {0} of member {1} gets {2}. This property should not be used within the SDK, and instead AWSSDKUtils.CorrectedNow or AWSSDKUtils.CorrectedUtcNow should be used."; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PreventDateTimeNowUseAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new PreventDateTimeNowUseAnalyzerCodeFix(); } [Theory] [MemberData(nameof(TestCorrectData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeNowUseAnalyzer_Correct_Test(string data) { var expectedResult = new DiagnosticResult[0]; VerifyCSharpDiagnostic(data, expectedResult); } // A Test for DateTime.Today and DateTime.Now and DateTime.UtcNow in methods [Theory] [MemberData(nameof(TestMethodData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Methods_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "Main", "Program", attribute, 11, 24, testCodeFixData); } // A Test for DateTime.Use and DateTime.Now and DateTime.UtcNow in field [Theory] [MemberData(nameof(TestFieldData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Field_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "null", "Program", attribute, 9, 32, testCodeFixData); } // A Test for DateTime.Use and DateTime.Now and DateTime.UtcNow in parameter [Theory] [MemberData(nameof(TestPassInParameterData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Parameter_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "Main", "Program", attribute, 11, 24, testCodeFixData); } // A Test for DateTime.Use and DateTime.Now and DateTime.UtcNow in parameter [Theory] [MemberData(nameof(TestPropertyData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Property_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "null", "Program", attribute, 13, 24, testCodeFixData); } // A Test for DateTime.Use and DateTime.Now and DateTime.UtcNow in Lambda expressions [Theory] [MemberData(nameof(TestLambdaData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Lambda_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "null", "Program", attribute, 9, 67, testCodeFixData); } // A Test for DateTime.Use and DateTime.Now and DateTime.UtcNow in Delegate expressions [Theory] [MemberData(nameof(TestDelegateData), MemberType = typeof(PreventDateTimeNowUseAnalyzerTests))] public void CR1003_PreventDateTimeUseAnalyzer_Delegate_Tests(string data, string attribute, string codeFixData) { var testData = string.Format(data, attribute); var testCodeFixData = string.Format(codeFixData, attribute); CompareActualAndExpected(testData, "null", "Program", attribute, 10, 50, testCodeFixData); } // Compare the actual diagnostic result with expected result private void CompareActualAndExpected(string testData, string method, string className, string dateTimeAttribute, int row, int colomn, string testCodeFixData) { var expectedResult = new DiagnosticResult { Id = DiagnosticIds.PreventDateTimeNowUseRuleId, Message = string.Format(MessageFormat, method, className, "System." + dateTimeAttribute), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", row, colomn) } }; VerifyCSharpDiagnostic(testData, expectedResult); VerifyCSharpFix(testData, testCodeFixData); } } }
112
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System; using System.Collections.Generic; using System.Text; using CustomRoslynAnalyzers.Test.TestHelper; using Xunit; using Microsoft.CodeAnalysis.CodeFixes; using CustomRoslynAnalyzers.CodeFix; namespace CustomRoslynAnalyzers.Test { public partial class PreventHashAlgorithmCreateAnalyzerTests : CodeFixVerifier { private const string MessageFormat = "Method {0} of member {1} invokes {2}. This method should not be used within the SDK, as it may lead to MD5 use, which is not FIPS compliant."; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PreventHashAlgorithmCreateAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new PreventHashAlgorithmCreateAnalyzerCodeFix(); } // A Correct Case Test [Theory] [MemberData(nameof(TestCorrectData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyzer_Correct_Test(string data) { var expectedResult = new DiagnosticResult[0]; VerifyCSharpDiagnostic(data, expectedResult); } // A Test for HashAlgorithm.Create() in method [Theory] [MemberData(nameof(TestMethodData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyzer_Method_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "Main", "Program", invocation, 12, 24, testCodeFixData); } // A Test for HashAlgorithm.Create() in field [Theory] [MemberData(nameof(TestFieldData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyze_Field_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "null", "Program", invocation, 10, 37, testCodeFixData); } // A Test for HashAlgorithm.Create() in Property [Theory] [MemberData(nameof(TestPropertyData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyze_Property_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "null", "Program", invocation, 14, 24, testCodeFixData); } // A Test for HashAlgorithm.Create() in Parameter [Theory] [MemberData(nameof(TestPassInParameterData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyze_Parameter_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "Main", "Program", invocation, 12, 24, testCodeFixData); } // A Test for HashAlgorithm.Create() in Lambda Expression [Theory] [MemberData(nameof(TestLambdaData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyze_Lambda_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "null", "Program", invocation, 10, 67, testCodeFixData); } // A Test for HashAlgorithm.Create() in Delegate [Theory] [MemberData(nameof(TestDelegateData), MemberType = typeof(PreventHashAlgorithmCreateAnalyzerTests))] public void CR1001_PreventHashAlgorithmCreateAnalyze_Delegate_Test(string data, string invocation, string codeFixData) { var testData = string.Format(data, invocation); var testCodeFixData = string.Format(codeFixData, invocation); CompareActualAndExpected(testData, "null", "Program", invocation, 11, 59, testCodeFixData); } // Compare the actual diagnostic result with expected result private void CompareActualAndExpected(string testData, string methodName, string className, string invocation , int row, int column, string testCodeFixData) { var expectedResult = new DiagnosticResult { Id = DiagnosticIds.PreventHashAlgorithmCreateRuleId, Message = string.Format(MessageFormat, methodName, className, "System.Security.Cryptography." + invocation), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", row, column) } }; VerifyCSharpDiagnostic(testData, expectedResult); VerifyCSharpFix(testData, testCodeFixData); } } }
113
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using CustomRoslynAnalyzers.Test.TestHelper; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using CustomRoslynAnalyzers.CodeFix; using Microsoft.CodeAnalysis.CodeFixes; namespace CustomRoslynAnalyzers.Test { public partial class PreventMD5AnalyzerTests : CodeFixVerifier { private const string MessageFormat = "Type {0} of member {1} is a subclass of MD5. MD5 should not be used within the SDK, as it is not FIPS compliant."; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PreventMD5UseAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new PreventMD5UseAnalyzerCodeFix(); } // A test for correct test [Fact] public void CR1000_PreventMD5UseAnalyzer_Correct_Test() { string data = @" using System.Security.Cryptography; namespace TestPreventMD5UseAnalyzer { class Program { static void Main(string[] args) { } public void test3(object m) { } } }"; var expectedResult = new DiagnosticResult[0]; VerifyCSharpDiagnostic(data, expectedResult); } /// A test for all of the senarios including /// Field, Property, InsideMethod, /// Declare Method, PassIn Parameter to Method, Lambda Expression, Delegate [Theory] [MemberData(nameof(TestInsideMethodData), MemberType = typeof(PreventMD5AnalyzerTests))] public void CR1000_PreventMD5UseAnalyzer_Multiple_Tests(string data, string typeData, string belongsToData, int row, int column, string codeFixData) { var expectedResult = new DiagnosticResult { Id = DiagnosticIds.PreventMD5UseRuleId, Message = string.Format(MessageFormat, typeData, belongsToData), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", row, column) } }; VerifyCSharpDiagnostic(data, expectedResult); VerifyCSharpFix(data, codeFixData); } } }
71
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using CustomRoslynAnalyzers.Test.TestHelper; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using CustomRoslynAnalyzers.CodeFix; namespace CustomRoslynAnalyzers.Test { public partial class PreventRegionEndpointUseAnalyzerTests : CodeFixVerifier { private const string MessageFormat = "Target member uses {0}. This member {1} be used within the SDK. {2}"; private const string USEast1ResolutionMessage = "Evaluate whether this usage is safe and add a suppression if it is."; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PreventRegionEndpointUseAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new PreventRegionEndpointUseAnalyzerCodeFixProvider(); } // A Test for the correct test [Fact] public void CR1004_PreventRegionEndpointUseAnalyzer_Correct_Tests() { string data = @" namespace TestPreventRegionEndpointUseAnalyzer { class Program { static void Main(string[] args) { } } }"; var expectedResult = new DiagnosticResult[0]; VerifyCSharpDiagnostic(data, expectedResult); } // A test for all of the senarios including Field, Property, InsideMethod, Declare Method, PassIn Parameter to Method, Lambda Expression, Delegate [Theory] [MemberData(nameof(TestInsideMethodData), MemberType = typeof(PreventRegionEndpointUseAnalyzerTests))] public void CR1004_PreventRegionEndpointUseAnalyzer_Multiple_Tests(string data, int row, int column, string codeFixData) { var expectedResult = new DiagnosticResult { Id = DiagnosticIds.PreventRegionEndpointUseRuleId, Message = string.Format(MessageFormat, "RegionEndpoint.USEast1", "shouldn't usually", USEast1ResolutionMessage), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", row, column) } }; if (!data.Contains("USEast1")) { expectedResult.Message = string.Format(MessageFormat, "RegionEndpoint.USWest1", "should never", USEast1ResolutionMessage); } VerifyCSharpDiagnostic(data, expectedResult); VerifyCSharpFix(data, codeFixData); } } }
71
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using CustomRoslynAnalyzers.Test.TestHelper; using Xunit; using CustomRoslynAnalyzers.CodeFix; namespace CustomRoslynAnalyzers.Test { public partial class PreventStaticLoggersAnalyzerTests : CodeFixVerifier { private const string MessageFormat = "Static member {0} of type {1} implements {2}. Instances of {2} should not be stored in static variables. Logger configuration can change during SDK use, but static references are not impacted by this."; protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PreventStaticLoggersAnalyzer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new PreventStaticLoggerAnalyzerCodeFix(); } // A test for the Correct Case [Fact] public void CR1002_PreventRegionEndpointUseAnalyzer_Correct_Tests() { string data = @" namespace TestPreventStaticLoggersAnalyzer { class Program { static void Main(string[] args) { } } }"; var expectedResult = new DiagnosticResult[0]; VerifyCSharpDiagnostic(data, expectedResult); } // A test for all of the senarios including Static Field, Static Property [Theory] [MemberData(nameof(AllTestData), MemberType = typeof(PreventStaticLoggersAnalyzerTests))] public void CR1002_PreventStaticLoggersAnalyzer_Multiple_Tests(string dataWithoutLogger, string declaringTypeName, string selfType, string interfaceName, int row, int column, string codeFixDataWithoutLogger, string dataImplementILogger) { var data = string.Format(dataWithoutLogger, dataImplementILogger); var codeFixData = string.Format(codeFixDataWithoutLogger, dataImplementILogger); var expectedResult = new DiagnosticResult { Id = DiagnosticIds.PreventStaticLoggersRuleId, Message = string.Format(MessageFormat, declaringTypeName, selfType, interfaceName), Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", row, column) } }; VerifyCSharpDiagnostic(data, expectedResult); VerifyCSharpFix(data, codeFixData); } } }
70
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers.Test { public partial class PreventDateTimeNowUseAnalyzerTests { private const string BasicCorrectData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer { class Program { static void Main(string[] args) { var test = 1; } } }"; private const string BasicMethodData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ static void Main(string[] args) {{ var test = {0}; }} }} }}"; private const string BasicFieldData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ public DateTime test = {0}; static void Main(string[] args) {{ }} }} }}"; private const string BasicPassInParameterData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ static void Main(string[] args) {{ TestMethod({0}); }} public static void TestMethod(DateTime d) {{ }} }} }}"; private const string BasicPropertyData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ public DateTime test3 {{ get {{ return {0}; }} }} static void Main(string[] args) {{ }} }} }}"; private const string BasicLambdaData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ Func<DateTime, int, DateTime> testForEquality = (x, y) => {0}; static void Main(string[] args) {{ }} }} }}"; private const string BasicDelegateData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ public delegate DateTime DateFunc(); class Program {{ DateFunc dateFunc = delegate () {{ return {0}; }}; static void Main(string[] args) {{ }} }} }}"; private const string MethodCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] static void Main(string[] args) {{ var test = {0}; }} }} }}"; private const string FieldCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] public DateTime test = {0}; static void Main(string[] args) {{ }} }} }}"; private const string PassInParameterCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] static void Main(string[] args) {{ TestMethod({0}); }} public static void TestMethod(DateTime d) {{ }} }} }}"; private const string PropertyCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] public DateTime test3 {{ get {{ return {0}; }} }} static void Main(string[] args) {{ }} }} }}"; private const string LambdaCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] Func<DateTime, int, DateTime> testForEquality = (x, y) => {0}; static void Main(string[] args) {{ }} }} }}"; private const string DelegateCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ public delegate DateTime DateFunc(); class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1003"")] DateFunc dateFunc = delegate () {{ return {0}; }}; static void Main(string[] args) {{ }} }} }}"; private static List<string[]> MethodData => CreateSeperateData(BasicMethodData, MethodCodeFixData); private static List<string[]> FieldData => CreateSeperateData(BasicFieldData, FieldCodeFixData); private static List<string[]> PassInParameterData => CreateSeperateData(BasicPassInParameterData, PassInParameterCodeFixData); private static List<string[]> PropertyData => CreateSeperateData(BasicPropertyData, PropertyCodeFixData); private static List<string[]> LambdaData => CreateSeperateData(BasicLambdaData, LambdaCodeFixData); private static List<string[]> DelegateData => CreateSeperateData(BasicDelegateData, DelegateCodeFixData); public static IEnumerable<object[]> TestCorrectData => new List<string[]> { new string[] { BasicCorrectData } }; public static IEnumerable<object[]> TestMethodData => MethodData; public static IEnumerable<object[]> TestFieldData => FieldData; public static IEnumerable<object[]> TestPassInParameterData => PassInParameterData; public static IEnumerable<object[]> TestPropertyData => PropertyData; public static IEnumerable<object[]> TestLambdaData => LambdaData; public static IEnumerable<object[]> TestDelegateData => DelegateData; private static List<string[]> CreateSeperateData(string basicData, string codeFixData) { return new List<string[]> { new string[] { basicData, "DateTime.Now", codeFixData}, new string[] { basicData, "DateTime.Today", codeFixData}, new string[] { basicData, "DateTime.UtcNow", codeFixData} }; } } }
248
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers.Test { public partial class PreventHashAlgorithmCreateAnalyzerTests { private const string BasicCorrectData = @" using System; using System.Security.Cryptography; namespace TestPreventTimeNowUseAnalyzer { class Program { static void Main(string[] args) { var test = 1; } } }"; private const string BasicMethodData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ static void Main(string[] args) {{ var test = {0}; }} }} }}"; private const string BasicFieldData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ public HashAlgorithm test = {0}; static void Main(string[] args) {{ }} }} }}"; private const string BasicPropertyData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ public HashAlgorithm test4 {{ get {{ return {0}; }} }} static void Main(string[] args) {{ }} }} }}"; private const string BasicPassInParameterData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventHashAlgorithmCreateAnalyzer {{ class Program {{ static void Main(string[] args) {{ TestMethod({0}); }} public static void TestMethod(HashAlgorithm h) {{ }} }} }}"; private const string BasicLambdaData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ Func<int, int, HashAlgorithm> testForEquality = (x, y) => {0}; static void Main(string[] args) {{ }} }} }}"; private const string BasicDelegateData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ public delegate HashAlgorithm HashAlgorithmFunc(); class Program {{ HashAlgorithmFunc dateFunc = delegate () {{ return {0}; }}; static void Main(string[] args) {{ }} }} }}"; private const string MethodCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] static void Main(string[] args) {{ var test = {0}; }} }} }}"; private const string FieldCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] public HashAlgorithm test = {0}; static void Main(string[] args) {{ }} }} }}"; private const string PassInParameterCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventHashAlgorithmCreateAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] static void Main(string[] args) {{ TestMethod({0}); }} public static void TestMethod(HashAlgorithm h) {{ }} }} }}"; private const string PropertyCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] public HashAlgorithm test4 {{ get {{ return {0}; }} }} static void Main(string[] args) {{ }} }} }}"; private const string LambdaCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] Func<int, int, HashAlgorithm> testForEquality = (x, y) => {0}; static void Main(string[] args) {{ }} }} }}"; private const string DelegateCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventTimeNowUseAnalyzer {{ public delegate HashAlgorithm HashAlgorithmFunc(); class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1001"")] HashAlgorithmFunc dateFunc = delegate () {{ return {0}; }}; static void Main(string[] args) {{ }} }} }}"; public static IEnumerable<object[]> TestCorrectData => new List<string[]> { new string[] { BasicCorrectData } }; private static List<string[]> MethodData => CreateSeperateData(BasicMethodData, MethodCodeFixData); private static List<string[]> FieldData => CreateSeperateData(BasicFieldData, FieldCodeFixData); private static List<string[]> PassInParameterData => CreateSeperateData(BasicPassInParameterData, PassInParameterCodeFixData); private static List<string[]> PropertyData => CreateSeperateData(BasicPropertyData, PropertyCodeFixData); private static List<string[]> LambdaData => CreateSeperateData(BasicLambdaData, LambdaCodeFixData); private static List<string[]> DelegateData => CreateSeperateData(BasicDelegateData, DelegateCodeFixData); public static IEnumerable<object[]> TestMethodData => MethodData; public static IEnumerable<object[]> TestFieldData => FieldData; public static IEnumerable<object[]> TestPropertyData => PropertyData; public static IEnumerable<object[]> TestPassInParameterData => PassInParameterData; public static IEnumerable<object[]> TestLambdaData => LambdaData; public static IEnumerable<object[]> TestDelegateData => DelegateData; private static List<string[]> CreateSeperateData(string basicData, string codeFixData) { return new List<string[]> { new string[] { basicData, "HashAlgorithm.Create()", codeFixData}, new string[] { basicData, "HashAlgorithm.Create(\"test\")", codeFixData}, }; } } }
258
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers.Test { public partial class PreventMD5AnalyzerTests { private const string BasicFieldData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { public MD5 test; static void Main(string[] args) { } } }"; private const string BasicPropertyData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { public MD5 test2 { get; set; } static void Main(string[] args) { } } }"; private const string BasicInsideMethodData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { static void Main(string[] args) { var test = MD5.Create(); } } }"; private const string BasicDeclareMethodParameterData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { static void Main(string[] args) { } public void test3(MD5 m) { } } }"; private const string BasicPassInParameterToMethodData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { static void Main(string[] args) { test3(MD5.Create()); } public static void test3(object m) { } } }"; private const string BasicLamdaExpressionData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { Func<object> testFunc = () => MD5.Create(); static void Main(string[] args) { } } }"; private const string BasicDelegateData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { public delegate MD5 MD5Func(); class Program { MD5Func md5Func = delegate () { return MD5.Create(); }; static void Main(string[] args) { } } }"; private const string FieldCodeFixData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] public MD5 test; static void Main(string[] args) { } } }"; private const string PropertyCodeFixData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] public MD5 test2 { get; set; } static void Main(string[] args) { } } }"; private const string InsideMethodCodeFixData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] static void Main(string[] args) { var test = MD5.Create(); } } }"; private const string DeclareMethodParameterCodeFixData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { static void Main(string[] args) { } [SuppressMessage(""AWSSDKRules"", ""CR1000"")] public void test3(MD5 m) { } } }"; private const string PassInParameterToMethodCodeFixData = @" using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] static void Main(string[] args) { test3(MD5.Create()); } public static void test3(object m) { } } }"; private const string LambdaExpressionCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] Func<object> testFunc = () => MD5.Create(); static void Main(string[] args) { } } }"; private const string DelegateCodeFixData = @" using System; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; namespace TestPreventMD5UseAnalyzer { public delegate MD5 MD5Func(); class Program { [SuppressMessage(""AWSSDKRules"", ""CR1000"")] MD5Func md5Func = delegate () { return MD5.Create(); }; static void Main(string[] args) { } } }"; public static IEnumerable<object[]> TestInsideMethodData => CreateSeperateData(); private static List<object[]> CreateSeperateData() { return new List<object[]> { // Data for the field test new object[] {BasicFieldData, "System.Security.Cryptography.MD5", "Program", 9, 9, FieldCodeFixData}, // Data for the property test new object[] {BasicPropertyData, "System.Security.Cryptography.MD5", "Program", 9, 16, PropertyCodeFixData}, // Data for the inside method test new object[] {BasicInsideMethodData, "System.Security.Cryptography.MD5", "Main", 11, 24, InsideMethodCodeFixData}, // Data for the declare method parameter new object[] { BasicDeclareMethodParameterData, "System.Security.Cryptography.MD5", "test3", 12, 27, DeclareMethodParameterCodeFixData}, // Data for the pass in parameter to method new object[] { BasicPassInParameterToMethodData, "System.Security.Cryptography.MD5", "Main", 11, 19, PassInParameterToMethodCodeFixData}, // Data for the Lambda Expression new object[] { BasicLamdaExpressionData, "System.Security.Cryptography.MD5", "Program", 10, 39, LambdaExpressionCodeFixData}, // Data for the Delegate new object[] { BasicDelegateData, "System.Security.Cryptography.MD5", "Program", 11, 48, DelegateCodeFixData} }; } } }
255
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers.Test { public partial class PreventRegionEndpointUseAnalyzerTests { private const string BasicFieldData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { public RegionEndpoint test4 = RegionEndpoint.USEast1; static void Main(string[] args) { } } }"; private const string BasicPropertyData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { public RegionEndpoint Test6 { get { return RegionEndpoint.USEast1; } set { } } } }"; private const string BasicInsideMethodData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { static void Main(string[] args) { var test2 = RegionEndpoint.USEast1; } } }"; private const string BasicPassInParameterToMethodData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { static void Main(string[] args) { test(RegionEndpoint.USEast1); } static void test(RegionEndpoint usEast1) { } } }"; private const string BasicLambdaData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { public Func<RegionEndpoint> test = () => RegionEndpoint.USEast1; static void Main(string[] args) { } } }"; private const string BasicDelegateData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { delegate RegionEndpoint RegionEndpointFunc(); class Program { RegionEndpointFunc regionEndpointFunc = delegate () { return RegionEndpoint.USEast1; }; static void Main(string[] args) { } } }"; private const string BasicWithoutUSEast1Data = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { public static readonly RegionEndpoint test4 = RegionEndpoint.USWest1; static void Main(string[] args) { } } }"; private const string FieldCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] public RegionEndpoint test4 = RegionEndpoint.USEast1; static void Main(string[] args) { } } }"; private const string PropertyCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] public RegionEndpoint Test6 { get { return RegionEndpoint.USEast1; } set { } } } }"; private const string InsideMethodCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] static void Main(string[] args) { var test2 = RegionEndpoint.USEast1; } } }"; private const string PassInParameterToMethodCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] static void Main(string[] args) { test(RegionEndpoint.USEast1); } static void test(RegionEndpoint usEast1) { } } }"; private const string LambdaCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] public Func<RegionEndpoint> test = () => RegionEndpoint.USEast1; static void Main(string[] args) { } } }"; private const string DelegateCodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { delegate RegionEndpoint RegionEndpointFunc(); class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] RegionEndpointFunc regionEndpointFunc = delegate () { return RegionEndpoint.USEast1; }; static void Main(string[] args) { } } }"; private const string WithoutUSEast1CodeFixData = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon; namespace TestPreventRegionEndPointUseAnalyzer { class Program { [SuppressMessage(""AWSSDKRules"", ""CR1004"")] public static readonly RegionEndpoint test4 = RegionEndpoint.USWest1; static void Main(string[] args) { } } }"; public static IEnumerable<object[]> TestInsideMethodData => CreateSeperateData(); private static List<object[]> CreateSeperateData() { return new List<object[]> { // Data for the field test new object[] {BasicFieldData, 10, 39, FieldCodeFixData}, // Data for the property test new object[] {BasicPropertyData, 12, 26, PropertyCodeFixData}, // Data for the inside method test new object[] {BasicInsideMethodData, 12, 25, InsideMethodCodeFixData}, // Data for the pass in parameter to method new object[] { BasicPassInParameterToMethodData, 12, 18, PassInParameterToMethodCodeFixData}, // Data for the Lambda Expression new object[] { BasicLambdaData, 10, 50, LambdaCodeFixData}, // Data for the Delegate new object[] {BasicDelegateData, 11, 70, DelegateCodeFixData}, // Data for the use of USWest1 not USEast1 new object[] {BasicWithoutUSEast1Data, 10, 55, WithoutUSEast1CodeFixData} }; } } }
262
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace CustomRoslynAnalyzers.Test { public partial class PreventStaticLoggersAnalyzerTests { private const string BasicDataForImplementILogger = @" public class Logger : ILogger { public void Debug(Exception exception, string messageFormat, params object[] args) { return; } public void DebugFormat(string messageFormat, params object[] args) { return; } public void Error(Exception exception, string messageFormat, params object[] args) { return; } public void Flush() { return; } public void InfoFormat(string messageFormat, params object[] args) { return; } }"; private const string BasicFieldDataWithoutLogger = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon.Runtime.Internal.Util; namespace TestPreventStaticLoggersAnalyzer {{ class Program {{ public static Logger B; static void Main(string[] args) {{ }} }} {0} }}"; private const string BasicPropertyDataWithoutLogger = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon.Runtime.Internal.Util; namespace TestPreventStaticLoggersAnalyzer {{ class Program {{ public static Logger A {{ set; get; }} static void Main(string[] args) {{ }} }} {0} }}"; private const string FieldCodeFixDataWithoutLogger = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon.Runtime.Internal.Util; namespace TestPreventStaticLoggersAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1002"")] public static Logger B; static void Main(string[] args) {{ }} }} {0} }}"; private const string PropertyCodeFixDataWithoutLogger = @" using System; using System.Diagnostics.CodeAnalysis; using Amazon.Runtime.Internal.Util; namespace TestPreventStaticLoggersAnalyzer {{ class Program {{ [SuppressMessage(""AWSSDKRules"", ""CR1002"")] public static Logger A {{ set; get; }} static void Main(string[] args) {{ }} }} {0} }}"; public static IEnumerable<object[]> AllTestData => CreateSeperateData(); private static List<object[]> CreateSeperateData() { return new List<object[]> { // Data for the field test new object[] { BasicFieldDataWithoutLogger, "Program", "TestPreventStaticLoggersAnalyzer.Logger", "ILogger", 10, 9, FieldCodeFixDataWithoutLogger, BasicDataForImplementILogger}, // Data for the property test new object[] { BasicPropertyDataWithoutLogger, "Program", "TestPreventStaticLoggersAnalyzer.Logger", "ILogger", 10, 9, PropertyCodeFixDataWithoutLogger, BasicDataForImplementILogger}, }; } } }
120
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using System.Collections.Generic; using System.Linq; using System.Threading; /// <summary> /// The Code under this class is generated by Visual Studio /// </summary> namespace CustomRoslynAnalyzers.Test.TestHelper { /// <summary> /// Diagnostic Producer class with extra methods dealing with applying codefixes /// All methods are static /// </summary> public abstract partial class CodeFixVerifier : DiagnosticVerifier { /// <summary> /// Apply the inputted CodeAction to the inputted document. /// Meant to be used to apply codefixes. /// </summary> /// <param name="document">The Document to apply the fix on</param> /// <param name="codeAction">A CodeAction that will be applied to the Document.</param> /// <returns>A Document with the changes from the CodeAction</returns> private static Document ApplyFix(Document document, CodeAction codeAction) { var operations = codeAction.GetOperationsAsync(CancellationToken.None).Result; var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution; return solution.GetDocument(document.Id); } /// <summary> /// Compare two collections of Diagnostics,and return a list of any new diagnostics that appear only in the second collection. /// Note: Considers Diagnostics to be the same if they have the same Ids. In the case of multiple diagnostics with the same Id in a row, /// this method may not necessarily return the new one. /// </summary> /// <param name="diagnostics">The Diagnostics that existed in the code before the CodeFix was applied</param> /// <param name="newDiagnostics">The Diagnostics that exist in the code after the CodeFix was applied</param> /// <returns>A list of Diagnostics that only surfaced in the code after the CodeFix was applied</returns> private static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics) { var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); int oldIndex = 0; int newIndex = 0; while (newIndex < newArray.Length) { if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id) { ++oldIndex; ++newIndex; } else { yield return newArray[newIndex++]; } } } /// <summary> /// Get the existing compiler diagnostics on the inputted document. /// </summary> /// <param name="document">The Document to run the compiler diagnostic analyzers on</param> /// <returns>The compiler diagnostics that were found in the code</returns> private static IEnumerable<Diagnostic> GetCompilerDiagnostics(Document document) { return document.GetSemanticModelAsync().Result.GetDiagnostics(); } /// <summary> /// Given a document, turn it into a string based on the syntax root /// </summary> /// <param name="document">The Document to be converted to a string</param> /// <returns>A string containing the syntax of the Document after formatting</returns> private static string GetStringFromDocument(Document document) { var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result; var root = simplifiedDoc.GetSyntaxRootAsync().Result; root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return root.GetText().ToString(); } } }
89
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using System; /// <summary> /// The Code under this class is generated by Visual Studio /// </summary> namespace CustomRoslynAnalyzers.Test.TestHelper { /// <summary> /// Location where the diagnostic appears, as determined by path, line number, and column number. /// </summary> public struct DiagnosticResultLocation { public DiagnosticResultLocation(string path, int line, int column) { if (line < -1) { throw new ArgumentOutOfRangeException(nameof(line), "line must be >= -1"); } if (column < -1) { throw new ArgumentOutOfRangeException(nameof(column), "column must be >= -1"); } this.Path = path; this.Line = line; this.Column = column; } public string Path { get; } public int Line { get; } public int Column { get; } } /// <summary> /// Struct that stores information about a Diagnostic appearing in a source /// </summary> public struct DiagnosticResult { private DiagnosticResultLocation[] locations; public DiagnosticResultLocation[] Locations { get { if (this.locations == null) { this.locations = new DiagnosticResultLocation[] { }; } return this.locations; } set { this.locations = value; } } public DiagnosticSeverity Severity { get; set; } public string Id { get; set; } public string Message { get; set; } public string Path { get { return this.Locations.Length > 0 ? this.Locations[0].Path : ""; } } public int Line { get { return this.Locations.Length > 0 ? this.Locations[0].Line : -1; } } public int Column { get { return this.Locations.Length > 0 ? this.Locations[0].Column : -1; } } } }
91
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using System; using System.Runtime; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Cryptography; using System.Reflection; /// <summary> /// The Code under this class is generated by Visual Studio /// </summary> namespace CustomRoslynAnalyzers.Test.TestHelper { /// <summary> /// Class for turning strings into documents and getting the diagnostics on them /// All methods are static /// </summary> public abstract partial class DiagnosticVerifier { private static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); private static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location); private static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location); private static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location); private static readonly MetadataReference HashAlgorithmReference = MetadataReference.CreateFromFile(typeof(HashAlgorithm).Assembly.Location); private static readonly MetadataReference MD5Reference = MetadataReference.CreateFromFile(typeof(MD5).Assembly.Location); private static readonly MetadataReference RunTimeReference = MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").Location); private static readonly MetadataReference NetStandardReference = MetadataReference.CreateFromFile(Assembly.Load("System.Runtime, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location); #if DEBUG private static readonly MetadataReference AmazonReference = MetadataReference.CreateFromFile("..\\..\\..\\..\\..\\..\\sdk\\src\\Core\\bin\\Debug\\netstandard2.0\\AWSSDK.Core.dll"); #else private static readonly MetadataReference AmazonReference = MetadataReference.CreateFromFile("..\\..\\..\\..\\..\\..\\sdk\\src\\Core\\bin\\Release\\netstandard2.0\\AWSSDK.Core.dll"); #endif internal static string DefaultFilePathPrefix = "Test"; internal static string CSharpDefaultFileExt = "cs"; internal static string VisualBasicDefaultExt = "vb"; internal static string TestProjectName = "TestProject"; #region Get Diagnostics /// <summary> /// Given classes in the form of strings, their language, and an IDiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source classes are in</param> /// <param name="analyzer">The analyzer to be run on the sources</param> /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns> private static Diagnostic[] GetSortedDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer) { return GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language)); } /// <summary> /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it. /// The returned diagnostics are then ordered by location in the source document. /// </summary> /// <param name="analyzer">The analyzer to run on the documents</param> /// <param name="documents">The Documents that the analyzer will be run on</param> /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns> protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents) { var projects = new HashSet<Project>(); foreach (var document in documents) { projects.Add(document.Project); } var diagnostics = new List<Diagnostic>(); foreach (var project in projects) { var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer)); var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; foreach (var diag in diags) { if (diag.Location == Location.None || diag.Location.IsInMetadata) { diagnostics.Add(diag); } else { for (int i = 0; i < documents.Length; i++) { var document = documents[i]; var tree = document.GetSyntaxTreeAsync().Result; if (tree == diag.Location.SourceTree) { diagnostics.Add(diag); } } } } } var results = SortDiagnostics(diagnostics); diagnostics.Clear(); return results; } /// <summary> /// Sort diagnostics by location in source document /// </summary> /// <param name="diagnostics">The list of Diagnostics to be sorted</param> /// <returns>An IEnumerable containing the Diagnostics in order of Location</returns> private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics) { return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); } #endregion #region Set up compilation and documents /// <summary> /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns> private static Document[] GetDocuments(string[] sources, string language) { if (language != LanguageNames.CSharp) { throw new ArgumentException("Unsupported Language"); } var project = CreateProject(sources, language); var documents = project.Documents.ToArray(); if (sources.Length != documents.Length) { throw new InvalidOperationException("Amount of sources did not match amount of Documents created"); } return documents; } /// <summary> /// Create a Document from a string through creating a project that contains it. /// </summary> /// <param name="source">Classes in the form of a string</param> /// <param name="language">The language the source code is in</param> /// <returns>A Document created from the source string</returns> protected static Document CreateDocument(string source, string language = LanguageNames.CSharp) { return CreateProject(new[] { source }, language).Documents.First(); } /// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference) .AddMetadataReference(projectId, HashAlgorithmReference) .AddMetadataReference(projectId, RunTimeReference) .AddMetadataReference(projectId, MD5Reference) .AddMetadataReference(projectId, AmazonReference) .AddMetadataReference(projectId, NetStandardReference); int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return solution.GetProject(projectId); } #endregion } }
191
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; using System.Threading; /// <summary> /// The Code under this class is generated by Visual Studio /// </summary> namespace CustomRoslynAnalyzers.Test.TestHelper { /// <summary> /// Superclass of all Unit tests made for diagnostics with codefixes. /// Contains methods used to verify correctness of codefixes /// </summary> public abstract partial class CodeFixVerifier : DiagnosticVerifier { /// <summary> /// Returns the codefix being tested (C#) - to be implemented in non-abstract class /// </summary> /// <returns>The CodeFixProvider to be used for CSharp code</returns> protected virtual CodeFixProvider GetCSharpCodeFixProvider() { return null; } /// <summary> /// Returns the codefix being tested (VB) - to be implemented in non-abstract class /// </summary> /// <returns>The CodeFixProvider to be used for VisualBasic code</returns> protected virtual CodeFixProvider GetBasicCodeFixProvider() { return null; } /// <summary> /// Called to test a C# codefix when applied on the inputted string as a source /// </summary> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> protected void VerifyCSharpFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) { VerifyFix(LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), GetCSharpCodeFixProvider(), oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics); } /// <summary> /// Called to test a VB codefix when applied on the inputted string as a source /// </summary> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> protected void VerifyBasicFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) { VerifyFix(LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), GetBasicCodeFixProvider(), oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics); } /// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> private void VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics) { var document = CreateDocument(oldSource, language); var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var compilerDiagnostics = GetCompilerDiagnostics(document); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List<CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = ApplyFix(document, actions.ElementAt((int)codeFixIndex)); break; } document = ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); Assert.IsTrue(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), document.GetSyntaxRootAsync().Result.ToFullString())); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = GetStringFromDocument(document); Assert.AreEqual(newSource, actual); } } }
132
aws-sdk-net
aws
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// The Code under this class is generated by Visual Studio /// </summary> namespace CustomRoslynAnalyzers.Test.TestHelper { /// <summary> /// Superclass of all Unit Tests for DiagnosticAnalyzers /// </summary> public abstract partial class DiagnosticVerifier { #region To be implemented by Test classes /// <summary> /// Get the CSharp analyzer being tested - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return null; } /// <summary> /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return null; } #endregion #region Verifier wrappers /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run, /// then verifies each of them. /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="language">The language of the classes represented by the source strings</param> /// <param name="analyzer">The analyzer to be run on the source code</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected) { var diagnostics = GetSortedDiagnostics(sources, language, analyzer); VerifyDiagnosticResults(diagnostics, analyzer, expected); } #endregion #region Actual comparisons and verifications /// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { int expectedCount = expectedResults.Length; int actualCount = actualResults.Count(); if (expectedCount != actualCount) { string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.IsTrue(false, string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput)); } for (int i = 0; i < expectedResults.Length; i++) { var actual = actualResults.ElementAt(i); var expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) { Assert.IsTrue(false, string.Format("Expected:\r\nA project diagnostic with No location\r\nActual:\r\n{0}", FormatDiagnostics(analyzer, actual))); } } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); var additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) { Assert.IsTrue(false, string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n", expected.Locations.Length - 1, additionalLocations.Length, FormatDiagnostics(analyzer, actual))); } for (int j = 0; j < additionalLocations.Length; ++j) { VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } } if (actual.Id != expected.Id) { Assert.IsTrue(false, string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Id, actual.Id, FormatDiagnostics(analyzer, actual))); } if (actual.Severity != expected.Severity) { Assert.IsTrue(false, string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual))); } if (actual.GetMessage() != expected.Message) { Assert.IsTrue(false, string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual))); } } } /// <summary> /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult. /// </summary> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="diagnostic">The diagnostic that was found in the code</param> /// <param name="actual">The Location of the Diagnostic found in the code</param> /// <param name="expected">The DiagnosticResultLocation that should have been found</param> private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) { var actualSpan = actual.GetLineSpan(); Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")), string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic))); var actualLinePosition = actualSpan.StartLinePosition; // Only check line position if there is an actual line in the real diagnostic if (actualLinePosition.Line > 0) { if (actualLinePosition.Line + 1 != expected.Line) { Assert.IsTrue(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } } // Only check column position if there is an actual column position in the real diagnostic if (actualLinePosition.Character > 0) { if (actualLinePosition.Character + 1 != expected.Column) { Assert.IsTrue(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } } } #endregion #region Formatting Diagnostics /// <summary> /// Helper method to format a Diagnostic into an easily readable string /// </summary> /// <param name="analyzer">The analyzer that this verifier tests</param> /// <param name="diagnostics">The Diagnostics to be formatted</param> /// <returns>The Diagnostics formatted as a string</returns> private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics) { var builder = new StringBuilder(); for (int i = 0; i < diagnostics.Length; ++i) { builder.AppendLine("// " + diagnostics[i].ToString()); var analyzerType = analyzer.GetType(); var rules = analyzer.SupportedDiagnostics; foreach (var rule in rules) { if (rule != null && rule.Id == diagnostics[i].Id) { var location = diagnostics[i].Location; if (location == Location.None) { builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id); } else { Assert.IsTrue(location.IsInSource, $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n"); string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt"; var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition; builder.AppendFormat("{0}({1}, {2}, {3}.{4})", resultMethodName, linePosition.Line + 1, linePosition.Character + 1, analyzerType.Name, rule.Id); } if (i != diagnostics.Length - 1) { builder.Append(','); } builder.AppendLine(); break; } } } return builder.ToString(); } #endregion } }
274
aws-sdk-net
aws
C#
using System; using Microsoft.Build.Utilities; using System.Diagnostics; using System.Threading; namespace CustomTasks { public abstract class BuildTaskBase : Task { public bool WaitForDebugger { get; set; } public int MaxAttempts { get; set; } public BuildTaskBase() { WaitForDebugger = false; MaxAttempts = 10; } protected void CheckWaitForDebugger() { if (WaitForDebugger) { Log.LogMessage("MSBuild process id: {0}", Process.GetCurrentProcess().Id); Log.LogMessage("Waiting for debugger to be attached"); while (!Debugger.IsAttached) { Thread.Sleep(TimeSpan.FromSeconds(1)); } Debugger.Break(); } } public override bool Execute() { if (MaxAttempts <= 0) throw new ArgumentOutOfRangeException("MaxAttempts"); CheckWaitForDebugger(); for (int i = 0; i < MaxAttempts; i++) { try { var result = RetriableExecute(); if (result) return true; } catch (Exception e) { Log.LogWarning("Failed attempt {0}: {1}", (i + 1), e); } } Log.LogError("Attempted task {0} times without success", MaxAttempts); return false; } protected virtual bool RetriableExecute() { return true; } } }
64
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Framework; using System.IO; using Newtonsoft.Json; namespace CustomTasks { public class PlaceModelTask : BuildTaskBase { public const string METADATA_JSON = "metadata.json"; public const string SERVICE_MODEL_PATH = "generator\\ServiceModels"; public string SDKRepoPath { get; set; } public string ModelPath { get; set; } public string ServicePrefix { get; set; } [Output] public string BaseName { get; set; } public PlaceModelTask() { WaitForDebugger = true; } public override bool Execute() { string apiVersion = GetAPIVersion(ModelPath); string c2jFileName = string.Format("{0}-{1}.normal.json", ServicePrefix, apiVersion); string serviceModelDirectory = Path.Combine(SDKRepoPath, SERVICE_MODEL_PATH, ServicePrefix); if (!Directory.Exists(serviceModelDirectory)) { Directory.CreateDirectory(serviceModelDirectory); } File.Copy(ModelPath, Path.Combine(serviceModelDirectory, c2jFileName), /* overwrite = */ true); BaseName = GetBaseName(serviceModelDirectory, c2jFileName); return true; } private string GetAPIVersion(string modelPath) { C2JModel c2jModel = JsonConvert.DeserializeObject<C2JModel>( File.ReadAllText(modelPath)); C2JMetadata metadata = c2jModel.Metadata; return metadata.APIVersion; } private string GetBaseName(string directory, string modelName) { string baseName = ""; try { var metadatapath = Path.Combine(directory, METADATA_JSON); Metadata metadatajson = new Metadata(); if (File.Exists(metadatapath)) { metadatajson = JsonConvert.DeserializeObject<Metadata>( File.ReadAllText(metadatapath)); } else { metadatajson.Active = true; metadatajson.Synopsis = "Generated from self-service"; File.WriteAllText(metadatapath, JsonConvert.SerializeObject(metadatajson)); } baseName = metadatajson.BaseName; } catch {}; if (string.IsNullOrEmpty(baseName)) { C2JModel c2jModel = JsonConvert.DeserializeObject<C2JModel>( File.ReadAllText(Path.Combine(directory, modelName))); C2JMetadata metadata = c2jModel.Metadata; if (!string.IsNullOrEmpty(metadata.ServiceAbbreviation)) { baseName = SanitizeStringForClassName(metadata.ServiceAbbreviation); } else if (!string.IsNullOrEmpty(metadata.ServiceFullName)) { baseName = SanitizeStringForClassName(metadata.ServiceFullName); } } return baseName; } private static string SanitizeStringForClassName(string name) { string className = name; className = className.Replace("AWS", ""); className = className.Replace("Amazon", ""); // concatenate all the words by removing whitespace. className = System.Text.RegularExpressions.Regex.Replace(className, @"[^a-zA-Z0-9]", ""); return className; } private class Metadata { [JsonProperty("active")] public bool Active { get; set; } [JsonProperty("base-name")] public string BaseName { get; set; } [JsonProperty("synopsis")] public string Synopsis { get; set; } } private class C2JMetadata { [JsonProperty("serviceAbbreviation")] public string ServiceAbbreviation { get; set; } [JsonProperty("serviceFullName")] public string ServiceFullName { get; set; } [JsonProperty("apiVersion")] public string APIVersion { get; set; } } private class C2JModel { [JsonProperty("metadata")] public C2JMetadata Metadata { get; set; } } } }
144
aws-sdk-net
aws
C#
using System; using System.Threading; namespace CustomTasks { public class TimingTask : BuildTaskBase { private readonly static TimeSpan SleepTime = TimeSpan.FromSeconds(30); private static bool ShouldInit = true; private static Thread MainThread = null; private static DateTime StartTime; public override bool Execute() { if (ShouldInit) { ShouldInit = false; StartTime = DateTime.Now; MainThread = new Thread(() => { try { while (true) { var elapsed = DateTime.Now - StartTime; Console.WriteLine(">>>>> ELAPSED TIME = " + elapsed.ToString("h'h 'm'm 's's'")); Thread.Sleep(SleepTime); } } catch(Exception e) { Console.WriteLine("TimingTask encountered error: " + e); } }); MainThread.IsBackground = true; MainThread.Start(); } return true; } } }
43
aws-sdk-net
aws
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; namespace CustomTasks.Endpoint { /// <summary> /// Implementation of a IEndpointOverrider /// Endpoint overrider: will override the endpoints.json file and remove/add endpoints /// Based on a json input file for addition and removal /// </summary> public class EndpointOverrider : IEndpointOverrider { private readonly IFileSystem _fs; public EndpointOverrider() : this(new FileSystem()) { } public EndpointOverrider(IFileSystem fs) { _fs = fs; } /// <summary> /// Applies overrides to an endpoints.json file /// </summary> /// <param name="endpointsJsonSourceFilePath">The endpoints-original.json source location</param> /// <param name="endpointsOverrideFilePath">The path to the endpoints override json file</param> /// <returns>String: the new endpoints.json input text.</returns> public string ApplyOverrides(string endpointsJsonSourceFilePath, string endpointsOverrideFilePath) { // Retrieve the current endpoints-original.json file string input = _fs.ReadAllText(endpointsJsonSourceFilePath); JObject endpointsData = JObject.Parse(input); // Retrieve the endpoints-override.json file string overrideJson = _fs.ReadAllText(endpointsOverrideFilePath); if (!string.IsNullOrWhiteSpace(overrideJson)) { JObject configuration = JObject.Parse(overrideJson); if (configuration != null) { foreach (var service in configuration.Children()) { var servicePrefix = service.Path; JToken serviceNode = endpointsData["partitions"][0]["services"][servicePrefix]; if (serviceNode != null) { JObject endpointsNode = serviceNode["endpoints"] as JObject; var endpointsToRemove = configuration.SelectTokens($"{servicePrefix}.remove"); foreach (var endpointToRemove in endpointsToRemove.Children()) { endpointsNode.Remove(endpointToRemove.ToObject<string>()); } var endpointsToAdd = configuration.SelectTokens($"{servicePrefix}.add"); foreach (var endpointToAdd in endpointsToAdd.Children()) { // We can not have two properties with the same name var endpointProperty = endpointToAdd as JProperty; var exists = endpointsNode.Properties().ToList().Exists(p => p.Name == endpointProperty.Name); if (!exists) { endpointsNode.Add(endpointToAdd); } else { throw new InvalidOperationException($"The endpoint {endpointProperty.Name} already exists for service {servicePrefix}"); } } } else { throw new InvalidOperationException($"The service {servicePrefix} does not exist in the endpoints.json file"); } } } } var targetPath = Path.Combine(Path.GetDirectoryName(endpointsJsonSourceFilePath), "endpoints.json"); string output = JsonConvert.SerializeObject(endpointsData, Formatting.Indented); _fs.WriteAllText(targetPath, output); return output; } } }
90
aws-sdk-net
aws
C#
using System; using System.IO; namespace CustomTasks.Endpoint { public class EndpointOverriderTask : BuildTaskBase { public string EndpointsJsonSourceLocation { get; set; } public string EndpointsOverrideLocation { get; set; } public override bool Execute() { if (!File.Exists(EndpointsJsonSourceLocation)) throw new ArgumentException("Unable to find the endpoints-original.json file.", nameof(EndpointsJsonSourceLocation)); // We only want to do it on endpoints-original.json files. if (Path.GetFileName(EndpointsJsonSourceLocation) != "endpoints-original.json") throw new ArgumentException("The specified file is not an endpoints-original.json file.", nameof(EndpointsJsonSourceLocation)); var overrider = new EndpointOverrider(); overrider.ApplyOverrides(EndpointsJsonSourceLocation, EndpointsOverrideLocation); return true; } } }
26
aws-sdk-net
aws
C#
namespace CustomTasks.Endpoint { /// <summary> /// Implementation of a file system layer using System.IO /// </summary> public class FileSystem : IFileSystem { public string ReadAllText(string path) { return System.IO.File.ReadAllText(path); } public void WriteAllText(string path, string contents) { System.IO.File.WriteAllText(path, contents); } public void Copy(string sourceFileName, string destFileName, bool overwrite) { System.IO.File.Copy(sourceFileName, destFileName, overwrite); } } }
24
aws-sdk-net
aws
C#
namespace CustomTasks.Endpoint { /// <summary> /// Endpoint overrider: will override the endpoints.json file and remove/add endpoints /// Based on a json input file for addition and removal /// </summary> interface IEndpointOverrider { /// <summary> /// Applies overrides to an endpoints.json file /// </summary> /// <param name="endpointsJsonSourceFilePath">The endpoints.json source location</param> /// <param name="endpointsOverrideFilePath">The path to the endpoints override json file</param> /// <returns>String: the new endpoints.json input text.</returns> string ApplyOverrides(string endpointsJsonSourceFilePath, string endpointsOverrideFilePath); } }
18
aws-sdk-net
aws
C#
namespace CustomTasks.Endpoint { /// <summary> /// Abstraction layer to a file system. /// </summary> public interface IFileSystem { string ReadAllText(string path); void WriteAllText(string path, string contents); void Copy(string sourceFileName, string destFileName, bool overwrite); } }
15
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CustomTasks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomTasks")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cf793704-9436-41b2-8a59-fc90e70e13da")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using Moq; using NUnit.Framework; using System; namespace CustomTasks.Endpoint.Test { public class EndpointOverriderTests { private const string BaseContentPath = "../../../Content"; private readonly string ENDPOINT_SOURCE = $"{BaseContentPath}/endpoints-source.json"; [Test] public void GivenARegularEndpointsJsonFile_WhenAnEndpointIsModifiedAndAPseudoRegionIsCreated_ThenTheEndpointsJsonFileIsCorrect() { var target = $"{BaseContentPath}/endpoints-target.json"; var configuration = $"{BaseContentPath}/endpoints-override-us-east-1-regional.json"; var fs = new Mock<IFileSystem>(); var overrider = GetEndpointOverriderMock(ENDPOINT_SOURCE, configuration, fs); fs.Setup(f => f.WriteAllText(It.IsAny<string>(), It.IsAny<string>())).Verifiable(); var output = overrider.ApplyOverrides(ENDPOINT_SOURCE, configuration); Assert.AreEqual(System.IO.File.ReadAllText(target), output); fs.Verify(); } [Test] public void GivenARegularEndpointsJsonFile_WhenTheModificationRulesFileIsEmpty_ThenTheEndpointsJsonFileIsNotTouched() { var target = $"{BaseContentPath}/endpoints-source.json"; var configuration = $"{BaseContentPath}/endpoints-override-empty-file.json"; var fs = new Mock<IFileSystem>(); var overrider = GetEndpointOverriderMock(ENDPOINT_SOURCE, configuration, fs); var output = overrider.ApplyOverrides(ENDPOINT_SOURCE, configuration); Assert.AreEqual(System.IO.File.ReadAllText(target), output); fs.Verify(); } [Test] public void GivenARegularEndpointsJsonFile_WhenTheModificationFileIsNotEmptyButDoesNotContainsChanges_ThenTheEndpointsJsonFileIsNotTouched() { var target = $"{BaseContentPath}/endpoints-source.json"; var configuration = $"{BaseContentPath}/endpoints-override-empty-nodes-exists.json"; var fs = new Mock<IFileSystem>(); var overrider = GetEndpointOverriderMock(ENDPOINT_SOURCE, configuration, fs); var output = overrider.ApplyOverrides(ENDPOINT_SOURCE, configuration); Assert.AreEqual(System.IO.File.ReadAllText(target), output); fs.Verify(); } [Test] public void GivenARegularEndpointsJsonFile_WhenTheModificationRulesContainAWrongService_ThenAnInvalidOperationExceptionIsThrown() { var configuration = $"{BaseContentPath}/endpoints-override-add-unknown-service.json"; var fs = new Mock<IFileSystem>(); var overrider = GetEndpointOverriderMock(ENDPOINT_SOURCE, configuration, fs); Assert.Throws<InvalidOperationException>(() => overrider.ApplyOverrides(ENDPOINT_SOURCE, configuration)); fs.Verify(); } [Test] public void GivenARegularEndpointsJsonFile_WhenTheModificationRulesContainADuplicateEndpoint_ThenTheEndpointsJsonFileIsCorrect() { var configuration = $"{BaseContentPath}/endpoints-override-add-duplicate.json"; var fs = new Mock<IFileSystem>(); var overrider = GetEndpointOverriderMock(ENDPOINT_SOURCE, configuration, fs); Assert.Throws<InvalidOperationException>(() => overrider.ApplyOverrides(ENDPOINT_SOURCE, configuration)); fs.Verify(); } private EndpointOverrider GetEndpointOverriderMock(string source, string configuration, Mock<IFileSystem> fs) { var content = System.IO.File.ReadAllText(source); fs.Setup(f => f.ReadAllText(source)).Returns(content).Verifiable(); content = System.IO.File.ReadAllText(configuration); fs.Setup(f => f.ReadAllText(configuration)).Returns(content).Verifiable(); var overrider = new EndpointOverrider(fs.Object); return overrider; } } }
82
aws-sdk-net
aws
C#
using System; using NUnit.Framework; namespace TestCases { public class RandomFailureTests { private static readonly Random random = new Random(); private static readonly int FREQUENCY = 25; private const string SAMPLE_S3_MULTILINE_STRING = "B;chunk-signature=6a4d50a3307c001ad83900a73442136a0a0f203520fd8c0e966f655cc830bbe8\r\n" + "Hello world\r\n" + "0;chunk-signature=9384094dc67fd7c29a4c7e0aa3866233b3774e41d1470b8f51a96becbd91f60c\r\n" + "x-amz-checksum-sha1:e1AsOh9IyGCa4hLN+2Od7jlnP14=\r\n" + "x-amz-trailer-signature:5e9fae6e80d8cb558e2c43d228a8c36d6b36b5f6f8b86fb8f6596111f3f229a1\r\n" + "\r\n"; [Test] public void TestMethod01() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod02() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod03() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod04() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod05() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod06() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod07() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod08() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod09() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod10() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod11() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod12() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod13() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod14() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod15() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod16() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod17() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod18() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod19() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod20() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod21() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod22() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod23() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod24() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [Test] public void TestMethod25() { Assert.IsFalse(random.Next(100) < FREQUENCY); } [TestCase(SAMPLE_S3_MULTILINE_STRING)] [TestCase("another multiline\r\n string\r\n")] public void TestMethod26(string input) { Assert.IsTrue(input.Contains("\r\n")); Assert.IsFalse(random.Next(100) < FREQUENCY); } } }
178
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DummyMSTestCases")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DummyMSTestCases")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd0d6108-36d5-42a7-a3d0-b428c87395c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using NUnit.Framework; namespace TestCases { public class MismatchTest { [Test] public void SignatureMismatch() { throw new Exception("The request signature we calculated does not match the signature you provided."); } } }
16
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DummyNoRetryTestCases")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DummyNoRetryTestCases")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4DCAF40E-5A86-427F-A0ED-9847585BF83A")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using Xunit; namespace DummyXUnitTestCases { public class TestCases { private int Add(int a, int b) { return a + b; } [Fact] public void PassingTest() { Assert.True(4 == Add(2, 2)); } [Fact] public void FailingTest() { Assert.True(3 == Add(2, 2)); } private bool Odd(int val) { return val % 2 != 0; } [Theory] [InlineData(3)] [InlineData(5)] [InlineData(7)] [InlineData(9)] public void SucceedingTheory(int val) { Assert.True(Odd(val)); } [Theory] [InlineData(3)] [InlineData(4)] [InlineData(7)] [InlineData(9)] public void FailingTheory(int val) { Assert.True(Odd(val)); } [Fact(Skip = "Skipped Test")] public void TestSkip() { throw new Exception("This should have been skipped!"); } } }
58
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DummyXUnitTestCases")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DummyXUnitTestCases")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e63d3373-8d72-47bc-b9a7-46879b877d86")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TestWrapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestWrapper")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3d1058ab-4434-4d97-8dae-b9d47069454d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TestWrapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestWrapper")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3c64655b-6e7b-4938-ab2e-cd80b3b73b83")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Linq; using TestWrapper.TestRunners; using System.IO; namespace TestWrapper { public class MSTestRunner : TestRunner { public MSTestRunner(string testSuiteExecutable, FileInfo testContainer, DirectoryInfo workingDirectory) : base(testSuiteExecutable, testContainer, workingDirectory: null) { } } }
20
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; namespace TestWrapper { public class ResultsSummary { public readonly static IList<string> NO_RETRYABLE_STRINGS = new List<string> { "The request signature we calculated does not match the signature you provided." }; public ResultsSummary( int exitCode, IList<string> failedTests, int passed, int failed, int skipped, bool containsNoRetryableTests) { this.ExitCode = exitCode; this.FailedTestNames = failedTests; this.Passed = passed; this.Failed = failed; this.Skipped = skipped; this.ContainsNoRetryableTests = containsNoRetryableTests; } public IList<string> FailedTestNames { get; private set; } public int Passed { get; private set; } public int Failed { get; private set; } public int Skipped { get; private set; } public int ExitCode { get; private set; } public bool ContainsNoRetryableTests { get; private set; } public override string ToString() { using (StringWriter writer = new StringWriter()) { if (0 < this.FailedTestNames.Count) { writer.WriteLine("Failed Tests :"); foreach (string testName in this.FailedTestNames) { writer.WriteLine(String.Format("\t{0}\n", testName)); } } writer.WriteLine("Passed : {0}, Failed : {1}", this.Passed, this.Failed); if(this.ContainsNoRetryableTests) { writer.WriteLine($"Non Retryable failed tests found"); } return writer.ToString(); } } } }
59
aws-sdk-net
aws
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using System.Xml.Linq; using Amazon.Runtime.CredentialManagement; namespace TestWrapper.TestRunners { public abstract class TestRunner { public enum TestConfiguration { Debug, Release } private readonly static TimeSpan MAX_SINGLE_EXEC_TIME = TimeSpan.FromHours(2); private const int MAX_TEST_RUNS_DEFAULT = 15; private const int MAX_CONSECUTIVE_FAILURES_DEFAULT = 5; private static readonly HashSet<char> CHARS_TO_QUOTE_ON = new HashSet<char> { ' ', '\t', }; private const string AWS_PROFILE_ENVIRONMENT_VARIABLE = "AWS_PROFILE"; protected TestRunner(string testSuiteExecutable, FileInfo testContainer, DirectoryInfo workingDirectory) { ValidateFileInfo(testContainer, nameof(testContainer)); if (workingDirectory != null && !workingDirectory.Exists) { throw new ArgumentOutOfRangeException(nameof(workingDirectory), "Directory not found at location " + workingDirectory.FullName); } TestSuiteExecutable = testSuiteExecutable; TestContainer = testContainer; WorkingDirectory = workingDirectory == null ? TestContainer.Directory : workingDirectory; RunnerName = this.GetType().Name; MaxTestRuns = MAX_TEST_RUNS_DEFAULT; MaxConsecutiveFailures = MAX_CONSECUTIVE_FAILURES_DEFAULT; } public string RunnerName { get; set; } public int MaxTestRuns { get; set; } public int MaxConsecutiveFailures { get; set; } public string TestSuiteExecutable { get; private set; } public FileInfo TestContainer { get; private set; } public DirectoryInfo WorkingDirectory { get; private set; } public string FrameworkCategoryAttribute { get; set; } public string[] Categories { get; set; } public string[] CategoriesToIgnore { get; set; } public TestConfiguration Configuration { get; set; } public string TestExecutionProfile { get; set; } /// <summary> /// Whether the final test results file should be kept on disk. /// If set to true, the TRX file will not be deleted after all tests run successfully or /// all retries are exhausted. /// </summary> public bool KeepTestResults { get; set; } private string TestResultsPath => Path.Combine(TestContainer.DirectoryName, "TestResults"); /// <summary> /// Run the tests for this test runner. /// </summary> /// <param name="failedTestNames">A list of the names of failed tests, if any.</param> /// <param name="exception">The exception that occurred while running tests, or null.</param> /// <returns>True if all tests passed, false otherwise.</returns> public bool RunTests(out IList<string> failedTestNames, out Exception exception) { bool allTestsPassed = false; exception = null; failedTestNames = new List<string>(); try { int prevFailedTestCount = Int32.MaxValue; int consecutiveFailureCount = 0; for (int runCount = 1; runCount < MaxTestRuns; runCount++) { var summary = Run(failedTestNames); failedTestNames = summary.FailedTestNames; Console.WriteLine("====== TestWrapper Run Attempt {0} =====", runCount); Console.WriteLine(RunnerName); Console.WriteLine(summary); Console.WriteLine("======================="); // If there were no Retryable test failures then stop all retries. if(summary.ContainsNoRetryableTests) { break; } if (summary.ExitCode != 0) { prevFailedTestCount = summary.Failed; } var anyRan = summary.Passed > 0 || summary.Failed > 0; if (!anyRan) { break; } allTestsPassed = summary.Failed == 0; if (allTestsPassed) { break; } if (summary.Failed < prevFailedTestCount) { prevFailedTestCount = summary.Failed; consecutiveFailureCount = 0; } else if (consecutiveFailureCount < MaxConsecutiveFailures) { consecutiveFailureCount++; } else { break; } // If the max number of retries hasn't been reached yet, delete the current test results file. if (runCount < MaxTestRuns) { CleanUpTestResults(); } } } catch (Exception e) { Console.WriteLine("Exception occurred running tests:\n {0}", e.ToString()); exception = e; allTestsPassed = false; } // At this point, the tests have completed (either successfully or not), but we check // if whoever invoked the task requested the results files should be maintained. if (!KeepTestResults) { CleanUpTestResults(); } return allTestsPassed; } protected ResultsSummary Run(IEnumerable<string> tests) { var args = ConstructArguments(tests); int exitCode = InvokeTestSuite(args, out var logLocation); var summary = ParseLog(exitCode, logLocation); return summary; } private void CleanUpTestResults() { Directory.Delete(TestResultsPath, true); } private static ResultsSummary ParseLog(int exitCode, string logLocation) { XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; var testRun = XElement.Load(logLocation); var resultSummary = testRun .Descendants(ns + "ResultSummary") .First(); var statistics = resultSummary .Descendants(ns + "Counters") .First() .Attributes() .ToDictionary(stat => stat.Name.LocalName, stat => int.Parse(stat.Value)); var passedCount = statistics["passed"]; var failedCount = statistics["failed"]; var skippedCount = statistics["total"] - statistics["executed"]; var unitTestResults = testRun .Descendants(ns + "Results") .Descendants(ns + "UnitTestResult"); /* * Previously, there was one query looking at all failed test results in the trx file. * However, there are a few methods which use [DataTest] and [DataRow] attributes, and in their case * the output will look something like this (one line for the test name and one line for each input): * Failed Tests : * TestMethod01 * TestMethod01 (abc) * TestMethod01 (xyz) * In the XML file, the input lines will be inside an "InnerResults" element and contain an attribute * called "parentExecutionId". We don't want to include them in the results summary (only the parent test name). */ var singleTests = unitTestResults.Where(ele => !ele.Descendants(ns + "InnerResults").Any() && !ele.Attributes("parentExecutionId").Any()); var dataRowTests = unitTestResults.Where(ele => ele.Descendants(ns + "InnerResults").Any()); var failedTests = singleTests.Union(dataRowTests) .Where(ele => ele.Attributes("outcome").First().Value == "Failed") .Select(ele => ele.Attributes("testName").First().Value) .ToList(); var containsNoRetryableTests = false; var testReportContent = File.ReadAllText(logLocation); if (ResultsSummary.NO_RETRYABLE_STRINGS.Any(x => testReportContent.Contains(x))) { containsNoRetryableTests = true; } return new ResultsSummary(exitCode, failedTests, passedCount, failedCount, skippedCount, containsNoRetryableTests); } private static void ValidateFileInfo(FileInfo fileInfo, string argName) { if (fileInfo == null) throw new ArgumentNullException(argName); if (!fileInfo.Exists) throw new ArgumentOutOfRangeException(argName, "File not found at location " + fileInfo.FullName); } protected static string QuoteArg(string arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); if (arg.IndexOf('"') >= 0) throw new ArgumentOutOfRangeException(nameof(arg), "Quotes are unexpected here"); var shouldQuote = arg.Any(c => CHARS_TO_QUOTE_ON.Contains(c)); if (shouldQuote) return string.Format("\"{0}\"", arg); else return arg; } protected int InvokeTestSuite(string args, out string logLocation) { var workingDir = WorkingDirectory.FullName; var file = TestSuiteExecutable; var si = new ProcessStartInfo { FileName = file, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; Console.WriteLine("Invoking tests."); Console.WriteLine("File: {0}", file); Console.WriteLine("Args: {0}", args); Console.WriteLine("Dir: {0}", workingDir); if (!string.IsNullOrWhiteSpace(TestExecutionProfile)) { var chain = new CredentialProfileStoreChain(); CredentialProfile profile; if (chain.TryGetProfile(TestExecutionProfile, out profile)) { Console.WriteLine($"Profile '{TestExecutionProfile}' found."); si.EnvironmentVariables[AWS_PROFILE_ENVIRONMENT_VARIABLE] = TestExecutionProfile; Console.WriteLine($"TestExecutionProfile: {TestExecutionProfile}"); } else { Console.WriteLine($"Profile '{TestExecutionProfile}' not found, ignoring the TestExecutionProfile attribute on test wrapper build task."); } } string error; string output; int exitCode; using (var outWriter = new StringWriter()) using (var errWriter = new StringWriter()) using (var p = new Process()) { p.StartInfo = si; p.OutputDataReceived += LogMultiple(Console.Out, outWriter); p.ErrorDataReceived += LogMultiple(Console.Error, errWriter); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); if (p.WaitForExit((int)MAX_SINGLE_EXEC_TIME.TotalMilliseconds)) { p.WaitForExit(); } output = outWriter.ToString(); error = errWriter.ToString(); exitCode = p.ExitCode; if (!p.HasExited) { var separator = new string('-', 10); using (var sw = new StringWriter()) { sw.WriteLine("Process is stuck!"); sw.WriteLine("StdOut"); sw.WriteLine(separator); sw.WriteLine(output); sw.WriteLine(separator); sw.WriteLine("ErrOut"); sw.WriteLine(separator); sw.WriteLine(error); sw.WriteLine(separator); var message = sw.ToString(); try { p.Kill(); } catch (Exception) { } throw new InvalidOperationException(message); } } p.Close(); } logLocation = Directory.GetFiles(TestResultsPath) .Select(fileName => new FileInfo(fileName)) .OrderByDescending(fileInfo => fileInfo.CreationTime) .First().FullName; return exitCode; } private static DataReceivedEventHandler LogMultiple(TextWriter consoleWriter, StringWriter stringWriter) { return (s, e) => { var data = e.Data; stringWriter.WriteLine(data); consoleWriter.WriteLine(data); }; } protected virtual string ConstructArguments(IEnumerable<string> tests) { var components = new List<string>(); // add test switch components.Add("test"); // add container components.Add(GetContainerArg(TestContainer.FullName)); // change logger to trx components.Add("--logger trx"); // add configuration components.Add(GetConfigArg(Configuration)); // add specific tests // dotnet test cannot handle parameterized test reruns (queries), so collapsing those failures to their distinct top theory var testsList = tests.Select(testName => Regex.Replace(testName, @"\(.*\)$", "")).Distinct().ToList(); string filter = null; if (testsList.Count > 0) { filter = string.Join("|", testsList.Select(GetTestArg)); } else if (Categories != null && Categories.Length > 0) { filter = string.Join("|", Categories.Select(GetCategoryArg)); } else if (CategoriesToIgnore != null && CategoriesToIgnore.Length > 0) { filter = string.Join("|", CategoriesToIgnore.Select(GetCategoryToIgnoreArg)); } if (!string.IsNullOrEmpty(filter)) { components.Add(string.Format("--filter \"{0}\"", filter)); } components.Add("--no-build"); var args = string.Join(" ", components); return args; } protected virtual string GetContainerArg(string container) { return QuoteArg(container); } protected virtual string GetTestArg(string testName) { if (testName.Contains(".")) { // assume a "." means it's a fully qualified name return string.Format("FullyQualifiedName={0}", QuoteArg(testName)); } else { // assume no "." means it's a test method name return string.Format("Name={0}", QuoteArg(testName.Trim(' '))); } } protected virtual string GetCategoryArg(string categoryName) { return string.Format("{0}={1}", FrameworkCategoryAttribute, categoryName); } protected virtual string GetCategoryToIgnoreArg(string categoryName) { return string.Format("{0}!={1}", FrameworkCategoryAttribute, categoryName); } protected virtual string GetConfigArg(TestConfiguration config) { return string.Format("-c {0}", QuoteArg(config.ToString())); } } }
428
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Linq; using TestWrapper.TestRunners; using System.IO; namespace TestWrapper { public class XUnitTestRunner : TestRunner { public XUnitTestRunner(string testSuiteExecutable, FileInfo testContainer, DirectoryInfo workingDirectory) : base(testSuiteExecutable, testContainer, workingDirectory: null) { } } }
20
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Build.Utilities; using System.IO; using System.Reflection; using Microsoft.Build.Framework; using TestWrapper.TestRunners; namespace TestWrapper { public class MsTestWrapperTask : TestWrapperTask { public ITaskItem ResultsOutputDir { get; set; } protected override void PrepareRunner() { var msTestRunner = new MSTestRunner(TestSuiteRunnerFileInfo, TestContainerFileInfo, null); msTestRunner.Categories = CategoriesArray; msTestRunner.CategoriesToIgnore = CategoriesToIgnoreArray; msTestRunner.FrameworkCategoryAttribute = "TestCategory"; msTestRunner.Configuration = Configuration == null ? TestRunner.TestConfiguration.Release : (TestRunner.TestConfiguration)Enum.Parse(typeof(TestRunner.TestConfiguration), Configuration.ItemSpec); msTestRunner.TestExecutionProfile = TestExecutionProfile.ItemSpec; msTestRunner.KeepTestResults = KeepTestResultsFile; Runner = msTestRunner; } } }
33
aws-sdk-net
aws
C#
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using TestWrapper.TestRunners; namespace TestWrapper { public abstract class TestWrapperTask : Task { public bool WaitForDebugger { get; set; } public ITaskItem Categories { get; set; } public ITaskItem CategoriesToIgnore { get; set; } public ITaskItem TestSuiteRunner { get; set; } public ITaskItem TestContainer { get; set; } public ITaskItem Configuration { get; set; } public ITaskItem TestExecutionProfile { get; set; } public ITaskItem KeepTestResults { get; set; } protected FileInfo TestContainerFileInfo { get { return new FileInfo(TestContainer.ItemSpec); } } protected string TestSuiteRunnerFileInfo { get { return TestSuiteRunner.ItemSpec; } } protected string[] CategoriesArray { get { string[] array = null; if (Categories != null && !string.IsNullOrEmpty(Categories.ItemSpec)) { array = Categories.ItemSpec .Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries) .Where(c => c != null && !string.IsNullOrEmpty(c.Trim())) .ToArray(); } return array; } } protected string[] CategoriesToIgnoreArray { get { string[] array = null; if (CategoriesToIgnore != null && !string.IsNullOrEmpty(CategoriesToIgnore.ItemSpec)) { array = CategoriesToIgnore.ItemSpec .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Where(c => c != null && !string.IsNullOrEmpty(c.Trim())) .ToArray(); } return array; } } protected bool KeepTestResultsFile { get { if (KeepTestResults == null || !bool.TryParse(KeepTestResults.ItemSpec, out var result)) { return false; } return result; } } protected TestRunner Runner { get; set; } public TestWrapperTask() { WaitForDebugger = false; } public override bool Execute() { CheckWaitForDebugger(); PrepareRunner(); IList<string> failedTestNames; Exception testRunException; if (Runner.RunTests(out failedTestNames, out testRunException)) return true; else { var loggingHelper = new TaskLoggingHelper(this); if (failedTestNames.Count > 0) { foreach (var name in failedTestNames) { loggingHelper.LogError(string.Format("Test failure in {0}: {1}", Runner.RunnerName, name)); } } if (testRunException != null) loggingHelper.LogErrorFromException(testRunException, true, true, null); return false; } } protected void CheckWaitForDebugger() { if (WaitForDebugger) { Log.LogMessage("MSBuild process id: {0}", Process.GetCurrentProcess().Id); Log.LogMessage("Waiting for debugger to be attached"); while (!Debugger.IsAttached) { Thread.Sleep(TimeSpan.FromSeconds(1)); } Debugger.Break(); } } protected abstract void PrepareRunner(); } }
124
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Build.Utilities; using System.IO; using System.Reflection; using Microsoft.Build.Framework; using static TestWrapper.XUnitTestRunner; using TestWrapper.TestRunners; namespace TestWrapper { public class XUnitWrapperTask : TestWrapperTask { protected override void PrepareRunner() { var xunitRunner = new XUnitTestRunner(TestSuiteRunnerFileInfo, TestContainerFileInfo, null); xunitRunner.Categories = CategoriesArray; xunitRunner.CategoriesToIgnore = CategoriesToIgnoreArray; xunitRunner.FrameworkCategoryAttribute = "Category"; xunitRunner.Configuration = Configuration == null ? TestRunner.TestConfiguration.Release : (TestRunner.TestConfiguration)Enum.Parse(typeof(TestRunner.TestConfiguration), Configuration.ItemSpec); xunitRunner.TestExecutionProfile = TestExecutionProfile.ItemSpec; xunitRunner.KeepTestResults = KeepTestResultsFile; Runner = xunitRunner; } } }
32
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace AWSSDKDocSamples { class Program { static int Main(string[] args) { bool allPass = true; var iSampleTypes = Assembly .GetExecutingAssembly() .GetTypes() .Where(t => t.GetInterfaces().Contains(typeof(ISample))) .ToList(); foreach (var iSampleType in iSampleTypes) { var iSample = Activator.CreateInstance(iSampleType) as ISample; try { iSample.Run(); } catch(Exception e) { allPass = false; Console.WriteLine("Error running sample in type {0}: {1}", iSampleType.FullName, e.ToString()); } } if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine(); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); } return (allPass ? 0 : 1); } } public interface ISample { void Run(); } }
50
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.AppConfig; using Amazon.AppConfig.Model; namespace AWSSDKDocSamples.Amazon.AppConfig.Generated { class AppConfigSamples : ISample { public void AppConfigCreateApplication() { #region to-create-an-application-1632264511615 var client = new AmazonAppConfigClient(); var response = client.CreateApplication(new CreateApplicationRequest { Description = "An application used for creating an example.", Name = "example-application" }); string description = response.Description; string id = response.Id; string name = response.Name; #endregion } public void AppConfigCreateConfigurationProfile() { #region to-create-a-configuration-profile-1632264580336 var client = new AmazonAppConfigClient(); var response = client.CreateConfigurationProfile(new CreateConfigurationProfileRequest { ApplicationId = "339ohji", LocationUri = "ssm-parameter://Example-Parameter", Name = "Example-Configuration-Profile", RetrievalRoleArn = "arn:aws:iam::111122223333:role/Example-App-Config-Role" }); string applicationId = response.ApplicationId; string id = response.Id; string locationUri = response.LocationUri; string name = response.Name; string retrievalRoleArn = response.RetrievalRoleArn; #endregion } public void AppConfigCreateDeploymentStrategy() { #region to-create-a-deployment-strategy-1632264783812 var client = new AmazonAppConfigClient(); var response = client.CreateDeploymentStrategy(new CreateDeploymentStrategyRequest { DeploymentDurationInMinutes = 15, GrowthFactor = 25, Name = "Example-Deployment", ReplicateTo = "SSM_DOCUMENT" }); int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; string growthType = response.GrowthType; string id = response.Id; string name = response.Name; string replicateTo = response.ReplicateTo; #endregion } public void AppConfigCreateEnvironment() { #region to-create-an-environment-1632265124975 var client = new AmazonAppConfigClient(); var response = client.CreateEnvironment(new CreateEnvironmentRequest { ApplicationId = "339ohji", Name = "Example-Environment" }); string applicationId = response.ApplicationId; string id = response.Id; string name = response.Name; string state = response.State; #endregion } public void AppConfigCreateHostedConfigurationVersion() { #region to-create-a-hosted-configuration-version-1632265196980 var client = new AmazonAppConfigClient(); var response = client.CreateHostedConfigurationVersion(new CreateHostedConfigurationVersionRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f", Content = new MemoryStream(eyAiTmFtZSI6ICJFeGFtcGxlQXBwbGljYXRpb24iLCAiSWQiOiBFeGFtcGxlSUQsICJSYW5rIjogNyB9), ContentType = "text", LatestVersionNumber = 1 }); string applicationId = response.ApplicationId; string configurationProfileId = response.ConfigurationProfileId; string contentType = response.ContentType; int versionNumber = response.VersionNumber; #endregion } public void AppConfigDeleteApplication() { #region to-delete-an-application-1632265343951 var client = new AmazonAppConfigClient(); var response = client.DeleteApplication(new DeleteApplicationRequest { ApplicationId = "339ohji" }); #endregion } public void AppConfigDeleteConfigurationProfile() { #region to-delete-a-configuration-profile-1632265401308 var client = new AmazonAppConfigClient(); var response = client.DeleteConfigurationProfile(new DeleteConfigurationProfileRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f" }); #endregion } public void AppConfigDeleteDeploymentStrategy() { #region to-delete-a-deployment-strategy-1632265473708 var client = new AmazonAppConfigClient(); var response = client.DeleteDeploymentStrategy(new DeleteDeploymentStrategyRequest { DeploymentStrategyId = "1225qzk" }); #endregion } public void AppConfigDeleteEnvironment() { #region to-delete-an-environment-1632265641044 var client = new AmazonAppConfigClient(); var response = client.DeleteEnvironment(new DeleteEnvironmentRequest { ApplicationId = "339ohji", EnvironmentId = "54j1r29" }); #endregion } public void AppConfigDeleteHostedConfigurationVersion() { #region to-delete-a-hosted-configuration-version-1632265720740 var client = new AmazonAppConfigClient(); var response = client.DeleteHostedConfigurationVersion(new DeleteHostedConfigurationVersionRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f", VersionNumber = 1 }); #endregion } public void AppConfigGetApplication() { #region to-list-details-of-an-application-1632265864702 var client = new AmazonAppConfigClient(); var response = client.GetApplication(new GetApplicationRequest { ApplicationId = "339ohji" }); string id = response.Id; string name = response.Name; #endregion } public void AppConfigGetConfiguration() { #region to-retrieve-configuration-details-1632265954314 var client = new AmazonAppConfigClient(); var response = client.GetConfiguration(new GetConfigurationRequest { Application = "example-application", ClientId = "example-id", Configuration = "Example-Configuration-Profile", Environment = "Example-Environment" }); string configurationVersion = response.ConfigurationVersion; string contentType = response.ContentType; #endregion } public void AppConfigGetConfigurationProfile() { #region to-retrieve-configuration-profile-details-1632266081013 var client = new AmazonAppConfigClient(); var response = client.GetConfigurationProfile(new GetConfigurationProfileRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f" }); string applicationId = response.ApplicationId; string id = response.Id; string locationUri = response.LocationUri; string name = response.Name; string retrievalRoleArn = response.RetrievalRoleArn; #endregion } public void AppConfigGetDeployment() { #region to-retrieve-deployment-details-1633976766883 var client = new AmazonAppConfigClient(); var response = client.GetDeployment(new GetDeploymentRequest { ApplicationId = "339ohji", DeploymentNumber = 1, EnvironmentId = "54j1r29" }); string applicationId = response.ApplicationId; DateTime completedAt = response.CompletedAt; string configurationLocationUri = response.ConfigurationLocationUri; string configurationName = response.ConfigurationName; string configurationProfileId = response.ConfigurationProfileId; string configurationVersion = response.ConfigurationVersion; int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int deploymentNumber = response.DeploymentNumber; string deploymentStrategyId = response.DeploymentStrategyId; string environmentId = response.EnvironmentId; List<DeploymentEvent> eventLog = response.EventLog; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; string growthType = response.GrowthType; float percentageComplete = response.PercentageComplete; DateTime startedAt = response.StartedAt; string state = response.State; #endregion } public void AppConfigGetDeploymentStrategy() { #region to-retrieve-details-of-a-deployment-strategy-1632266385805 var client = new AmazonAppConfigClient(); var response = client.GetDeploymentStrategy(new GetDeploymentStrategyRequest { DeploymentStrategyId = "1225qzk" }); int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; string growthType = response.GrowthType; string id = response.Id; string name = response.Name; string replicateTo = response.ReplicateTo; #endregion } public void AppConfigGetEnvironment() { #region to-retrieve-environment-details-1632266924806 var client = new AmazonAppConfigClient(); var response = client.GetEnvironment(new GetEnvironmentRequest { ApplicationId = "339ohji", EnvironmentId = "54j1r29" }); string applicationId = response.ApplicationId; string id = response.Id; string name = response.Name; string state = response.State; #endregion } public void AppConfigGetHostedConfigurationVersion() { #region to-retrieve-hosted-configuration-details-1632267003527 var client = new AmazonAppConfigClient(); var response = client.GetHostedConfigurationVersion(new GetHostedConfigurationVersionRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f", VersionNumber = 1 }); string applicationId = response.ApplicationId; string configurationProfileId = response.ConfigurationProfileId; string contentType = response.ContentType; int versionNumber = response.VersionNumber; #endregion } public void AppConfigListApplications() { #region to-list-the-available-applications-1632267111131 var client = new AmazonAppConfigClient(); var response = client.ListApplications(new ListApplicationsRequest { }); List<Application> items = response.Items; #endregion } public void AppConfigListConfigurationProfiles() { #region to-list-the-available-configuration-profiles-1632267193265 var client = new AmazonAppConfigClient(); var response = client.ListConfigurationProfiles(new ListConfigurationProfilesRequest { ApplicationId = "339ohji" }); List<ConfigurationProfileSummary> items = response.Items; #endregion } public void AppConfigListDeployments() { #region to-list-the-available-deployments-1632267282025 var client = new AmazonAppConfigClient(); var response = client.ListDeployments(new ListDeploymentsRequest { ApplicationId = "339ohji", EnvironmentId = "54j1r29" }); List<DeploymentSummary> items = response.Items; #endregion } public void AppConfigListDeploymentStrategies() { #region to-list-the-available-deployment-strategies-1632267364180 var client = new AmazonAppConfigClient(); var response = client.ListDeploymentStrategies(new ListDeploymentStrategiesRequest { }); List<DeploymentStrategy> items = response.Items; #endregion } public void AppConfigListEnvironments() { #region to-list-the-available-environments-1632267474389 var client = new AmazonAppConfigClient(); var response = client.ListEnvironments(new ListEnvironmentsRequest { ApplicationId = "339ohji" }); List<Environment> items = response.Items; #endregion } public void AppConfigListHostedConfigurationVersions() { #region to-list-the-available-hosted-configuration-versions-1632267647667 var client = new AmazonAppConfigClient(); var response = client.ListHostedConfigurationVersions(new ListHostedConfigurationVersionsRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f" }); List<HostedConfigurationVersionSummary> items = response.Items; #endregion } public void AppConfigListTagsForResource() { #region to-list-the-tags-of-an-application-1632328796560 var client = new AmazonAppConfigClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:appconfig:us-east-1:111122223333:application/339ohji" }); Dictionary<string, string> tags = response.Tags; #endregion } public void AppConfigStartDeployment() { #region to-start-a-configuration-deployment-1632328956790 var client = new AmazonAppConfigClient(); var response = client.StartDeployment(new StartDeploymentRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f", ConfigurationVersion = "1", DeploymentStrategyId = "1225qzk", Description = "", EnvironmentId = "54j1r29", Tags = new Dictionary<string, string> { } }); string applicationId = response.ApplicationId; string configurationLocationUri = response.ConfigurationLocationUri; string configurationName = response.ConfigurationName; string configurationProfileId = response.ConfigurationProfileId; string configurationVersion = response.ConfigurationVersion; int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int deploymentNumber = response.DeploymentNumber; string deploymentStrategyId = response.DeploymentStrategyId; string environmentId = response.EnvironmentId; List<DeploymentEvent> eventLog = response.EventLog; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; string growthType = response.GrowthType; float percentageComplete = response.PercentageComplete; DateTime startedAt = response.StartedAt; string state = response.State; #endregion } public void AppConfigStopDeployment() { #region to-stop-configuration-deployment-1632329139126 var client = new AmazonAppConfigClient(); var response = client.StopDeployment(new StopDeploymentRequest { ApplicationId = "339ohji", DeploymentNumber = 2, EnvironmentId = "54j1r29" }); int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int deploymentNumber = response.DeploymentNumber; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; float percentageComplete = response.PercentageComplete; #endregion } public void AppConfigTagResource() { #region to-tag-an-application-1632330350645 var client = new AmazonAppConfigClient(); var response = client.TagResource(new TagResourceRequest { ResourceArn = "arn:aws:appconfig:us-east-1:111122223333:application/339ohji", Tags = new Dictionary<string, string> { { "group1", "1" } } }); #endregion } public void AppConfigUntagResource() { #region to-remove-a-tag-from-an-application-1632330429881 var client = new AmazonAppConfigClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceArn = "arn:aws:appconfig:us-east-1:111122223333:application/339ohji", TagKeys = new List<string> { "group1" } }); #endregion } public void AppConfigUpdateApplication() { #region to-update-an-application-1632330585893 var client = new AmazonAppConfigClient(); var response = client.UpdateApplication(new UpdateApplicationRequest { ApplicationId = "339ohji", Description = "", Name = "Example-Application" }); string description = response.Description; string id = response.Id; string name = response.Name; #endregion } public void AppConfigUpdateConfigurationProfile() { #region to-update-a-configuration-profile-1632330721974 var client = new AmazonAppConfigClient(); var response = client.UpdateConfigurationProfile(new UpdateConfigurationProfileRequest { ApplicationId = "339ohji", ConfigurationProfileId = "ur8hx2f", Description = "Configuration profile used for examples." }); string applicationId = response.ApplicationId; string description = response.Description; string id = response.Id; string locationUri = response.LocationUri; string name = response.Name; string retrievalRoleArn = response.RetrievalRoleArn; #endregion } public void AppConfigUpdateDeploymentStrategy() { #region to-update-a-deployment-strategy-1632330896602 var client = new AmazonAppConfigClient(); var response = client.UpdateDeploymentStrategy(new UpdateDeploymentStrategyRequest { DeploymentStrategyId = "1225qzk", FinalBakeTimeInMinutes = 20 }); int deploymentDurationInMinutes = response.DeploymentDurationInMinutes; int finalBakeTimeInMinutes = response.FinalBakeTimeInMinutes; float growthFactor = response.GrowthFactor; string growthType = response.GrowthType; string id = response.Id; string name = response.Name; string replicateTo = response.ReplicateTo; #endregion } public void AppConfigUpdateEnvironment() { #region to-update-an-environment-1632331382428 var client = new AmazonAppConfigClient(); var response = client.UpdateEnvironment(new UpdateEnvironmentRequest { ApplicationId = "339ohji", Description = "An environment for examples.", EnvironmentId = "54j1r29" }); string applicationId = response.ApplicationId; string description = response.Description; string id = response.Id; string name = response.Name; string state = response.State; #endregion } public void AppConfigValidateConfiguration() { #region to-validate-a-configuration-1632331491365 var client = new AmazonAppConfigClient(); var response = client.ValidateConfiguration(new ValidateConfigurationRequest { ApplicationId = "abc1234", ConfigurationProfileId = "ur8hx2f", ConfigurationVersion = "1" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
648
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ApplicationAutoScaling; using Amazon.ApplicationAutoScaling.Model; namespace AWSSDKDocSamples.Amazon.ApplicationAutoScaling.Generated { class ApplicationAutoScalingSamples : ISample { public void ApplicationAutoScalingDeleteScalingPolicy() { #region to-delete-a-scaling-policy-1470863892689 var client = new AmazonApplicationAutoScalingClient(); var response = client.DeleteScalingPolicy(new DeleteScalingPolicyRequest { PolicyName = "web-app-cpu-lt-25", ResourceId = "service/default/web-app", ScalableDimension = "ecs:service:DesiredCount", ServiceNamespace = "ecs" }); #endregion } public void ApplicationAutoScalingDeleteScheduledAction() { #region to-delete-a-scheduled-action-1677963329606 var client = new AmazonApplicationAutoScalingClient(); var response = client.DeleteScheduledAction(new DeleteScheduledActionRequest { ResourceId = "fleet/sample-fleet", ScalableDimension = "appstream:fleet:DesiredCapacity", ScheduledActionName = "my-recurring-action", ServiceNamespace = "appstream" }); #endregion } public void ApplicationAutoScalingDeregisterScalableTarget() { #region to-deregister-a-scalable-target-1470864164895 var client = new AmazonApplicationAutoScalingClient(); var response = client.DeregisterScalableTarget(new DeregisterScalableTargetRequest { ResourceId = "service/default/web-app", ScalableDimension = "ecs:service:DesiredCount", ServiceNamespace = "ecs" }); #endregion } public void ApplicationAutoScalingDescribeScalableTargets() { #region to-describe-scalable-targets-1470864286961 var client = new AmazonApplicationAutoScalingClient(); var response = client.DescribeScalableTargets(new DescribeScalableTargetsRequest { ServiceNamespace = "ecs" }); List<ScalableTarget> scalableTargets = response.ScalableTargets; #endregion } public void ApplicationAutoScalingDescribeScalingActivities() { #region to-describe-scaling-activities-for-a-scalable-target-1470864398629 var client = new AmazonApplicationAutoScalingClient(); var response = client.DescribeScalingActivities(new DescribeScalingActivitiesRequest { ResourceId = "service/default/web-app", ScalableDimension = "ecs:service:DesiredCount", ServiceNamespace = "ecs" }); List<ScalingActivity> scalingActivities = response.ScalingActivities; #endregion } public void ApplicationAutoScalingDescribeScalingPolicies() { #region to-describe-scaling-policies-1470864609734 var client = new AmazonApplicationAutoScalingClient(); var response = client.DescribeScalingPolicies(new DescribeScalingPoliciesRequest { ServiceNamespace = "ecs" }); string nextToken = response.NextToken; List<ScalingPolicy> scalingPolicies = response.ScalingPolicies; #endregion } public void ApplicationAutoScalingDescribeScheduledActions() { #region to-describe-scheduled-actions-1677965249349 var client = new AmazonApplicationAutoScalingClient(); var response = client.DescribeScheduledActions(new DescribeScheduledActionsRequest { ServiceNamespace = "dynamodb" }); List<ScheduledAction> scheduledActions = response.ScheduledActions; #endregion } public void ApplicationAutoScalingListTagsForResource() { #region to-list-tags-for-a-scalable-target-1677971474903 var client = new AmazonApplicationAutoScalingClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceARN = "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123" }); Dictionary<string, string> tags = response.Tags; #endregion } public void ApplicationAutoScalingPutScalingPolicy() { #region to-apply-a-target-tracking-scaling-policy-with-a-predefined-metric-specification-1569364247984 var client = new AmazonApplicationAutoScalingClient(); var response = client.PutScalingPolicy(new PutScalingPolicyRequest { PolicyName = "cpu75-target-tracking-scaling-policy", PolicyType = "TargetTrackingScaling", ResourceId = "service/default/web-app", ScalableDimension = "ecs:service:DesiredCount", ServiceNamespace = "ecs", TargetTrackingScalingPolicyConfiguration = new TargetTrackingScalingPolicyConfiguration { PredefinedMetricSpecification = new PredefinedMetricSpecification { PredefinedMetricType = "ECSServiceAverageCPUUtilization" }, ScaleInCooldown = 60, ScaleOutCooldown = 60, TargetValue = 75 } }); List<Alarm> alarms = response.Alarms; string policyARN = response.PolicyARN; #endregion } public void ApplicationAutoScalingPutScheduledAction() { #region to-create-a-recurring-scheduled-action-1677970068621 var client = new AmazonApplicationAutoScalingClient(); var response = client.PutScheduledAction(new PutScheduledActionRequest { ResourceId = "table/TestTable", ScalableDimension = "dynamodb:table:WriteCapacityUnits", ScalableTargetAction = new ScalableTargetAction { MinCapacity = 6 }, Schedule = "cron(15 12 * * ? *)", ScheduledActionName = "my-recurring-action", ServiceNamespace = "dynamodb" }); #endregion } public void ApplicationAutoScalingRegisterScalableTarget() { #region to-register-a-new-scalable-target-1470864910380 var client = new AmazonApplicationAutoScalingClient(); var response = client.RegisterScalableTarget(new RegisterScalableTargetRequest { MaxCapacity = 10, MinCapacity = 1, ResourceId = "service/default/web-app", ScalableDimension = "ecs:service:DesiredCount", ServiceNamespace = "ecs" }); string scalableTargetARN = response.ScalableTargetARN; #endregion } public void ApplicationAutoScalingTagResource() { #region to-add-a-tag-to-a-scalable-target-1677970764620 var client = new AmazonApplicationAutoScalingClient(); var response = client.TagResource(new TagResourceRequest { ResourceARN = "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123", Tags = new Dictionary<string, string> { { "environment", "production" } } }); #endregion } public void ApplicationAutoScalingUntagResource() { #region to-remove-a-tag-from-a-scalable-target-1677971117168 var client = new AmazonApplicationAutoScalingClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceARN = "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123", TagKeys = new List<string> { "environment" } }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
249
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.AutoScaling; using Amazon.AutoScaling.Model; namespace AWSSDKDocSamples.Amazon.AutoScaling.Generated { class AutoScalingSamples : ISample { public void AutoScalingAttachInstances() { #region autoscaling-attach-instances-1 var client = new AmazonAutoScalingClient(); var response = client.AttachInstances(new AttachInstancesRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" } }); #endregion } public void AutoScalingAttachLoadBalancers() { #region autoscaling-attach-load-balancers-1 var client = new AmazonAutoScalingClient(); var response = client.AttachLoadBalancers(new AttachLoadBalancersRequest { AutoScalingGroupName = "my-auto-scaling-group", LoadBalancerNames = new List<string> { "my-load-balancer" } }); #endregion } public void AutoScalingAttachLoadBalancerTargetGroups() { #region autoscaling-attach-load-balancer-target-groups-1 var client = new AmazonAutoScalingClient(); var response = client.AttachLoadBalancerTargetGroups(new AttachLoadBalancerTargetGroupsRequest { AutoScalingGroupName = "my-auto-scaling-group", TargetGroupARNs = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" } }); #endregion } public void AutoScalingAttachTrafficSources() { #region to-attach-a-target-group-to-an-auto-scaling-group-1680036570089 var client = new AmazonAutoScalingClient(); var response = client.AttachTrafficSources(new AttachTrafficSourcesRequest { AutoScalingGroupName = "my-auto-scaling-group", TrafficSources = new List<TrafficSourceIdentifier> { new TrafficSourceIdentifier { Identifier = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" } } }); #endregion } public void AutoScalingCancelInstanceRefresh() { #region to-cancel-an-instance-refresh-1592960979817 var client = new AmazonAutoScalingClient(); var response = client.CancelInstanceRefresh(new CancelInstanceRefreshRequest { AutoScalingGroupName = "my-auto-scaling-group" }); string instanceRefreshId = response.InstanceRefreshId; #endregion } public void AutoScalingCompleteLifecycleAction() { #region autoscaling-complete-lifecycle-action-1 var client = new AmazonAutoScalingClient(); var response = client.CompleteLifecycleAction(new CompleteLifecycleActionRequest { AutoScalingGroupName = "my-auto-scaling-group", LifecycleActionResult = "CONTINUE", LifecycleActionToken = "bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635", LifecycleHookName = "my-lifecycle-hook" }); #endregion } public void AutoScalingCreateAutoScalingGroup() { #region autoscaling-create-auto-scaling-group-1 var client = new AmazonAutoScalingClient(); var response = client.CreateAutoScalingGroup(new CreateAutoScalingGroupRequest { AutoScalingGroupName = "my-auto-scaling-group", LaunchTemplate = new LaunchTemplateSpecification { LaunchTemplateName = "my-template-for-auto-scaling", Version = "$Latest" }, MaxInstanceLifetime = 2592000, MaxSize = 3, MinSize = 1, VPCZoneIdentifier = "subnet-057fa0918fEXAMPLE" }); #endregion } public void AutoScalingCreateAutoScalingGroup() { #region autoscaling-create-auto-scaling-group-2 var client = new AmazonAutoScalingClient(); var response = client.CreateAutoScalingGroup(new CreateAutoScalingGroupRequest { AutoScalingGroupName = "my-auto-scaling-group", HealthCheckGracePeriod = 300, HealthCheckType = "ELB", LaunchTemplate = new LaunchTemplateSpecification { LaunchTemplateName = "my-template-for-auto-scaling", Version = "$Latest" }, MaxSize = 3, MinSize = 1, TargetGroupARNs = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" }, VPCZoneIdentifier = "subnet-057fa0918fEXAMPLE, subnet-610acd08EXAMPLE" }); #endregion } public void AutoScalingCreateAutoScalingGroup() { #region to-create-an-auto-scaling-group-with-a-mixed-instances-policy-1617815269039 var client = new AmazonAutoScalingClient(); var response = client.CreateAutoScalingGroup(new CreateAutoScalingGroupRequest { AutoScalingGroupName = "my-asg", DesiredCapacity = 3, MaxSize = 5, MinSize = 1, MixedInstancesPolicy = new MixedInstancesPolicy { InstancesDistribution = new InstancesDistribution { OnDemandBaseCapacity = 1, OnDemandPercentageAboveBaseCapacity = 50, SpotAllocationStrategy = "capacity-optimized" }, LaunchTemplate = new LaunchTemplate { LaunchTemplateSpecification = new LaunchTemplateSpecification { LaunchTemplateName = "my-launch-template-for-x86", Version = "$Latest" }, Overrides = new List<LaunchTemplateOverrides> { new LaunchTemplateOverrides { InstanceType = "c6g.large", LaunchTemplateSpecification = new LaunchTemplateSpecification { LaunchTemplateName = "my-launch-template-for-arm", Version = "$Latest" } }, new LaunchTemplateOverrides { InstanceType = "c5.large" }, new LaunchTemplateOverrides { InstanceType = "c5a.large" } } } }, VPCZoneIdentifier = "subnet-057fa0918fEXAMPLE, subnet-610acd08EXAMPLE" }); #endregion } public void AutoScalingCreateLaunchConfiguration() { #region autoscaling-create-launch-configuration-1 var client = new AmazonAutoScalingClient(); var response = client.CreateLaunchConfiguration(new CreateLaunchConfigurationRequest { IamInstanceProfile = "my-iam-role", ImageId = "ami-12345678", InstanceType = "m3.medium", LaunchConfigurationName = "my-launch-config", SecurityGroups = new List<string> { "sg-eb2af88e" } }); #endregion } public void AutoScalingCreateOrUpdateTags() { #region autoscaling-create-or-update-tags-1 var client = new AmazonAutoScalingClient(); var response = client.CreateOrUpdateTags(new CreateOrUpdateTagsRequest { Tags = new List<Tag> { new Tag { Key = "Role", PropagateAtLaunch = true, ResourceId = "my-auto-scaling-group", ResourceType = "auto-scaling-group", Value = "WebServer" }, new Tag { Key = "Dept", PropagateAtLaunch = true, ResourceId = "my-auto-scaling-group", ResourceType = "auto-scaling-group", Value = "Research" } } }); #endregion } public void AutoScalingDeleteAutoScalingGroup() { #region autoscaling-delete-auto-scaling-group-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteAutoScalingGroup(new DeleteAutoScalingGroupRequest { AutoScalingGroupName = "my-auto-scaling-group" }); #endregion } public void AutoScalingDeleteAutoScalingGroup() { #region autoscaling-delete-auto-scaling-group-2 var client = new AmazonAutoScalingClient(); var response = client.DeleteAutoScalingGroup(new DeleteAutoScalingGroupRequest { AutoScalingGroupName = "my-auto-scaling-group", ForceDelete = true }); #endregion } public void AutoScalingDeleteLaunchConfiguration() { #region autoscaling-delete-launch-configuration-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteLaunchConfiguration(new DeleteLaunchConfigurationRequest { LaunchConfigurationName = "my-launch-config" }); #endregion } public void AutoScalingDeleteLifecycleHook() { #region autoscaling-delete-lifecycle-hook-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteLifecycleHook(new DeleteLifecycleHookRequest { AutoScalingGroupName = "my-auto-scaling-group", LifecycleHookName = "my-lifecycle-hook" }); #endregion } public void AutoScalingDeleteNotificationConfiguration() { #region autoscaling-delete-notification-configuration-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteNotificationConfiguration(new DeleteNotificationConfigurationRequest { AutoScalingGroupName = "my-auto-scaling-group", TopicARN = "arn:aws:sns:us-west-2:123456789012:my-sns-topic" }); #endregion } public void AutoScalingDeletePolicy() { #region autoscaling-delete-policy-1 var client = new AmazonAutoScalingClient(); var response = client.DeletePolicy(new DeletePolicyRequest { AutoScalingGroupName = "my-auto-scaling-group", PolicyName = "my-step-scale-out-policy" }); #endregion } public void AutoScalingDeleteScheduledAction() { #region autoscaling-delete-scheduled-action-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteScheduledAction(new DeleteScheduledActionRequest { AutoScalingGroupName = "my-auto-scaling-group", ScheduledActionName = "my-scheduled-action" }); #endregion } public void AutoScalingDeleteTags() { #region autoscaling-delete-tags-1 var client = new AmazonAutoScalingClient(); var response = client.DeleteTags(new DeleteTagsRequest { Tags = new List<Tag> { new Tag { Key = "Dept", ResourceId = "my-auto-scaling-group", ResourceType = "auto-scaling-group", Value = "Research" } } }); #endregion } public void AutoScalingDescribeAccountLimits() { #region autoscaling-describe-account-limits-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeAccountLimits(new DescribeAccountLimitsRequest { }); int maxNumberOfAutoScalingGroups = response.MaxNumberOfAutoScalingGroups; int maxNumberOfLaunchConfigurations = response.MaxNumberOfLaunchConfigurations; int numberOfAutoScalingGroups = response.NumberOfAutoScalingGroups; int numberOfLaunchConfigurations = response.NumberOfLaunchConfigurations; #endregion } public void AutoScalingDescribeAdjustmentTypes() { #region autoscaling-describe-adjustment-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeAdjustmentTypes(new DescribeAdjustmentTypesRequest { }); List<AdjustmentType> adjustmentTypes = response.AdjustmentTypes; #endregion } public void AutoScalingDescribeAutoScalingGroups() { #region autoscaling-describe-auto-scaling-groups-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeAutoScalingGroups(new DescribeAutoScalingGroupsRequest { AutoScalingGroupNames = new List<string> { "my-auto-scaling-group" } }); List<AutoScalingGroup> autoScalingGroups = response.AutoScalingGroups; #endregion } public void AutoScalingDescribeAutoScalingInstances() { #region autoscaling-describe-auto-scaling-instances-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeAutoScalingInstances(new DescribeAutoScalingInstancesRequest { InstanceIds = new List<string> { "i-4ba0837f" } }); List<AutoScalingInstanceDetails> autoScalingInstances = response.AutoScalingInstances; #endregion } public void AutoScalingDescribeAutoScalingNotificationTypes() { #region autoscaling-describe-auto-scaling-notification-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeAutoScalingNotificationTypes(new DescribeAutoScalingNotificationTypesRequest { }); List<string> autoScalingNotificationTypes = response.AutoScalingNotificationTypes; #endregion } public void AutoScalingDescribeInstanceRefreshes() { #region to-list-instance-refreshes-1592959593746 var client = new AmazonAutoScalingClient(); var response = client.DescribeInstanceRefreshes(new DescribeInstanceRefreshesRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<InstanceRefresh> instanceRefreshes = response.InstanceRefreshes; #endregion } public void AutoScalingDescribeLaunchConfigurations() { #region autoscaling-describe-launch-configurations-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeLaunchConfigurations(new DescribeLaunchConfigurationsRequest { LaunchConfigurationNames = new List<string> { "my-launch-config" } }); List<LaunchConfiguration> launchConfigurations = response.LaunchConfigurations; #endregion } public void AutoScalingDescribeLifecycleHooks() { #region autoscaling-describe-lifecycle-hooks-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeLifecycleHooks(new DescribeLifecycleHooksRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<LifecycleHook> lifecycleHooks = response.LifecycleHooks; #endregion } public void AutoScalingDescribeLifecycleHookTypes() { #region autoscaling-describe-lifecycle-hook-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeLifecycleHookTypes(new DescribeLifecycleHookTypesRequest { }); List<string> lifecycleHookTypes = response.LifecycleHookTypes; #endregion } public void AutoScalingDescribeLoadBalancers() { #region autoscaling-describe-load-balancers-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeLoadBalancers(new DescribeLoadBalancersRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<LoadBalancerState> loadBalancers = response.LoadBalancers; #endregion } public void AutoScalingDescribeLoadBalancerTargetGroups() { #region autoscaling-describe-load-balancer-target-groups-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeLoadBalancerTargetGroups(new DescribeLoadBalancerTargetGroupsRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<LoadBalancerTargetGroupState> loadBalancerTargetGroups = response.LoadBalancerTargetGroups; #endregion } public void AutoScalingDescribeMetricCollectionTypes() { #region autoscaling-describe-metric-collection-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeMetricCollectionTypes(new DescribeMetricCollectionTypesRequest { }); List<MetricGranularityType> granularities = response.Granularities; List<MetricCollectionType> metrics = response.Metrics; #endregion } public void AutoScalingDescribeNotificationConfigurations() { #region autoscaling-describe-notification-configurations-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeNotificationConfigurations(new DescribeNotificationConfigurationsRequest { AutoScalingGroupNames = new List<string> { "my-auto-scaling-group" } }); List<NotificationConfiguration> notificationConfigurations = response.NotificationConfigurations; #endregion } public void AutoScalingDescribePolicies() { #region autoscaling-describe-policies-1 var client = new AmazonAutoScalingClient(); var response = client.DescribePolicies(new DescribePoliciesRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<ScalingPolicy> scalingPolicies = response.ScalingPolicies; #endregion } public void AutoScalingDescribeScalingActivities() { #region autoscaling-describe-scaling-activities-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeScalingActivities(new DescribeScalingActivitiesRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<Activity> activities = response.Activities; #endregion } public void AutoScalingDescribeScalingProcessTypes() { #region autoscaling-describe-scaling-process-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeScalingProcessTypes(new DescribeScalingProcessTypesRequest { }); List<ProcessType> processes = response.Processes; #endregion } public void AutoScalingDescribeScheduledActions() { #region autoscaling-describe-scheduled-actions-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeScheduledActions(new DescribeScheduledActionsRequest { AutoScalingGroupName = "my-auto-scaling-group" }); List<ScheduledUpdateGroupAction> scheduledUpdateGroupActions = response.ScheduledUpdateGroupActions; #endregion } public void AutoScalingDescribeTags() { #region autoscaling-describe-tags-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeTags(new DescribeTagsRequest { Filters = new List<Filter> { new Filter { Name = "auto-scaling-group", Values = new List<string> { "my-auto-scaling-group" } } } }); List<TagDescription> tags = response.Tags; #endregion } public void AutoScalingDescribeTerminationPolicyTypes() { #region autoscaling-describe-termination-policy-types-1 var client = new AmazonAutoScalingClient(); var response = client.DescribeTerminationPolicyTypes(new DescribeTerminationPolicyTypesRequest { }); List<string> terminationPolicyTypes = response.TerminationPolicyTypes; #endregion } public void AutoScalingDescribeTrafficSources() { #region to-describe-the-target-groups-for-an-auto-scaling-group-1680040714521 var client = new AmazonAutoScalingClient(); var response = client.DescribeTrafficSources(new DescribeTrafficSourcesRequest { AutoScalingGroupName = "my-auto-scaling-group" }); string nextToken = response.NextToken; List<TrafficSourceState> trafficSources = response.TrafficSources; #endregion } public void AutoScalingDetachInstances() { #region autoscaling-detach-instances-1 var client = new AmazonAutoScalingClient(); var response = client.DetachInstances(new DetachInstancesRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" }, ShouldDecrementDesiredCapacity = true }); List<Activity> activities = response.Activities; #endregion } public void AutoScalingDetachLoadBalancers() { #region autoscaling-detach-load-balancers-1 var client = new AmazonAutoScalingClient(); var response = client.DetachLoadBalancers(new DetachLoadBalancersRequest { AutoScalingGroupName = "my-auto-scaling-group", LoadBalancerNames = new List<string> { "my-load-balancer" } }); #endregion } public void AutoScalingDetachLoadBalancerTargetGroups() { #region autoscaling-detach-load-balancer-target-groups-1 var client = new AmazonAutoScalingClient(); var response = client.DetachLoadBalancerTargetGroups(new DetachLoadBalancerTargetGroupsRequest { AutoScalingGroupName = "my-auto-scaling-group", TargetGroupARNs = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" } }); #endregion } public void AutoScalingDetachTrafficSources() { #region to-detach-a-target-group-from-an-auto-scaling-group-1680040404169 var client = new AmazonAutoScalingClient(); var response = client.DetachTrafficSources(new DetachTrafficSourcesRequest { AutoScalingGroupName = "my-auto-scaling-group", TrafficSources = new List<TrafficSourceIdentifier> { new TrafficSourceIdentifier { Identifier = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" } } }); #endregion } public void AutoScalingDisableMetricsCollection() { #region autoscaling-disable-metrics-collection-1 var client = new AmazonAutoScalingClient(); var response = client.DisableMetricsCollection(new DisableMetricsCollectionRequest { AutoScalingGroupName = "my-auto-scaling-group", Metrics = new List<string> { "GroupDesiredCapacity" } }); #endregion } public void AutoScalingEnableMetricsCollection() { #region autoscaling-enable-metrics-collection-1 var client = new AmazonAutoScalingClient(); var response = client.EnableMetricsCollection(new EnableMetricsCollectionRequest { AutoScalingGroupName = "my-auto-scaling-group", Granularity = "1Minute" }); #endregion } public void AutoScalingEnterStandby() { #region autoscaling-enter-standby-1 var client = new AmazonAutoScalingClient(); var response = client.EnterStandby(new EnterStandbyRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" }, ShouldDecrementDesiredCapacity = true }); List<Activity> activities = response.Activities; #endregion } public void AutoScalingExecutePolicy() { #region autoscaling-execute-policy-1 var client = new AmazonAutoScalingClient(); var response = client.ExecutePolicy(new ExecutePolicyRequest { AutoScalingGroupName = "my-auto-scaling-group", BreachThreshold = 50, MetricValue = 59, PolicyName = "my-step-scale-out-policy" }); #endregion } public void AutoScalingExitStandby() { #region autoscaling-exit-standby-1 var client = new AmazonAutoScalingClient(); var response = client.ExitStandby(new ExitStandbyRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" } }); List<Activity> activities = response.Activities; #endregion } public void AutoScalingPutLifecycleHook() { #region autoscaling-put-lifecycle-hook-1 var client = new AmazonAutoScalingClient(); var response = client.PutLifecycleHook(new PutLifecycleHookRequest { AutoScalingGroupName = "my-auto-scaling-group", DefaultResult = "CONTINUE", HeartbeatTimeout = 300, LifecycleHookName = "my-launch-lifecycle-hook", LifecycleTransition = "autoscaling:EC2_INSTANCE_LAUNCHING" }); #endregion } public void AutoScalingPutNotificationConfiguration() { #region autoscaling-put-notification-configuration-1 var client = new AmazonAutoScalingClient(); var response = client.PutNotificationConfiguration(new PutNotificationConfigurationRequest { AutoScalingGroupName = "my-auto-scaling-group", NotificationTypes = new List<string> { "autoscaling:TEST_NOTIFICATION" }, TopicARN = "arn:aws:sns:us-west-2:123456789012:my-sns-topic" }); #endregion } public void AutoScalingPutScalingPolicy() { #region autoscaling-put-scaling-policy-1 var client = new AmazonAutoScalingClient(); var response = client.PutScalingPolicy(new PutScalingPolicyRequest { AutoScalingGroupName = "my-auto-scaling-group", PolicyName = "alb1000-target-tracking-scaling-policy", PolicyType = "TargetTrackingScaling", TargetTrackingConfiguration = new TargetTrackingConfiguration { PredefinedMetricSpecification = new PredefinedMetricSpecification { PredefinedMetricType = "ALBRequestCountPerTarget", ResourceLabel = "app/my-alb/778d41231b141a0f/targetgroup/my-alb-target-group/943f017f100becff" }, TargetValue = 1000 } }); List<Alarm> alarms = response.Alarms; string policyARN = response.PolicyARN; #endregion } public void AutoScalingPutScheduledUpdateGroupAction() { #region autoscaling-put-scheduled-update-group-action-1 var client = new AmazonAutoScalingClient(); var response = client.PutScheduledUpdateGroupAction(new PutScheduledUpdateGroupActionRequest { AutoScalingGroupName = "my-auto-scaling-group", DesiredCapacity = 4, EndTimeUtc = new DateTime(2014, 5, 12, 1, 0, 0, DateTimeKind.Utc), MaxSize = 6, MinSize = 2, ScheduledActionName = "my-scheduled-action", StartTimeUtc = new DateTime(2014, 5, 12, 1, 0, 0, DateTimeKind.Utc) }); #endregion } public void AutoScalingPutWarmPool() { #region to-add-a-warm-pool-to-an-auto-scaling-group-1617818810383 var client = new AmazonAutoScalingClient(); var response = client.PutWarmPool(new PutWarmPoolRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceReusePolicy = new InstanceReusePolicy { ReuseOnScaleIn = true }, MinSize = 30, PoolState = "Hibernated" }); #endregion } public void AutoScalingRecordLifecycleActionHeartbeat() { #region autoscaling-record-lifecycle-action-heartbeat-1 var client = new AmazonAutoScalingClient(); var response = client.RecordLifecycleActionHeartbeat(new RecordLifecycleActionHeartbeatRequest { AutoScalingGroupName = "my-auto-scaling-group", LifecycleActionToken = "bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635", LifecycleHookName = "my-lifecycle-hook" }); #endregion } public void AutoScalingResumeProcesses() { #region autoscaling-resume-processes-1 var client = new AmazonAutoScalingClient(); var response = client.ResumeProcesses(new ResumeProcessesRequest { AutoScalingGroupName = "my-auto-scaling-group", ScalingProcesses = new List<string> { "AlarmNotification" } }); #endregion } public void AutoScalingSetDesiredCapacity() { #region autoscaling-set-desired-capacity-1 var client = new AmazonAutoScalingClient(); var response = client.SetDesiredCapacity(new SetDesiredCapacityRequest { AutoScalingGroupName = "my-auto-scaling-group", DesiredCapacity = 2, HonorCooldown = true }); #endregion } public void AutoScalingSetInstanceHealth() { #region autoscaling-set-instance-health-1 var client = new AmazonAutoScalingClient(); var response = client.SetInstanceHealth(new SetInstanceHealthRequest { HealthStatus = "Unhealthy", InstanceId = "i-93633f9b" }); #endregion } public void AutoScalingSetInstanceProtection() { #region autoscaling-set-instance-protection-1 var client = new AmazonAutoScalingClient(); var response = client.SetInstanceProtection(new SetInstanceProtectionRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" }, ProtectedFromScaleIn = true }); #endregion } public void AutoScalingSetInstanceProtection() { #region autoscaling-set-instance-protection-2 var client = new AmazonAutoScalingClient(); var response = client.SetInstanceProtection(new SetInstanceProtectionRequest { AutoScalingGroupName = "my-auto-scaling-group", InstanceIds = new List<string> { "i-93633f9b" }, ProtectedFromScaleIn = false }); #endregion } public void AutoScalingStartInstanceRefresh() { #region to-start-an-instance-refresh-1592957271522 var client = new AmazonAutoScalingClient(); var response = client.StartInstanceRefresh(new StartInstanceRefreshRequest { AutoScalingGroupName = "my-auto-scaling-group", DesiredConfiguration = new DesiredConfiguration { LaunchTemplate = new LaunchTemplateSpecification { LaunchTemplateName = "my-template-for-auto-scaling", Version = "$Latest" } }, Preferences = new RefreshPreferences { InstanceWarmup = 400, MinHealthyPercentage = 90, SkipMatching = true } }); string instanceRefreshId = response.InstanceRefreshId; #endregion } public void AutoScalingSuspendProcesses() { #region autoscaling-suspend-processes-1 var client = new AmazonAutoScalingClient(); var response = client.SuspendProcesses(new SuspendProcessesRequest { AutoScalingGroupName = "my-auto-scaling-group", ScalingProcesses = new List<string> { "AlarmNotification" } }); #endregion } public void AutoScalingTerminateInstanceInAutoScalingGroup() { #region autoscaling-terminate-instance-in-auto-scaling-group-1 var client = new AmazonAutoScalingClient(); var response = client.TerminateInstanceInAutoScalingGroup(new TerminateInstanceInAutoScalingGroupRequest { InstanceId = "i-93633f9b", ShouldDecrementDesiredCapacity = false }); #endregion } public void AutoScalingUpdateAutoScalingGroup() { #region autoscaling-update-auto-scaling-group-1 var client = new AmazonAutoScalingClient(); var response = client.UpdateAutoScalingGroup(new UpdateAutoScalingGroupRequest { AutoScalingGroupName = "my-auto-scaling-group", LaunchTemplate = new LaunchTemplateSpecification { LaunchTemplateName = "my-template-for-auto-scaling", Version = "2" }, MaxSize = 5, MinSize = 1, NewInstancesProtectedFromScaleIn = true }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
1,130
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Batch; using Amazon.Batch.Model; namespace AWSSDKDocSamples.Amazon.Batch.Generated { class BatchSamples : ISample { public void BatchCancelJob() { #region to-cancel-a-job-1481152314733 var client = new AmazonBatchClient(); var response = client.CancelJob(new CancelJobRequest { JobId = "1d828f65-7a4d-42e8-996d-3b900ed59dc4", Reason = "Cancelling job." }); #endregion } public void BatchCreateComputeEnvironment() { #region to-create-a-managed-ec2-compute-environment-1481152600017 var client = new AmazonBatchClient(); var response = client.CreateComputeEnvironment(new CreateComputeEnvironmentRequest { Type = "MANAGED", ComputeEnvironmentName = "C4OnDemand", ComputeResources = new ComputeResource { Type = "EC2", DesiredvCpus = 48, Ec2KeyPair = "id_rsa", InstanceRole = "ecsInstanceRole", InstanceTypes = new List<string> { "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge", "c4.8xlarge" }, MaxvCpus = 128, MinvCpus = 0, SecurityGroupIds = new List<string> { "sg-cf5093b2" }, Subnets = new List<string> { "subnet-220c0e0a", "subnet-1a95556d", "subnet-978f6dce" }, Tags = new Dictionary<string, string> { { "Name", "Batch Instance - C4OnDemand" } } }, ServiceRole = "arn:aws:iam::012345678910:role/AWSBatchServiceRole", State = "ENABLED" }); string computeEnvironmentArn = response.ComputeEnvironmentArn; string computeEnvironmentName = response.ComputeEnvironmentName; #endregion } public void BatchCreateComputeEnvironment() { #region to-create-a-managed-ec2-spot-compute-environment-1481152844190 var client = new AmazonBatchClient(); var response = client.CreateComputeEnvironment(new CreateComputeEnvironmentRequest { Type = "MANAGED", ComputeEnvironmentName = "M4Spot", ComputeResources = new ComputeResource { Type = "SPOT", BidPercentage = 20, DesiredvCpus = 4, Ec2KeyPair = "id_rsa", InstanceRole = "ecsInstanceRole", InstanceTypes = new List<string> { "m4" }, MaxvCpus = 128, MinvCpus = 0, SecurityGroupIds = new List<string> { "sg-cf5093b2" }, SpotIamFleetRole = "arn:aws:iam::012345678910:role/aws-ec2-spot-fleet-role", Subnets = new List<string> { "subnet-220c0e0a", "subnet-1a95556d", "subnet-978f6dce" }, Tags = new Dictionary<string, string> { { "Name", "Batch Instance - M4Spot" } } }, ServiceRole = "arn:aws:iam::012345678910:role/AWSBatchServiceRole", State = "ENABLED" }); string computeEnvironmentArn = response.ComputeEnvironmentArn; string computeEnvironmentName = response.ComputeEnvironmentName; #endregion } public void BatchCreateJobQueue() { #region to-create-a-job-queue-with-a-single-compute-environment-1481152967946 var client = new AmazonBatchClient(); var response = client.CreateJobQueue(new CreateJobQueueRequest { ComputeEnvironmentOrder = new List<ComputeEnvironmentOrder> { new ComputeEnvironmentOrder { ComputeEnvironment = "M4Spot", Order = 1 } }, JobQueueName = "LowPriority", Priority = 1, State = "ENABLED" }); string jobQueueArn = response.JobQueueArn; string jobQueueName = response.JobQueueName; #endregion } public void BatchCreateJobQueue() { #region to-create-a-job-queue-with-multiple-compute-environments-1481153027051 var client = new AmazonBatchClient(); var response = client.CreateJobQueue(new CreateJobQueueRequest { ComputeEnvironmentOrder = new List<ComputeEnvironmentOrder> { new ComputeEnvironmentOrder { ComputeEnvironment = "C4OnDemand", Order = 1 }, new ComputeEnvironmentOrder { ComputeEnvironment = "M4Spot", Order = 2 } }, JobQueueName = "HighPriority", Priority = 10, State = "ENABLED" }); string jobQueueArn = response.JobQueueArn; string jobQueueName = response.JobQueueName; #endregion } public void BatchDeleteComputeEnvironment() { #region to-delete-a-compute-environment-1481153105644 var client = new AmazonBatchClient(); var response = client.DeleteComputeEnvironment(new DeleteComputeEnvironmentRequest { ComputeEnvironment = "P2OnDemand" }); #endregion } public void BatchDeleteJobQueue() { #region to-delete-a-job-queue-1481153508134 var client = new AmazonBatchClient(); var response = client.DeleteJobQueue(new DeleteJobQueueRequest { JobQueue = "GPGPU" }); #endregion } public void BatchDeregisterJobDefinition() { #region to-deregister-a-job-definition-1481153579565 var client = new AmazonBatchClient(); var response = client.DeregisterJobDefinition(new DeregisterJobDefinitionRequest { JobDefinition = "sleep10" }); #endregion } public void BatchDescribeComputeEnvironments() { #region to-describe-a-compute-environment-1481153713334 var client = new AmazonBatchClient(); var response = client.DescribeComputeEnvironments(new DescribeComputeEnvironmentsRequest { ComputeEnvironments = new List<string> { "P2OnDemand" } }); List<ComputeEnvironmentDetail> computeEnvironments = response.ComputeEnvironments; #endregion } public void BatchDescribeJobDefinitions() { #region to-describe-active-job-definitions-1481153895831 var client = new AmazonBatchClient(); var response = client.DescribeJobDefinitions(new DescribeJobDefinitionsRequest { Status = "ACTIVE" }); List<JobDefinition> jobDefinitions = response.JobDefinitions; #endregion } public void BatchDescribeJobQueues() { #region to-describe-a-job-queue-1481153995804 var client = new AmazonBatchClient(); var response = client.DescribeJobQueues(new DescribeJobQueuesRequest { JobQueues = new List<string> { "HighPriority" } }); List<JobQueueDetail> jobQueues = response.JobQueues; #endregion } public void BatchDescribeJobs() { #region to-describe-a-specific-job-1481154090490 var client = new AmazonBatchClient(); var response = client.DescribeJobs(new DescribeJobsRequest { Jobs = new List<string> { "24fa2d7a-64c4-49d2-8b47-f8da4fbde8e9" } }); List<JobDetail> jobs = response.Jobs; #endregion } public void BatchListJobs() { #region to-list-running-jobs-1481154202164 var client = new AmazonBatchClient(); var response = client.ListJobs(new ListJobsRequest { JobQueue = "HighPriority" }); List<JobSummary> jobSummaryList = response.JobSummaryList; #endregion } public void BatchListJobs() { #region to-list-submitted-jobs-1481154251623 var client = new AmazonBatchClient(); var response = client.ListJobs(new ListJobsRequest { JobQueue = "HighPriority", JobStatus = "SUBMITTED" }); List<JobSummary> jobSummaryList = response.JobSummaryList; #endregion } public void BatchListTagsForResource() { #region listtagsforresource-example-1591293003710 var client = new AmazonBatchClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1" }); Dictionary<string, string> tags = response.Tags; #endregion } public void BatchRegisterJobDefinition() { #region to-register-a-job-definition-1481154325325 var client = new AmazonBatchClient(); var response = client.RegisterJobDefinition(new RegisterJobDefinitionRequest { Type = "container", ContainerProperties = new ContainerProperties { Command = new List<string> { "sleep", "10" }, Image = "busybox", ResourceRequirements = new List<ResourceRequirement> { new ResourceRequirement { Type = "MEMORY", Value = "128" }, new ResourceRequirement { Type = "VCPU", Value = "1" } } }, JobDefinitionName = "sleep10" }); string jobDefinitionArn = response.JobDefinitionArn; string jobDefinitionName = response.JobDefinitionName; int revision = response.Revision; #endregion } public void BatchRegisterJobDefinition() { #region registerjobdefinition-with-tags-1591290509028 var client = new AmazonBatchClient(); var response = client.RegisterJobDefinition(new RegisterJobDefinitionRequest { Type = "container", ContainerProperties = new ContainerProperties { Command = new List<string> { "sleep", "30" }, Image = "busybox", ResourceRequirements = new List<ResourceRequirement> { new ResourceRequirement { Type = "MEMORY", Value = "128" }, new ResourceRequirement { Type = "VCPU", Value = "1" } } }, JobDefinitionName = "sleep30", Tags = new Dictionary<string, string> { { "Department", "Engineering" }, { "User", "JaneDoe" } } }); string jobDefinitionArn = response.JobDefinitionArn; string jobDefinitionName = response.JobDefinitionName; int revision = response.Revision; #endregion } public void BatchSubmitJob() { #region to-submit-a-job-to-a-queue-1481154481673 var client = new AmazonBatchClient(); var response = client.SubmitJob(new SubmitJobRequest { JobDefinition = "sleep60", JobName = "example", JobQueue = "HighPriority" }); string jobId = response.JobId; string jobName = response.JobName; #endregion } public void BatchTagResource() { #region tagresource-example-1591291959952 var client = new AmazonBatchClient(); var response = client.TagResource(new TagResourceRequest { ResourceArn = "arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1", Tags = new Dictionary<string, string> { { "Stage", "Alpha" } } }); #endregion } public void BatchTerminateJob() { #region to-terminate-a-job-1481154558276 var client = new AmazonBatchClient(); var response = client.TerminateJob(new TerminateJobRequest { JobId = "61e743ed-35e4-48da-b2de-5c8333821c84", Reason = "Terminating job." }); #endregion } public void BatchUntagResource() { #region untagresource-example-1591292811042 var client = new AmazonBatchClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceArn = "arn:aws:batch:us-east-1:123456789012:job-definition/sleep30:1", TagKeys = new List<string> { "Stage" } }); #endregion } public void BatchUpdateComputeEnvironment() { #region to-update-a-compute-environment-1481154702731 var client = new AmazonBatchClient(); var response = client.UpdateComputeEnvironment(new UpdateComputeEnvironmentRequest { ComputeEnvironment = "P2OnDemand", State = "DISABLED" }); string computeEnvironmentArn = response.ComputeEnvironmentArn; string computeEnvironmentName = response.ComputeEnvironmentName; #endregion } public void BatchUpdateJobQueue() { #region to-update-a-job-queue-1481154806981 var client = new AmazonBatchClient(); var response = client.UpdateJobQueue(new UpdateJobQueueRequest { JobQueue = "GPGPU", State = "DISABLED" }); string jobQueueArn = response.JobQueueArn; string jobQueueName = response.JobQueueName; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
507
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Cloud9; using Amazon.Cloud9.Model; namespace AWSSDKDocSamples.Amazon.Cloud9.Generated { class Cloud9Samples : ISample { public void Cloud9CreateEnvironmentEC2() { #region createenvironmentec2-1516821730547 var client = new AmazonCloud9Client(); var response = client.CreateEnvironmentEC2(new CreateEnvironmentEC2Request { Name = "my-demo-environment", AutomaticStopTimeMinutes = 60, Description = "This is my demonstration environment.", InstanceType = "t2.micro", OwnerArn = "arn:aws:iam::123456789012:user/MyDemoUser", SubnetId = "subnet-6300cd1b" }); string environmentId = response.EnvironmentId; #endregion } public void Cloud9CreateEnvironmentMembership() { #region createenvironmentmembership-1516822583452 var client = new AmazonCloud9Client(); var response = client.CreateEnvironmentMembership(new CreateEnvironmentMembershipRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX", Permissions = "read-write", UserArn = "arn:aws:iam::123456789012:user/AnotherDemoUser" }); EnvironmentMember membership = response.Membership; #endregion } public void Cloud9DeleteEnvironment() { #region deleteenvironment-1516822903149 var client = new AmazonCloud9Client(); var response = client.DeleteEnvironment(new DeleteEnvironmentRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX" }); #endregion } public void Cloud9DeleteEnvironmentMembership() { #region deleteenvironmentmembership-1516822975655 var client = new AmazonCloud9Client(); var response = client.DeleteEnvironmentMembership(new DeleteEnvironmentMembershipRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX", UserArn = "arn:aws:iam::123456789012:user/AnotherDemoUser" }); #endregion } public void Cloud9DescribeEnvironmentMemberships() { #region describeenvironmentmemberships1-1516823070453 var client = new AmazonCloud9Client(); var response = client.DescribeEnvironmentMemberships(new DescribeEnvironmentMembershipsRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX" }); List<EnvironmentMember> memberships = response.Memberships; #endregion } public void Cloud9DescribeEnvironmentMemberships() { #region describeenvironmentmemberships2-1516823191355 var client = new AmazonCloud9Client(); var response = client.DescribeEnvironmentMemberships(new DescribeEnvironmentMembershipsRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX", Permissions = new List<string> { "owner" } }); List<EnvironmentMember> memberships = response.Memberships; #endregion } public void Cloud9DescribeEnvironmentMemberships() { #region describeenvironmentmemberships3-1516823268793 var client = new AmazonCloud9Client(); var response = client.DescribeEnvironmentMemberships(new DescribeEnvironmentMembershipsRequest { UserArn = "arn:aws:iam::123456789012:user/MyDemoUser" }); List<EnvironmentMember> memberships = response.Memberships; #endregion } public void Cloud9DescribeEnvironments() { #region describeenvironments-1516823568291 var client = new AmazonCloud9Client(); var response = client.DescribeEnvironments(new DescribeEnvironmentsRequest { EnvironmentIds = new List<string> { "8d9967e2f0624182b74e7690ad69ebEX", "349c86d4579e4e7298d500ff57a6b2EX" } }); List<Environment> environments = response.Environments; #endregion } public void Cloud9DescribeEnvironmentStatus() { #region describeenvironmentstatus-1516823462133 var client = new AmazonCloud9Client(); var response = client.DescribeEnvironmentStatus(new DescribeEnvironmentStatusRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX" }); string message = response.Message; string status = response.Status; #endregion } public void Cloud9ListEnvironments() { #region listenvironments-1516823687205 var client = new AmazonCloud9Client(); var response = client.ListEnvironments(new ListEnvironmentsRequest { }); List<string> environmentIds = response.EnvironmentIds; #endregion } public void Cloud9UpdateEnvironment() { #region updateenvironment-1516823781910 var client = new AmazonCloud9Client(); var response = client.UpdateEnvironment(new UpdateEnvironmentRequest { Name = "my-changed-demo-environment", Description = "This is my changed demonstration environment.", EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX" }); #endregion } public void Cloud9UpdateEnvironmentMembership() { #region updateenvironmentmembership-1516823876645 var client = new AmazonCloud9Client(); var response = client.UpdateEnvironmentMembership(new UpdateEnvironmentMembershipRequest { EnvironmentId = "8d9967e2f0624182b74e7690ad69ebEX", Permissions = "read-only", UserArn = "arn:aws:iam::123456789012:user/AnotherDemoUser" }); EnvironmentMember membership = response.Membership; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
218
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; namespace AWSSDKDocSamples.Amazon.CloudFormation.Generated { class CloudFormationSamples : ISample { static IAmazonCloudFormation client = new AmazonCloudFormationClient(); public void CloudFormationCancelUpdateStack() { #region to-cancel-a-stack-update-that-is-in-progress-1472747085196 var response = client.CancelUpdateStack(new CancelUpdateStackRequest { StackName = "MyStack" }); #endregion } public void CloudFormationUpdateStack() { #region to-update-an-aws-cloudformation-stack-1472841931621 var response = client.UpdateStack(new UpdateStackRequest { NotificationARNs = new List<string> { }, Parameters = new List<Parameter> { new Parameter { ParameterKey = "KeyPairName", ParameterValue = "ExampleKeyPair" }, new Parameter { ParameterKey = "SubnetIDs", ParameterValue = "ExampleSubnetID1, ExampleSubnetID2" } }, ResourceTypes = new List<string> { }, StackName = "MyStack", Tags = new List<Tag> { }, TemplateURL = "https://s3.amazonaws.com/example/updated.template" }); string stackId = response.StackId; #endregion } public void CloudFormationUpdateStack() { #region to-update-an-aws-cloudformation-stack-1472841931621 var response = client.UpdateStack(new UpdateStackRequest { NotificationARNs = new List<string> { }, Parameters = new List<Parameter> { new Parameter { ParameterKey = "KeyPairName", UsePreviousValue = true }, new Parameter { ParameterKey = "SubnetIDs", ParameterValue = "SampleSubnetID1, UpdatedSampleSubnetID2" } }, ResourceTypes = new List<string> { }, StackName = "MyStack", Tags = new List<Tag> { }, TemplateURL = "https://s3.amazonaws.com/example/updated.template" }); string stackId = response.StackId; #endregion } public void CloudFormationUpdateStack() { #region to-update-an-aws-cloudformation-stack-1472841931621 var response = client.UpdateStack(new UpdateStackRequest { Capabilities = new List<string> { }, NotificationARNs = new List<string> { "arn:aws:sns:use-east-1:123456789012:mytopic1", "arn:aws:sns:us-east-1:123456789012:mytopic2" }, Parameters = new List<Parameter> { }, ResourceTypes = new List<string> { }, StackName = "MyStack", Tags = new List<Tag> { }, TemplateURL = "https://s3.amazonaws.com/example/updated.template", UsePreviousTemplate = true }); string stackId = response.StackId; #endregion } public void CloudFormationValidateTemplate() { #region to-validate-an-aws-cloudformation-template-1472839072307 var response = client.ValidateTemplate(new ValidateTemplateRequest { TemplateBody = "MyTemplate.json" }); List<string> capabilities = response.Capabilities; string capabilitiesReason = response.CapabilitiesReason; string description = response.Description; List<TemplateParameter> parameters = response.Parameters; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
154
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; namespace AWSSDKDocSamples.CloudWatch { class CloudWatchSamples : ISample { public static void CWGetMetricStatistics() { #region CWGetMetricStatistics var client = new AmazonCloudWatchClient(); var request = new GetMetricStatisticsRequest { Dimensions = new List<Dimension>() { dimension }, EndTime = DateTime.Today, MetricName = "CPUUtilization", Namespace = "AWS/EC2", // Get statistics by day. Period = (int)TimeSpan.FromDays(1).TotalSeconds, // Get statistics for the past month. StartTime = DateTime.Today.Subtract(TimeSpan.FromDays(30)), Statistics = new List<string>() { "Minimum" }, Unit = StandardUnit.Percent }; var response = client.GetMetricStatistics(request); if (response.Datapoints.Count > 0) { foreach (var point in response.Datapoints) { Console.WriteLine(point.Timestamp.ToShortDateString() + " " + point.Minimum + "%"); } } #endregion Console.ReadLine(); } public static void CWPutMetricData() { #region CWPutMetricData var client = new AmazonCloudWatchClient(); var dimension = new Dimension { Name = "Desktop Machine Metrics", Value = "Virtual Desktop Machine Usage" }; var metric1 = new MetricDatum { Dimensions = new List<Dimension>() { dimension }, MetricName = "Desktop Machines Online", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 14 }; var metric2 = new MetricDatum { Dimensions = new List<Dimension>() { dimension }, MetricName = "Desktop Machines Offline", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 7 }; var metric3 = new MetricDatum { Dimensions = new List<Dimension>() { dimension }, MetricName = "Desktop Machines Online", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 12 }; var metric4 = new MetricDatum { Dimensions = new List<Dimension>() { dimension }, MetricName = "Desktop Machines Offline", StatisticValues = new StatisticSet(), Timestamp = DateTime.Today, Unit = StandardUnit.Count, Value = 9 }; var request = new PutMetricDataRequest { MetricData = new List<MetricDatum>() { metric1, metric2, metric3, metric4 }, Namespace = "Example.com Custom Metrics" }; client.PutMetricData(request); #endregion } public static void CWListMetrics() { #region CWListMetrics var client = new AmazonCloudWatchClient(); var filter = new DimensionFilter { Name = "InstanceType", Value = "t1.micro" }; var request = new ListMetricsRequest { Dimensions = new List<DimensionFilter>() { filter }, MetricName = "CPUUtilization", Namespace = "AWS/EC2" }; var response = new ListMetricsResponse(); do { response = client.ListMetrics(request); if (response.Metrics.Count > 0) { foreach (var metric in response.Metrics) { Console.WriteLine(metric.MetricName + " (" + metric.Namespace + ")"); foreach (var dimension in metric.Dimensions) { Console.WriteLine(" " + dimension.Name + ": " + dimension.Value); } } } else { Console.WriteLine("No metrics found."); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void CWDescribeAlarms() { #region CWDescribeAlarms var client = new AmazonCloudWatchClient(); var request = new DescribeAlarmsRequest { AlarmNames = new List<string>() { "awseb-e-b36EXAMPLE-stack-CloudwatchAlarmLow-1KAKH4EXAMPLE" }, MaxRecords = 1, StateValue = StateValue.ALARM }; var response = new DescribeAlarmsResponse(); do { response = client.DescribeAlarms(request); foreach (var alarm in response.MetricAlarms) { Console.WriteLine(alarm.AlarmName); Console.WriteLine(alarm.AlarmDescription); Console.WriteLine(alarm.MetricName + " " + alarm.ComparisonOperator + " " + alarm.Threshold); Console.WriteLine(); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void CWDescribeAlarmHistory() { #region CWDescribeAlarmHistory var client = new AmazonCloudWatchClient(); var request = new DescribeAlarmHistoryRequest { AlarmName = "awseb-e-kkbEXAMPLE-stack-CloudwatchAlarmLow-1WVXD9EXAMPLE", EndDate = DateTime.Today, HistoryItemType = HistoryItemType.Action, MaxRecords = 1, StartDate = DateTime.Today.Subtract(TimeSpan.FromDays(30)) }; var response = new DescribeAlarmHistoryResponse(); do { response = client.DescribeAlarmHistory(request); foreach (var item in response.AlarmHistoryItems) { Console.WriteLine(item.AlarmName); Console.WriteLine(item.HistorySummary); Console.WriteLine(); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void CWPutMetricAlarm() { #region CWPutMetricAlarm var client = new AmazonCloudWatchClient(); var dimension = new Dimension { Name = "Desktop Machine Metrics", Value = "Virtual Desktop Machine Usage" }; var request = new PutMetricAlarmRequest { ActionsEnabled = true, AlarmActions = new List<string>() { "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults" }, AlarmDescription = "Too many instances offline", AlarmName = "Offline Instances", ComparisonOperator = ComparisonOperator.GreaterThanOrEqualToThreshold, Dimensions = new List<Dimension>() { dimension }, EvaluationPeriods = 1, MetricName = "Desktop Machines Offline", Namespace = "Example.com Custom Metrics", Period = (int)TimeSpan.FromMinutes(5).TotalSeconds, Statistic = new Statistic("Maximum"), Threshold = 5, Unit = StandardUnit.Count }; client.PutMetricAlarm(request); #endregion } public static void CWDescribeAlarmsForMetric() { #region CWDescribeAlarmsForMetric var client = new AmazonCloudWatchClient(); var dimension = new Dimension { Name = "AutoScalingGroupName", Value = "awseb-e-kkbEXAMPLE-stack-AutoScalingGroup-F4TAUEXAMPLE" }; var request = new DescribeAlarmsForMetricRequest { Dimensions = new List<Dimension>() { dimension }, MetricName = "NetworkOut", Namespace = "AWS/EC2" }; var response = client.DescribeAlarmsForMetric(request); if (response.MetricAlarms.Count > 0) { foreach (var alarm in response.MetricAlarms) { Console.WriteLine(); Console.WriteLine(alarm.AlarmName); Console.WriteLine(alarm.AlarmDescription); Console.WriteLine(alarm.MetricName + " " + alarm.ComparisonOperator + " " + alarm.Threshold); } } else { Console.WriteLine("No alarms."); } #endregion Console.ReadLine(); } public static void CWDeleteAlarms() { #region CWDeleteAlarms var client = new AmazonCloudWatchClient(); var request = new DeleteAlarmsRequest { AlarmNames = new List<string>() { "t1.microCPUUtilization" } }; client.DeleteAlarms(request); #endregion } public static void CWSetAlarmState() { #region CWSetAlarmState var client = new AmazonCloudWatchClient(); var request = new SetAlarmStateRequest { AlarmName = "Offline Instances", StateReason = "Too many instances are offline.", StateValue = StateValue.ALARM }; client.SetAlarmState(request); #endregion } public static void CWEnableAlarmActions() { #region CWEnableAlarmActions var client = new AmazonCloudWatchClient(); var request = new EnableAlarmActionsRequest { AlarmNames = new List<string>() { "awseb-e-kkbEXAMPLE-stack-CloudwatchAlarmLow-1WVXD9EXAMPLE" } }; client.EnableAlarmActions(request); #endregion } public static void CWDisableAlarmActions() { #region CWDisableAlarmActions var client = new AmazonCloudWatchClient(); var request = new DisableAlarmActionsRequest { AlarmNames = new List<string>() { "awseb-e-kkbEXAMPLE-stack-CloudwatchAlarmLow-1WVXD9EXAMPLE" } }; client.DisableAlarmActions(request); #endregion } #region ISample Members public virtual void Run() { } #endregion } }
374
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CodeBuild; using Amazon.CodeBuild.Model; namespace AWSSDKDocSamples.Amazon.CodeBuild.Generated { class CodeBuildSamples : ISample { public void CodeBuildBatchGetBuilds() { #region to-get-information-about-builds-1501187184588 var client = new AmazonCodeBuildClient(); var response = client.BatchGetBuilds(new BatchGetBuildsRequest { Ids = new List<string> { "codebuild-demo-project:9b0ac37f-d19e-4254-9079-f47e9a389eEX", "codebuild-demo-project:b79a46f7-1473-4636-a23f-da9c45c208EX" } }); List<Build> builds = response.Builds; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
41
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CodePipeline; using Amazon.CodePipeline.Model; namespace AWSSDKDocSamples.Amazon.CodePipeline.Generated { class CodePipelineSamples : ISample { static IAmazonCodePipeline client = new AmazonCodePipelineClient(); public void CodePipelineAcknowledgeJob() { #region acknowledge-a-job-for-a-custom-action-1449100979484 var response = client.AcknowledgeJob(new AcknowledgeJobRequest { JobId = "11111111-abcd-1111-abcd-111111abcdef", // Use the PollforJobs API to determine the ID of the job. Nonce = "3" // Use the PollforJobs API to determine the nonce for the job. }); string status = response.Status; // Valid values include Created, Queued, Dispatched, InProgress, TimedOut, Suceeded, and Failed. Completed jobs are removed from the system after a short period of time. #endregion } public void CodePipelineCreateCustomActionType() { #region create-a-custom-action-1449103500903 var response = client.CreateCustomActionType(new CreateCustomActionTypeRequest { Version = "1", // A new custom action always has a version of 1. This is required. Category = "Build", ConfigurationProperties = new List<ActionConfigurationProperty> { new ActionConfigurationProperty { Name = "MyJenkinsExampleBuildProject", Type = "String", Required = true, Key = true, Description = "The name of the build project must be provided when this action is added to the pipeline.", Queryable = false, Secret = false } }, // The text in description will be displayed to your users, and can contain a maximum of 2048 characters. The value for name in configurationProperties is the name of the project, if any. In this example, this is the name of the build project on the Jenkins server InputArtifactDetails = new ArtifactDetails { MaximumCount = 1, MinimumCount = 0 }, // This is the minimum and maximum number of artifacts allowed as inputs for the action. For more information about input and output artifacts, see Pipeline Structure Reference in the AWS CodePipeline User Guide. OutputArtifactDetails = new ArtifactDetails { MaximumCount = 1, MinimumCount = 0 }, // This is the minimum and maximum number of artifacts allowed as outputs for the action. For more information about input and output artifacts, see Pipeline Structure Reference in the AWS CodePipeline User Guide. Provider = "MyBuild-ProviderName", // In this example, this is the name given to the provider field when configuring the AWS CodePipeline Plugin for Jenkins. For more information, see the Four-Stage Pipeline Tutorial in the AWS CodePipeline User Guide. Settings = new ActionTypeSettings { EntityUrlTemplate = "https://192.0.2.4/job/{Config:ProjectName}/", ExecutionUrlTemplate = "https://192.0.2.4/job/{Config:ProjectName}/lastSuccessfulBuild/{ExternalExecutionId}/", RevisionUrlTemplate = "none" } // entityUrlTemplate is the static link that provides information about the service provider for the action. In the example, the build system includes a static link to the Jenkins build project at the specific server address. Similarly, executionUrlTemplate is the dynamic link that will be updated with information about the current or most recent run of the action. }); ActionType actionType = response.ActionType; #endregion } public void CodePipelineCreatePipeline() { #region create-a-pipeline-1449162214392 var response = client.CreatePipeline(new CreatePipelineRequest { Pipeline = new PipelineDeclaration { Version = 1, Name = "MySecondPipeline", ArtifactStore = new ArtifactStore { Type = "S3", Location = "codepipeline-us-east-1-11EXAMPLE11" }, RoleArn = "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service", Stages = new List<StageDeclaration> { new StageDeclaration { Name = "Source", Actions = new List<ActionDeclaration> { new ActionDeclaration { Name = "Source", ActionTypeId = new ActionTypeId { Version = "1", Category = "Source", Owner = "AWS", Provider = "S3" }, Configuration = new Dictionary<string, string> { { "S3Bucket", "awscodepipeline-demo-bucket" }, { "S3ObjectKey", "aws-codepipeline-s3-aws-codedeploy_linux.zip" } }, InputArtifacts = new List<InputArtifact> { }, OutputArtifacts = new List<OutputArtifact> { new OutputArtifact { Name = "MyApp" } }, RunOrder = 1 } } }, new StageDeclaration { Name = "Beta", Actions = new List<ActionDeclaration> { new ActionDeclaration { Name = "CodePipelineDemoFleet", ActionTypeId = new ActionTypeId { Version = "1", Category = "Deploy", Owner = "AWS", Provider = "CodeDeploy" }, Configuration = new Dictionary<string, string> { { "ApplicationName", "CodePipelineDemoApplication" }, { "DeploymentGroupName", "CodePipelineDemoFleet" } }, InputArtifacts = new List<InputArtifact> { new InputArtifact { Name = "MyApp" } }, OutputArtifacts = new List<OutputArtifact> { }, RunOrder = 1 } } } } } }); PipelineDeclaration pipeline = response.Pipeline; #endregion } public void CodePipelineDeleteCustomActionType() { #region delete-a-custom-action-1449163239567 var response = client.DeleteCustomActionType(new DeleteCustomActionTypeRequest { Version = "1", // This is the current version number of the custom action. Category = "Build", // This is the type of action that the custom action is, for example build or test. Provider = "MyJenkinsProviderName" // This is the provider of the service used in the custom action. In this example, the custom action is for a Jenkins build, and the name of the provider is the one configured in the AWS CodePipeline Plugin for Jenkins }); #endregion } public void CodePipelineDeletePipeline() { #region delete-a-pipeline-1449163893541 var response = client.DeletePipeline(new DeletePipelineRequest { Name = "MySecondPipeline" // The name of the pipeline to delete. }); #endregion } public void CodePipelineDisableStageTransition() { #region disable-transitions-into-or-out-of-a-stage-1449164517291 var response = client.DisableStageTransition(new DisableStageTransitionRequest { PipelineName = "MyFirstPipeline", Reason = "An example reason", StageName = "Beta", TransitionType = "Inbound" // Valid values are Inbound, which prevents artifacts from transitioning into the stage and being processed by the actions in that stage, or Outbound, which prevents artifacts from transitioning out of the stage after they have been processed by the actions in that stage. }); #endregion } public void CodePipelineEnableStageTransition() { #region enable-transitions-into-or-out-of-a-stage-1449164924423 var response = client.EnableStageTransition(new EnableStageTransitionRequest { PipelineName = "MyFirstPipeline", StageName = "Beta", TransitionType = "Inbound" // Valid values are Inbound, which allows artifacts to transition into the stage and be processed by the actions in that stage, or Outbound, which allows artifacts to transition out of the stage after they have been processed by the actions in that stage. }); #endregion } public void CodePipelineGetJobDetails() { #region get-the-details-of-a-job-1449183680273 var response = client.GetJobDetails(new GetJobDetailsRequest { JobId = "11111111-abcd-1111-abcd-111111abcdef" }); JobDetails jobDetails = response.JobDetails; #endregion } public void CodePipelineGetPipeline() { #region view-the-structure-of-a-pipeline-1449184156329 var response = client.GetPipeline(new GetPipelineRequest { Version = 123, // This is an optional parameter. If you do not specify a version, the most current version of the pipeline structure is returned. Name = "MyFirstPipeline" }); PipelineDeclaration pipeline = response.Pipeline; #endregion } public void CodePipelineGetPipelineState() { #region view-information-about-the-state-of-a-pipeline-1449184486550 var response = client.GetPipelineState(new GetPipelineStateRequest { Name = "MyFirstPipeline" }); DateTime created = response.Created; // The value for created and all other time- and date-related information such as lastStatusChange, is returned in timestamp format. string pipelineName = response.PipelineName; integer pipelineVersion = response.PipelineVersion; List<StageState> stageStates = response.StageStates; DateTime updated = response.Updated; #endregion } public void CodePipelineListActionTypes() { #region view-a-summary-of-all-action-types-associated-with-your-account-1455218918202 var response = client.ListActionTypes(new ListActionTypesRequest { ActionOwnerFilter = "Custom", NextToken = "" }); List<ActionType> actionTypes = response.ActionTypes; string nextToken = response.NextToken; // nextToken is optional. Its operation is reserved for future use. #endregion } public void CodePipelineListPipelines() { #region view-a-summary-of-all-pipelines-associated-with-your-account-1449185747807 var response = client.ListPipelines(new ListPipelinesRequest { }); string nextToken = response.NextToken; List<PipelineSummary> pipelines = response.Pipelines; // Date and time information returned in the pipeline blocks, such as the values for created or updated, are in timestamp format. #endregion } public void CodePipelinePollForJobs() { #region view-any-available-jobs-1449186054484 var response = client.PollForJobs(new PollForJobsRequest { ActionTypeId = new ActionTypeId { Version = "1", Category = "Test", Owner = "Custom", Provider = "MyJenkinsProviderName" }, MaxBatchSize = 5, QueryParam = new Dictionary<string, string> { { "ProjectName", "MyJenkinsTestProj" } } }); List<Job> jobs = response.Jobs; #endregion } public void CodePipelineStartPipelineExecution() { #region run-the-latest-revision-through-a-pipeline-1449186732433 var response = client.StartPipelineExecution(new StartPipelineExecutionRequest { Name = "MyFirstPipeline" }); string pipelineExecutionId = response.PipelineExecutionId; #endregion } public void CodePipelineUpdatePipeline() { #region update-the-structure-of-a-pipeline-1449186881322 var response = client.UpdatePipeline(new UpdatePipelineRequest { Pipeline = new PipelineDeclaration { Version = 2, Name = "MyFirstPipeline", ArtifactStore = new ArtifactStore { Type = "S3", Location = "codepipeline-us-east-1-11EXAMPLE11" }, RoleArn = "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service", Stages = new List<StageDeclaration> { new StageDeclaration { Name = "Source", Actions = new List<ActionDeclaration> { new ActionDeclaration { Name = "Source", ActionTypeId = new ActionTypeId { Version = "1", Category = "Source", Owner = "AWS", Provider = "S3" }, Configuration = new Dictionary<string, string> { { "S3Bucket", "awscodepipeline-demo-bucket2" }, { "S3ObjectKey", "aws-codepipeline-s3-aws-codedeploy_linux.zip" } }, InputArtifacts = new List<InputArtifact> { }, OutputArtifacts = new List<OutputArtifact> { new OutputArtifact { Name = "MyApp" } }, RunOrder = 1 } } }, new StageDeclaration { Name = "Beta", Actions = new List<ActionDeclaration> { new ActionDeclaration { Name = "CodePipelineDemoFleet", ActionTypeId = new ActionTypeId { Version = "1", Category = "Deploy", Owner = "AWS", Provider = "CodeDeploy" }, Configuration = new Dictionary<string, string> { { "ApplicationName", "CodePipelineDemoApplication" }, { "DeploymentGroupName", "CodePipelineDemoFleet" } }, InputArtifacts = new List<InputArtifact> { new InputArtifact { Name = "MyApp" } }, OutputArtifacts = new List<OutputArtifact> { }, RunOrder = 1 } } } } } }); PipelineDeclaration pipeline = response.Pipeline; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
400
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CostAndUsageReport; using Amazon.CostAndUsageReport.Model; namespace AWSSDKDocSamples.Amazon.CostAndUsageReport.Generated { class CostAndUsageReportSamples : ISample { public void CostAndUsageReportDeleteReportDefinition() { #region to-delete-a-report var client = new AmazonCostAndUsageReportClient(); var response = client.DeleteReportDefinition(new DeleteReportDefinitionRequest { ReportName = "ExampleReport" }); #endregion } public void CostAndUsageReportDescribeReportDefinitions() { #region to-retrieve-report-definitions var client = new AmazonCostAndUsageReportClient(); var response = client.DescribeReportDefinitions(new DescribeReportDefinitionsRequest { MaxResults = 5 }); List<ReportDefinition> reportDefinitions = response.ReportDefinitions; #endregion } public void CostAndUsageReportPutReportDefinition() { #region to-create-a-report-definitions var client = new AmazonCostAndUsageReportClient(); var response = client.PutReportDefinition(new PutReportDefinitionRequest { ReportDefinition = new ReportDefinition { AdditionalArtifacts = new List<string> { "REDSHIFT", "QUICKSIGHT" }, AdditionalSchemaElements = new List<string> { "RESOURCES" }, Compression = "ZIP", Format = "textORcsv", ReportName = "ExampleReport", S3Bucket = "example-s3-bucket", S3Prefix = "exampleprefix", S3Region = "us-east-1", TimeUnit = "DAILY" } }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
81
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.DatabaseMigrationService; using Amazon.DatabaseMigrationService.Model; namespace AWSSDKDocSamples.Amazon.DatabaseMigrationService.Generated { class DatabaseMigrationServiceSamples : ISample { public void DatabaseMigrationServiceAddTagsToResource() { #region add-tags-to-resource-1481744141435 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.AddTagsToResource(new AddTagsToResourceRequest { ResourceArn = "arn:aws:dms:us-east-1:123456789012:endpoint:ASXWXJZLNWNT5HTWCGV2BUJQ7E", // Required. Use the ARN of the resource you want to tag. Tags = new List<Tag> { new Tag { Key = "Acount", Value = "1633456" } } // Required. Use the Key/Value pair format. }); #endregion } public void DatabaseMigrationServiceCreateEndpoint() { #region create-endpoint-1481746254348 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.CreateEndpoint(new CreateEndpointRequest { CertificateArn = "", DatabaseName = "testdb", EndpointIdentifier = "test-endpoint-1", EndpointType = "source", EngineName = "mysql", ExtraConnectionAttributes = "", KmsKeyId = "arn:aws:kms:us-east-1:123456789012:key/4c1731d6-5435-ed4d-be13-d53411a7cfbd", Password = "pasword", Port = 3306, ServerName = "mydb.cx1llnox7iyx.us-west-2.rds.amazonaws.com", SslMode = "require", Tags = new List<Tag> { new Tag { Key = "Acount", Value = "143327655" } }, Username = "username" }); Endpoint endpoint = response.Endpoint; #endregion } public void DatabaseMigrationServiceCreateReplicationInstance() { #region create-replication-instance-1481746705295 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.CreateReplicationInstance(new CreateReplicationInstanceRequest { AllocatedStorage = 123, AutoMinorVersionUpgrade = true, AvailabilityZone = "", EngineVersion = "", KmsKeyId = "", MultiAZ = true, PreferredMaintenanceWindow = "", PubliclyAccessible = true, ReplicationInstanceClass = "", ReplicationInstanceIdentifier = "", ReplicationSubnetGroupIdentifier = "", Tags = new List<Tag> { new Tag { Key = "string", Value = "string" } }, VpcSecurityGroupIds = new List<string> { } }); ReplicationInstance replicationInstance = response.ReplicationInstance; #endregion } public void DatabaseMigrationServiceCreateReplicationSubnetGroup() { #region create-replication-subnet-group-1481747297930 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.CreateReplicationSubnetGroup(new CreateReplicationSubnetGroupRequest { ReplicationSubnetGroupDescription = "US West subnet group", ReplicationSubnetGroupIdentifier = "us-west-2ab-vpc-215ds366", SubnetIds = new List<string> { "subnet-e145356n", "subnet-58f79200" }, Tags = new List<Tag> { new Tag { Key = "Acount", Value = "145235" } } }); ReplicationSubnetGroup replicationSubnetGroup = response.ReplicationSubnetGroup; #endregion } public void DatabaseMigrationServiceCreateReplicationTask() { #region create-replication-task-1481747646288 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.CreateReplicationTask(new CreateReplicationTaskRequest { CdcStartTime = new DateTime(2016, 12, 14, 10, 25, 43, DateTimeKind.Utc), MigrationType = "full-load", ReplicationInstanceArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ", ReplicationTaskIdentifier = "task1", ReplicationTaskSettings = "", SourceEndpointArn = "arn:aws:dms:us-east-1:123456789012:endpoint:ZW5UAN6P4E77EC7YWHK4RZZ3BE", TableMappings = "file://mappingfile.json", Tags = new List<Tag> { new Tag { Key = "Acount", Value = "24352226" } }, TargetEndpointArn = "arn:aws:dms:us-east-1:123456789012:endpoint:ASXWXJZLNWNT5HTWCGV2BUJQ7E" }); ReplicationTask replicationTask = response.ReplicationTask; #endregion } public void DatabaseMigrationServiceDeleteCertificate() { #region delete-certificate-1481751957981 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteCertificate(new DeleteCertificateRequest { CertificateArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUSM457DE6XFJCJQ" }); Certificate certificate = response.Certificate; #endregion } public void DatabaseMigrationServiceDeleteConnection() { #region delete-connection-1481751957981 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteConnection(new DeleteConnectionRequest { EndpointArn = "arn:aws:dms:us-east-1:123456789012:endpoint:RAAR3R22XSH46S3PWLC3NJAWKM", ReplicationInstanceArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ" }); Connection connection = response.Connection; #endregion } public void DatabaseMigrationServiceDeleteEndpoint() { #region delete-endpoint-1481752425530 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteEndpoint(new DeleteEndpointRequest { EndpointArn = "arn:aws:dms:us-east-1:123456789012:endpoint:RAAR3R22XSH46S3PWLC3NJAWKM" }); Endpoint endpoint = response.Endpoint; #endregion } public void DatabaseMigrationServiceDeleteReplicationInstance() { #region delete-replication-instance-1481752552839 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteReplicationInstance(new DeleteReplicationInstanceRequest { ReplicationInstanceArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ" }); ReplicationInstance replicationInstance = response.ReplicationInstance; #endregion } public void DatabaseMigrationServiceDeleteReplicationSubnetGroup() { #region delete-replication-subnet-group-1481752728597 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteReplicationSubnetGroup(new DeleteReplicationSubnetGroupRequest { ReplicationSubnetGroupIdentifier = "us-west-2ab-vpc-215ds366" }); #endregion } public void DatabaseMigrationServiceDeleteReplicationTask() { #region delete-replication-task-1481752903506 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DeleteReplicationTask(new DeleteReplicationTaskRequest { ReplicationTaskArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ" }); ReplicationTask replicationTask = response.ReplicationTask; #endregion } public void DatabaseMigrationServiceDescribeAccountAttributes() { #region describe-acount-attributes-1481753085663 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeAccountAttributes(new DescribeAccountAttributesRequest { }); List<AccountQuota> accountQuotas = response.AccountQuotas; #endregion } public void DatabaseMigrationServiceDescribeCertificates() { #region describe-certificates-1481753186244 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeCertificates(new DescribeCertificatesRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); List<Certificate> certificates = response.Certificates; string marker = response.Marker; #endregion } public void DatabaseMigrationServiceDescribeConnections() { #region describe-connections-1481754477953 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeConnections(new DescribeConnectionsRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); List<Connection> connections = response.Connections; string marker = response.Marker; #endregion } public void DatabaseMigrationServiceDescribeEndpoints() { #region describe-endpoints-1481754926060 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeEndpoints(new DescribeEndpointsRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); List<Endpoint> endpoints = response.Endpoints; string marker = response.Marker; #endregion } public void DatabaseMigrationServiceDescribeEndpointTypes() { #region describe-endpoint-types-1481754742591 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeEndpointTypes(new DescribeEndpointTypesRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<SupportedEndpointType> supportedEndpointTypes = response.SupportedEndpointTypes; #endregion } public void DatabaseMigrationServiceDescribeOrderableReplicationInstances() { #region describe-orderable-replication-instances-1481755123669 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeOrderableReplicationInstances(new DescribeOrderableReplicationInstancesRequest { Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<OrderableReplicationInstance> orderableReplicationInstances = response.OrderableReplicationInstances; #endregion } public void DatabaseMigrationServiceDescribeRefreshSchemasStatus() { #region describe-refresh-schema-status-1481755303497 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeRefreshSchemasStatus(new DescribeRefreshSchemasStatusRequest { EndpointArn = "" }); RefreshSchemasStatus refreshSchemasStatus = response.RefreshSchemasStatus; #endregion } public void DatabaseMigrationServiceDescribeReplicationInstances() { #region describe-replication-instances-1481755443952 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeReplicationInstances(new DescribeReplicationInstancesRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<ReplicationInstance> replicationInstances = response.ReplicationInstances; #endregion } public void DatabaseMigrationServiceDescribeReplicationSubnetGroups() { #region describe-replication-subnet-groups-1481755621284 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeReplicationSubnetGroups(new DescribeReplicationSubnetGroupsRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<ReplicationSubnetGroup> replicationSubnetGroups = response.ReplicationSubnetGroups; #endregion } public void DatabaseMigrationServiceDescribeReplicationTasks() { #region describe-replication-tasks-1481755777563 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeReplicationTasks(new DescribeReplicationTasksRequest { Filters = new List<Filter> { new Filter { Name = "string", Values = new List<string> { "string", "string" } } }, Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<ReplicationTask> replicationTasks = response.ReplicationTasks; #endregion } public void DatabaseMigrationServiceDescribeSchemas() { #region describe-schemas-1481755933924 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeSchemas(new DescribeSchemasRequest { EndpointArn = "", Marker = "", MaxRecords = 123 }); string marker = response.Marker; List<string> schemas = response.Schemas; #endregion } public void DatabaseMigrationServiceDescribeTableStatistics() { #region describe-table-statistics-1481756071890 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.DescribeTableStatistics(new DescribeTableStatisticsRequest { Marker = "", MaxRecords = 123, ReplicationTaskArn = "" }); string marker = response.Marker; string replicationTaskArn = response.ReplicationTaskArn; List<TableStatistics> tableStatistics = response.TableStatistics; #endregion } public void DatabaseMigrationServiceImportCertificate() { #region import-certificate-1481756197206 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.ImportCertificate(new ImportCertificateRequest { CertificateIdentifier = "", CertificatePem = "" }); Certificate certificate = response.Certificate; #endregion } public void DatabaseMigrationServiceListTagsForResource() { #region list-tags-for-resource-1481761095501 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "" }); List<Tag> tagList = response.TagList; #endregion } public void DatabaseMigrationServiceModifyEndpoint() { #region modify-endpoint-1481761649937 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.ModifyEndpoint(new ModifyEndpointRequest { CertificateArn = "", DatabaseName = "", EndpointArn = "", EndpointIdentifier = "", EndpointType = "source", EngineName = "", ExtraConnectionAttributes = "", Password = "", Port = 123, ServerName = "", SslMode = "require", Username = "" }); Endpoint endpoint = response.Endpoint; #endregion } public void DatabaseMigrationServiceModifyReplicationInstance() { #region modify-replication-instance-1481761784746 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.ModifyReplicationInstance(new ModifyReplicationInstanceRequest { AllocatedStorage = 123, AllowMajorVersionUpgrade = true, ApplyImmediately = true, AutoMinorVersionUpgrade = true, EngineVersion = "1.5.0", MultiAZ = true, PreferredMaintenanceWindow = "sun:06:00-sun:14:00", ReplicationInstanceArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ", ReplicationInstanceClass = "dms.t2.micro", ReplicationInstanceIdentifier = "test-rep-1", VpcSecurityGroupIds = new List<string> { } }); ReplicationInstance replicationInstance = response.ReplicationInstance; #endregion } public void DatabaseMigrationServiceModifyReplicationSubnetGroup() { #region modify-replication-subnet-group-1481762275392 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.ModifyReplicationSubnetGroup(new ModifyReplicationSubnetGroupRequest { ReplicationSubnetGroupDescription = "", ReplicationSubnetGroupIdentifier = "", SubnetIds = new List<string> { } }); ReplicationSubnetGroup replicationSubnetGroup = response.ReplicationSubnetGroup; #endregion } public void DatabaseMigrationServiceRefreshSchemas() { #region refresh-schema-1481762399111 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.RefreshSchemas(new RefreshSchemasRequest { EndpointArn = "", ReplicationInstanceArn = "" }); RefreshSchemasStatus refreshSchemasStatus = response.RefreshSchemasStatus; #endregion } public void DatabaseMigrationServiceRemoveTagsFromResource() { #region remove-tags-from-resource-1481762571330 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.RemoveTagsFromResource(new RemoveTagsFromResourceRequest { ResourceArn = "arn:aws:dms:us-east-1:123456789012:endpoint:ASXWXJZLNWNT5HTWCGV2BUJQ7E", TagKeys = new List<string> { } }); #endregion } public void DatabaseMigrationServiceStartReplicationTask() { #region start-replication-task-1481762706778 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.StartReplicationTask(new StartReplicationTaskRequest { CdcStartTime = new DateTime(2016, 12, 14, 5, 33, 20, DateTimeKind.Utc), ReplicationTaskArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ", StartReplicationTaskType = "start-replication" }); ReplicationTask replicationTask = response.ReplicationTask; #endregion } public void DatabaseMigrationServiceStopReplicationTask() { #region stop-replication-task-1481762924947 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.StopReplicationTask(new StopReplicationTaskRequest { ReplicationTaskArn = "arn:aws:dms:us-east-1:123456789012:endpoint:ASXWXJZLNWNT5HTWCGV2BUJQ7E" }); ReplicationTask replicationTask = response.ReplicationTask; #endregion } public void DatabaseMigrationServiceTestConnection() { #region test-conection-1481763017636 var client = new AmazonDatabaseMigrationServiceClient(); var response = client.TestConnection(new TestConnectionRequest { EndpointArn = "arn:aws:dms:us-east-1:123456789012:endpoint:RAAR3R22XSH46S3PWLC3NJAWKM", ReplicationInstanceArn = "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ" }); Connection connection = response.Connection; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
702
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.DeviceFarm; using Amazon.DeviceFarm.Model; namespace AWSSDKDocSamples.Amazon.DeviceFarm.Generated { class DeviceFarmSamples : ISample { public void DeviceFarmCreateDevicePool() { #region createdevicepool-example-1470862210860 var client = new AmazonDeviceFarmClient(); var response = client.CreateDevicePool(new CreateDevicePoolRequest { Name = "MyDevicePool", // A device pool contains related devices, such as devices that run only on Android or that run only on iOS. Description = "My Android devices", ProjectArn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the project ARN by using the list-projects CLI command. Rules = new List<Rule> { } }); DevicePool devicePool = response.DevicePool; #endregion } public void DeviceFarmCreateProject() { #region createproject-example-1470862210860 var client = new AmazonDeviceFarmClient(); var response = client.CreateProject(new CreateProjectRequest { Name = "MyProject" // A project in Device Farm is a workspace that contains test runs. A run is a test of a single app against one or more devices. }); Project project = response.Project; #endregion } public void DeviceFarmCreateRemoteAccessSession() { #region to-create-a-remote-access-session-1470970668274 var client = new AmazonDeviceFarmClient(); var response = client.CreateRemoteAccessSession(new CreateRemoteAccessSessionRequest { Name = "MySession", Configuration = new CreateRemoteAccessSessionConfiguration { BillingMethod = "METERED" }, DeviceArn = "arn:aws:devicefarm:us-west-2::device:123EXAMPLE", // You can get the device ARN by using the list-devices CLI command. ProjectArn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command. }); RemoteAccessSession remoteAccessSession = response.RemoteAccessSession; #endregion } public void DeviceFarmCreateUpload() { #region createupload-example-1470864711775 var client = new AmazonDeviceFarmClient(); var response = client.CreateUpload(new CreateUploadRequest { Name = "MyAppiumPythonUpload", Type = "APPIUM_PYTHON_TEST_PACKAGE", ProjectArn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command. }); Upload upload = response.Upload; #endregion } public void DeviceFarmDeleteDevicePool() { #region deletedevicepool-example-1470866975494 var client = new AmazonDeviceFarmClient(); var response = client.DeleteDevicePool(new DeleteDevicePoolRequest { Arn = "arn:aws:devicefarm:us-west-2::devicepool:123-456-EXAMPLE-GUID" // You can get the device pool ARN by using the list-device-pools CLI command. }); #endregion } public void DeviceFarmDeleteProject() { #region deleteproject-example-1470867374212 var client = new AmazonDeviceFarmClient(); var response = client.DeleteProject(new DeleteProjectRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command. }); #endregion } public void DeviceFarmDeleteRemoteAccessSession() { #region to-delete-a-specific-remote-access-session-1470971431677 var client = new AmazonDeviceFarmClient(); var response = client.DeleteRemoteAccessSession(new DeleteRemoteAccessSessionRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:session:EXAMPLE-GUID-123-456" // You can get the remote access session ARN by using the list-remote-access-sessions CLI command. }); #endregion } public void DeviceFarmDeleteRun() { #region deleterun-example-1470867905129 var client = new AmazonDeviceFarmClient(); var response = client.DeleteRun(new DeleteRunRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:run:EXAMPLE-GUID-123-456" // You can get the run ARN by using the list-runs CLI command. }); #endregion } public void DeviceFarmDeleteUpload() { #region deleteupload-example-1470868363942 var client = new AmazonDeviceFarmClient(); var response = client.DeleteUpload(new DeleteUploadRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:upload:EXAMPLE-GUID-123-456" // You can get the upload ARN by using the list-uploads CLI command. }); #endregion } public void DeviceFarmGetAccountSettings() { #region to-get-information-about-account-settings-1472567568189 var client = new AmazonDeviceFarmClient(); var response = client.GetAccountSettings(new GetAccountSettingsRequest { }); AccountSettings accountSettings = response.AccountSettings; #endregion } public void DeviceFarmGetDevice() { #region getdevice-example-1470870602173 var client = new AmazonDeviceFarmClient(); var response = client.GetDevice(new GetDeviceRequest { Arn = "arn:aws:devicefarm:us-west-2::device:123EXAMPLE" }); Device device = response.Device; #endregion } public void DeviceFarmGetDevicePool() { #region getdevicepool-example-1470870873136 var client = new AmazonDeviceFarmClient(); var response = client.GetDevicePool(new GetDevicePoolRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can obtain the project ARN by using the list-projects CLI command. }); DevicePool devicePool = response.DevicePool; #endregion } public void DeviceFarmGetDevicePoolCompatibility() { #region getdevicepoolcompatibility-example-1470925003466 var client = new AmazonDeviceFarmClient(); var response = client.GetDevicePoolCompatibility(new GetDevicePoolCompatibilityRequest { AppArn = "arn:aws:devicefarm:us-west-2::app:123-456-EXAMPLE-GUID", DevicePoolArn = "arn:aws:devicefarm:us-west-2::devicepool:123-456-EXAMPLE-GUID", // You can get the device pool ARN by using the list-device-pools CLI command. TestType = "APPIUM_PYTHON" }); List<DevicePoolCompatibilityResult> compatibleDevices = response.CompatibleDevices; List<DevicePoolCompatibilityResult> incompatibleDevices = response.IncompatibleDevices; #endregion } public void DeviceFarmGetJob() { #region getjob-example-1470928294268 var client = new AmazonDeviceFarmClient(); var response = client.GetJob(new GetJobRequest { Arn = "arn:aws:devicefarm:us-west-2::job:123-456-EXAMPLE-GUID" // You can get the job ARN by using the list-jobs CLI command. }); Job job = response.Job; #endregion } public void DeviceFarmGetOfferingStatus() { #region to-get-status-information-about-device-offerings-1472568124402 var client = new AmazonDeviceFarmClient(); var response = client.GetOfferingStatus(new GetOfferingStatusRequest { NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE=" // A dynamically generated value, used for paginating results. }); Dictionary<string, OfferingStatus> current = response.Current; Dictionary<string, OfferingStatus> nextPeriod = response.NextPeriod; #endregion } public void DeviceFarmGetProject() { #region to-get-a-project-1470975038449 var client = new AmazonDeviceFarmClient(); var response = client.GetProject(new GetProjectRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:5e01a8c7-c861-4c0a-b1d5-12345EXAMPLE" // You can get the project ARN by using the list-projects CLI command. }); Project project = response.Project; #endregion } public void DeviceFarmGetRemoteAccessSession() { #region to-get-a-remote-access-session-1471014119414 var client = new AmazonDeviceFarmClient(); var response = client.GetRemoteAccessSession(new GetRemoteAccessSessionRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:session:EXAMPLE-GUID-123-456" // You can get the remote access session ARN by using the list-remote-access-sessions CLI command. }); RemoteAccessSession remoteAccessSession = response.RemoteAccessSession; #endregion } public void DeviceFarmGetRun() { #region to-get-a-test-run-1471015895657 var client = new AmazonDeviceFarmClient(); var response = client.GetRun(new GetRunRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:run:5e01a8c7-c861-4c0a-b1d5-5ec6e6c6dd23/0fcac17b-6122-44d7-ae5a-12345EXAMPLE" // You can get the run ARN by using the list-runs CLI command. }); Run run = response.Run; #endregion } public void DeviceFarmGetSuite() { #region to-get-information-about-a-test-suite-1471016525008 var client = new AmazonDeviceFarmClient(); var response = client.GetSuite(new GetSuiteRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:suite:EXAMPLE-GUID-123-456" // You can get the suite ARN by using the list-suites CLI command. }); Suite suite = response.Suite; #endregion } public void DeviceFarmGetTest() { #region to-get-information-about-a-specific-test-1471025744238 var client = new AmazonDeviceFarmClient(); var response = client.GetTest(new GetTestRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:test:EXAMPLE-GUID-123-456" // You can get the test ARN by using the list-tests CLI command. }); Test test = response.Test; #endregion } public void DeviceFarmGetUpload() { #region to-get-information-about-a-specific-upload-1471025996221 var client = new AmazonDeviceFarmClient(); var response = client.GetUpload(new GetUploadRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:upload:EXAMPLE-GUID-123-456" // You can get the test ARN by using the list-uploads CLI command. }); Upload upload = response.Upload; #endregion } public void DeviceFarmInstallToRemoteAccessSession() { #region to-install-to-a-remote-access-session-1471634453818 var client = new AmazonDeviceFarmClient(); var response = client.InstallToRemoteAccessSession(new InstallToRemoteAccessSessionRequest { AppArn = "arn:aws:devicefarm:us-west-2:123456789101:app:EXAMPLE-GUID-123-456", RemoteAccessSessionArn = "arn:aws:devicefarm:us-west-2:123456789101:session:EXAMPLE-GUID-123-456" // You can get the remote access session ARN by using the list-remote-access-sessions CLI command. }); Upload appUpload = response.AppUpload; #endregion } public void DeviceFarmListArtifacts() { #region to-list-artifacts-for-a-resource-1471635409527 var client = new AmazonDeviceFarmClient(); var response = client.ListArtifacts(new ListArtifactsRequest { Type = "SCREENSHOT", Arn = "arn:aws:devicefarm:us-west-2:123456789101:run:EXAMPLE-GUID-123-456" // Can also be used to list artifacts for a Job, Suite, or Test ARN. }); #endregion } public void DeviceFarmListDevicePools() { #region to-get-information-about-device-pools-1471635745170 var client = new AmazonDeviceFarmClient(); var response = client.ListDevicePools(new ListDevicePoolsRequest { Type = "PRIVATE", Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command. }); List<DevicePool> devicePools = response.DevicePools; #endregion } public void DeviceFarmListDevices() { #region to-get-information-about-devices-1471641699344 var client = new AmazonDeviceFarmClient(); var response = client.ListDevices(new ListDevicesRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-projects CLI command. }); #endregion } public void DeviceFarmListJobs() { #region to-get-information-about-jobs-1471642228071 var client = new AmazonDeviceFarmClient(); var response = client.ListJobs(new ListJobsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456" // You can get the project ARN by using the list-jobs CLI command. }); #endregion } public void DeviceFarmListOfferings() { #region to-get-information-about-device-offerings-1472562810999 var client = new AmazonDeviceFarmClient(); var response = client.ListOfferings(new ListOfferingsRequest { NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE=" // A dynamically generated value, used for paginating results. }); List<Offering> offerings = response.Offerings; #endregion } public void DeviceFarmListOfferingTransactions() { #region to-get-information-about-device-offering-transactions-1472561712315 var client = new AmazonDeviceFarmClient(); var response = client.ListOfferingTransactions(new ListOfferingTransactionsRequest { NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE=" // A dynamically generated value, used for paginating results. }); List<OfferingTransaction> offeringTransactions = response.OfferingTransactions; #endregion } public void DeviceFarmListProjects() { #region to-get-information-about-a-device-farm-project-1472564014388 var client = new AmazonDeviceFarmClient(); var response = client.ListProjects(new ListProjectsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:7ad300ed-8183-41a7-bf94-12345EXAMPLE", NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Project> projects = response.Projects; #endregion } public void DeviceFarmListRemoteAccessSessions() { #region to-get-information-about-a-remote-access-session-1472581144803 var client = new AmazonDeviceFarmClient(); var response = client.ListRemoteAccessSessions(new ListRemoteAccessSessionsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:session:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the session by using the list-sessions CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE=" // A dynamically generated value, used for paginating results. }); List<RemoteAccessSession> remoteAccessSessions = response.RemoteAccessSessions; #endregion } public void DeviceFarmListRuns() { #region to-get-information-about-test-runs-1472582711069 var client = new AmazonDeviceFarmClient(); var response = client.ListRuns(new ListRunsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:run:5e01a8c7-c861-4c0a-b1d5-5ec6e6c6dd23/0fcac17b-6122-44d7-ae5a-12345EXAMPLE", // You can get the Amazon Resource Name (ARN) of the run by using the list-runs CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Run> runs = response.Runs; #endregion } public void DeviceFarmListSamples() { #region to-get-information-about-samples-1472582847534 var client = new AmazonDeviceFarmClient(); var response = client.ListSamples(new ListSamplesRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Sample> samples = response.Samples; #endregion } public void DeviceFarmListSuites() { #region to-get-information-about-suites-1472583038218 var client = new AmazonDeviceFarmClient(); var response = client.ListSuites(new ListSuitesRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:job:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the job by using the list-jobs CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Suite> suites = response.Suites; #endregion } public void DeviceFarmListTests() { #region to-get-information-about-tests-1472617372212 var client = new AmazonDeviceFarmClient(); var response = client.ListTests(new ListTestsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Test> tests = response.Tests; #endregion } public void DeviceFarmListUniqueProblems() { #region to-get-information-about-unique-problems-1472617781008 var client = new AmazonDeviceFarmClient(); var response = client.ListUniqueProblems(new ListUniqueProblemsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); Dictionary<string, List<UniqueProblem>> uniqueProblems = response.UniqueProblems; #endregion } public void DeviceFarmListUploads() { #region to-get-information-about-uploads-1472617943090 var client = new AmazonDeviceFarmClient(); var response = client.ListUploads(new ListUploadsRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. NextToken = "RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE" // A dynamically generated value, used for paginating results. }); List<Upload> uploads = response.Uploads; #endregion } public void DeviceFarmPurchaseOffering() { #region to-purchase-a-device-slot-offering-1472648146343 var client = new AmazonDeviceFarmClient(); var response = client.PurchaseOffering(new PurchaseOfferingRequest { OfferingId = "D68B3C05-1BA6-4360-BC69-12345EXAMPLE", // You can get the offering ID by using the list-offerings CLI command. Quantity = 1 }); OfferingTransaction offeringTransaction = response.OfferingTransaction; #endregion } public void DeviceFarmRenewOffering() { #region to-renew-a-device-slot-offering-1472648899785 var client = new AmazonDeviceFarmClient(); var response = client.RenewOffering(new RenewOfferingRequest { OfferingId = "D68B3C05-1BA6-4360-BC69-12345EXAMPLE", // You can get the offering ID by using the list-offerings CLI command. Quantity = 1 }); OfferingTransaction offeringTransaction = response.OfferingTransaction; #endregion } public void DeviceFarmScheduleRun() { #region to-schedule-a-test-run-1472652429636 var client = new AmazonDeviceFarmClient(); var response = client.ScheduleRun(new ScheduleRunRequest { Name = "MyRun", DevicePoolArn = "arn:aws:devicefarm:us-west-2:123456789101:pool:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the device pool by using the list-pools CLI command. ProjectArn = "arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456", // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. Test = new ScheduleRunTest { Type = "APPIUM_JAVA_JUNIT", TestPackageArn = "arn:aws:devicefarm:us-west-2:123456789101:test:EXAMPLE-GUID-123-456" } }); Run run = response.Run; #endregion } public void DeviceFarmStopRun() { #region to-stop-a-test-run-1472653770340 var client = new AmazonDeviceFarmClient(); var response = client.StopRun(new StopRunRequest { Arn = "arn:aws:devicefarm:us-west-2:123456789101:run:EXAMPLE-GUID-123-456" // You can get the Amazon Resource Name (ARN) of the test run by using the list-runs CLI command. }); Run run = response.Run; #endregion } public void DeviceFarmUpdateDevicePool() { #region to-update-a-device-pool-1472653887677 var client = new AmazonDeviceFarmClient(); var response = client.UpdateDevicePool(new UpdateDevicePoolRequest { Name = "NewName", Arn = "arn:aws:devicefarm:us-west-2::devicepool:082d10e5-d7d7-48a5-ba5c-12345EXAMPLE", // You can get the Amazon Resource Name (ARN) of the device pool by using the list-pools CLI command. Description = "NewDescription", Rules = new List<Rule> { new Rule { Value = "True", Attribute = "REMOTE_ACCESS_ENABLED", Operator = "EQUALS" } } }); DevicePool devicePool = response.DevicePool; // Note: you cannot update curated device pools. #endregion } public void DeviceFarmUpdateProject() { #region to-update-a-device-pool-1472653887677 var client = new AmazonDeviceFarmClient(); var response = client.UpdateProject(new UpdateProjectRequest { Name = "NewName", Arn = "arn:aws:devicefarm:us-west-2:123456789101:project:8f75187d-101e-4625-accc-12345EXAMPLE" // You can get the Amazon Resource Name (ARN) of the project by using the list-projects CLI command. }); Project project = response.Project; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
687
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; namespace AWSSDKDocSamples.Amazon.DynamoDBv2.Generated { class DynamoDBSamples : ISample { public void DynamoDBBatchGetItem() { #region batch-get-item-1435614252853 var client = new AmazonDynamoDBClient(); var response = client.BatchGetItem(new BatchGetItemRequest { RequestItems = new Dictionary<string, KeysAndAttributes> { { "tablename1", new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue>> { new Dictionary<string, AttributeValue> { { "key1", new AttributeValue { N = "NumberAttributeValue" } } } }, AttributesToGet = new List<string> { "attr1", "attr2" }, ConsistentRead = true, ProjectionExpression = "str1", ExpressionAttributeNames = new Dictionary<string, string> { { "name1", "attr3" }, { "name2", "attr4" } } } }, { "tablename2", new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue>> { new Dictionary<string, AttributeValue> { { "key2", new AttributeValue { BOOL = true } } } }, AttributesToGet = new List<string> { "attr1", "attr2" }, ConsistentRead = false, ProjectionExpression = "str2", ExpressionAttributeNames = new Dictionary<string, string> { { "name1", "attr3" }, { "name2", "attr4" } } } } }, ReturnConsumedCapacity = "NONE" }); Dictionary<string, List<Dictionary<string, AttributeValue>>> responses = response.Responses; List<ConsumedCapacity> consumedCapacity = response.ConsumedCapacity; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
75