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-lambda-dotnet | aws | C# | 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 BlueprintBaseName._1;
public class StepFunctionTasks
{
/// <summary>
/// Default constructor that Lambda will invoke.
/// </summary>
public StepFunctionTasks()
{
}
public State Greeting(State state, ILambdaContext context)
{
state.Message = "Hello";
if(!string.IsNullOrEmpty(state.Name))
{
state.Message += " " + state.Name;
}
// Tell Step Function to wait 5 seconds before calling
state.WaitInSeconds = 5;
return state;
}
public State Salutations(State state, ILambdaContext context)
{
state.Message += ", Goodbye";
if (!string.IsNullOrEmpty(state.Name))
{
state.Message += " " + state.Name;
}
return state;
}
} | 45 |
aws-lambda-dotnet | aws | C# | using Xunit;
using Amazon.Lambda.Core;
using Amazon.Lambda.TestUtilities;
namespace BlueprintBaseName._1.Tests;
public class FunctionTest
{
public FunctionTest()
{
}
[Fact]
public void TestGreeting()
{
TestLambdaContext context = new TestLambdaContext();
StepFunctionTasks functions = new StepFunctionTasks();
var state = new State
{
Name = "MyStepFunctions"
};
state = functions.Greeting(state, context);
Assert.Equal(5, state.WaitInSeconds);
Assert.Equal("Hello MyStepFunctions", state.Message);
}
} | 31 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
// The function handler that will be called for each Lambda event
var handler = (string input, ILambdaContext context) =>
{
return input.ToUpper();
};
// Build the Lambda runtime client passing in the handler to call for each
// event and the JSON serializer to use for translating Lambda JSON documents
// to .NET types.
await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer())
.Build()
.RunAsync(); | 16 |
aws-lambda-dotnet | aws | C# | using System.Net;
using System.Text;
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Runtime;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.ApiGatewayManagementApi;
using Amazon.ApiGatewayManagementApi.Model;
// 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 BlueprintBaseName._1;
public class Functions
{
public const string ConnectionIdField = "connectionId";
private const string TABLE_NAME_ENV = "TABLE_NAME";
/// <summary>
/// DynamoDB table used to store the open connection ids. More advanced use cases could store logged on user map to their connection id to implement direct message chatting.
/// </summary>
string ConnectionMappingTable { get; }
/// <summary>
/// DynamoDB service client used to store and retieve connection information from the ConnectionMappingTable
/// </summary>
IAmazonDynamoDB DDBClient { get; }
/// <summary>
/// Factory func to create the AmazonApiGatewayManagementApiClient. This is needed to created per endpoint of the a connection. It is a factory to make it easy for tests
/// to moq the creation.
/// </summary>
Func<string, IAmazonApiGatewayManagementApi> ApiGatewayManagementApiClientFactory { get; }
/// <summary>
/// Default constructor that Lambda will invoke.
/// </summary>
public Functions()
{
DDBClient = new AmazonDynamoDBClient();
// Grab the name of the DynamoDB from the environment variable setup in the CloudFormation template serverless.template
if(Environment.GetEnvironmentVariable(TABLE_NAME_ENV) == null)
{
throw new ArgumentException($"Missing required environment variable {TABLE_NAME_ENV}");
}
ConnectionMappingTable = Environment.GetEnvironmentVariable(TABLE_NAME_ENV) ?? "";
this.ApiGatewayManagementApiClientFactory = (Func<string, AmazonApiGatewayManagementApiClient>)((endpoint) =>
{
return new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig
{
ServiceURL = endpoint
});
});
}
/// <summary>
/// Constructor used for testing allow tests to pass in moq versions of the service clients.
/// </summary>
/// <param name="ddbClient"></param>
/// <param name="apiGatewayManagementApiClientFactory"></param>
/// <param name="connectionMappingTable"></param>
public Functions(IAmazonDynamoDB ddbClient, Func<string, IAmazonApiGatewayManagementApi> apiGatewayManagementApiClientFactory, string connectionMappingTable)
{
this.DDBClient = ddbClient;
this.ApiGatewayManagementApiClientFactory = apiGatewayManagementApiClientFactory;
this.ConnectionMappingTable = connectionMappingTable;
}
public async Task<APIGatewayProxyResponse> OnConnectHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
try
{
var connectionId = request.RequestContext.ConnectionId;
context.Logger.LogInformation($"ConnectionId: {connectionId}");
var ddbRequest = new PutItemRequest
{
TableName = ConnectionMappingTable,
Item = new Dictionary<string, AttributeValue>
{
{ConnectionIdField, new AttributeValue{ S = connectionId}}
}
};
await DDBClient.PutItemAsync(ddbRequest);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = "Connected."
};
}
catch (Exception e)
{
context.Logger.LogInformation("Error connecting: " + e.Message);
context.Logger.LogInformation(e.StackTrace);
return new APIGatewayProxyResponse
{
StatusCode = 500,
Body = $"Failed to connect: {e.Message}"
};
}
}
public async Task<APIGatewayProxyResponse> SendMessageHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
try
{
// Construct the API Gateway endpoint that incoming message will be broadcasted to.
var domainName = request.RequestContext.DomainName;
var stage = request.RequestContext.Stage;
var endpoint = $"https://{domainName}/{stage}";
context.Logger.LogInformation($"API Gateway management endpoint: {endpoint}");
// The body will look something like this: {"message":"sendmessage", "data":"What are you doing?"}
JsonDocument message = JsonDocument.Parse(request.Body);
// Grab the data from the JSON body which is the message to broadcasted.
JsonElement dataProperty;
if (!message.RootElement.TryGetProperty("data", out dataProperty) || dataProperty.GetString() == null)
{
context.Logger.LogInformation("Failed to find data element in JSON document");
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.BadRequest
};
}
var data = dataProperty.GetString() ?? "";
var stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));
// List all of the current connections. In a more advanced use case the table could be used to grab a group of connection ids for a chat group.
var scanRequest = new ScanRequest
{
TableName = ConnectionMappingTable,
ProjectionExpression = ConnectionIdField
};
var scanResponse = await DDBClient.ScanAsync(scanRequest);
// Construct the IAmazonApiGatewayManagementApi which will be used to send the message to.
var apiClient = ApiGatewayManagementApiClientFactory(endpoint);
// Loop through all of the connections and broadcast the message out to the connections.
var count = 0;
foreach (var item in scanResponse.Items)
{
var postConnectionRequest = new PostToConnectionRequest
{
ConnectionId = item[ConnectionIdField].S,
Data = stream
};
try
{
context.Logger.LogInformation($"Post to connection {count}: {postConnectionRequest.ConnectionId}");
stream.Position = 0;
await apiClient.PostToConnectionAsync(postConnectionRequest);
count++;
}
catch (AmazonServiceException e)
{
// API Gateway returns a status of 410 GONE then the connection is no
// longer available. If this happens, delete the identifier
// from our DynamoDB table.
if (e.StatusCode == HttpStatusCode.Gone)
{
var ddbDeleteRequest = new DeleteItemRequest
{
TableName = ConnectionMappingTable,
Key = new Dictionary<string, AttributeValue>
{
{ConnectionIdField, new AttributeValue {S = postConnectionRequest.ConnectionId}}
}
};
context.Logger.LogInformation($"Deleting gone connection: {postConnectionRequest.ConnectionId}");
await DDBClient.DeleteItemAsync(ddbDeleteRequest);
}
else
{
context.Logger.LogInformation($"Error posting message to {postConnectionRequest.ConnectionId}: {e.Message}");
context.Logger.LogInformation(e.StackTrace);
}
}
}
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = "Data sent to " + count + " connection" + (count == 1 ? "" : "s")
};
}
catch (Exception e)
{
context.Logger.LogInformation("Error disconnecting: " + e.Message);
context.Logger.LogInformation(e.StackTrace);
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.InternalServerError,
Body = $"Failed to send message: {e.Message}"
};
}
}
public async Task<APIGatewayProxyResponse> OnDisconnectHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
try
{
var connectionId = request.RequestContext.ConnectionId;
context.Logger.LogInformation($"ConnectionId: {connectionId}");
var ddbRequest = new DeleteItemRequest
{
TableName = ConnectionMappingTable,
Key = new Dictionary<string, AttributeValue>
{
{ConnectionIdField, new AttributeValue {S = connectionId}}
}
};
await DDBClient.DeleteItemAsync(ddbRequest);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = "Disconnected."
};
}
catch (Exception e)
{
context.Logger.LogInformation("Error disconnecting: " + e.Message);
context.Logger.LogInformation(e.StackTrace);
return new APIGatewayProxyResponse
{
StatusCode = 500,
Body = $"Failed to disconnect: {e.Message}"
};
}
}
} | 251 |
aws-lambda-dotnet | aws | C# | using Xunit;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using Moq;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.ApiGatewayManagementApi;
using Amazon.ApiGatewayManagementApi.Model;
namespace BlueprintBaseName._1.Tests;
public class FunctionsTest
{
public FunctionsTest()
{
}
[Fact]
public async Task TestConnect()
{
Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>();
Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>();
string tableName = "mocktable";
string connectionId = "test-id";
_mockDDBClient.Setup(client => client.PutItemAsync(It.IsAny<PutItemRequest>(), It.IsAny<CancellationToken>()))
.Callback<PutItemRequest, CancellationToken>((request, token) =>
{
Assert.Equal(tableName, request.TableName);
Assert.Equal(connectionId, request.Item[Functions.ConnectionIdField].S);
});
var functions = new Functions(_mockDDBClient.Object, (endpoint) => _mockApiGatewayClient.Object, tableName);
var lambdaContext = new TestLambdaContext();
var request = new APIGatewayProxyRequest
{
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
ConnectionId = connectionId
}
};
var response = await functions.OnConnectHandler(request, lambdaContext);
Assert.Equal(200, response.StatusCode);
}
[Fact]
public async Task TestDisconnect()
{
Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>();
Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>();
string tableName = "mocktable";
string connectionId = "test-id";
_mockDDBClient.Setup(client => client.DeleteItemAsync(It.IsAny<DeleteItemRequest>(), It.IsAny<CancellationToken>()))
.Callback<DeleteItemRequest, CancellationToken>((request, token) =>
{
Assert.Equal(tableName, request.TableName);
Assert.Equal(connectionId, request.Key[Functions.ConnectionIdField].S);
});
var functions = new Functions(_mockDDBClient.Object, (endpoint) => _mockApiGatewayClient.Object, tableName);
var lambdaContext = new TestLambdaContext();
var request = new APIGatewayProxyRequest
{
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
ConnectionId = connectionId
}
};
var response = await functions.OnDisconnectHandler(request, lambdaContext);
Assert.Equal(200, response.StatusCode);
}
[Fact]
public async Task TestSendMessage()
{
Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>();
Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>();
string tableName = "mocktable";
string connectionId = "test-id";
string message = "hello world";
_mockDDBClient.Setup(client => client.ScanAsync(It.IsAny<ScanRequest>(), It.IsAny<CancellationToken>()))
.Callback<ScanRequest, CancellationToken>((request, token) =>
{
Assert.Equal(tableName, request.TableName);
Assert.Equal(Functions.ConnectionIdField, request.ProjectionExpression);
})
.Returns((ScanRequest r, CancellationToken token) =>
{
return Task.FromResult(new ScanResponse
{
Items = new List<Dictionary<string, AttributeValue>>
{
{ new Dictionary<string, AttributeValue>{ {Functions.ConnectionIdField, new AttributeValue { S = connectionId } } } }
}
});
});
Func<string, IAmazonApiGatewayManagementApi> apiGatewayFactory = ((endpoint) =>
{
Assert.Equal("https://test-domain/test-stage", endpoint);
return _mockApiGatewayClient.Object;
});
_mockApiGatewayClient.Setup(client => client.PostToConnectionAsync(It.IsAny<PostToConnectionRequest>(), It.IsAny<CancellationToken>()))
.Callback<PostToConnectionRequest, CancellationToken>((request, token) =>
{
var actualMessage = new StreamReader(request.Data).ReadToEnd();
Assert.Equal(message, actualMessage);
});
var functions = new Functions(_mockDDBClient.Object, apiGatewayFactory, tableName);
var lambdaContext = new TestLambdaContext();
var request = new APIGatewayProxyRequest
{
RequestContext = new APIGatewayProxyRequest.ProxyRequestContext
{
ConnectionId = connectionId,
DomainName = "test-domain",
Stage = "test-stage"
},
Body = "{\"message\":\"sendmessage\", \"data\":\"" + message + "\"}"
};
var response = await functions.SendMessageHandler(request, lambdaContext);
Assert.Equal(200, response.StatusCode);
}
} | 138 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
namespace Packager
{
public abstract class BaseBlueprintPackager
{
protected string _blueprintRoot;
protected IList<string> _excludeBlueprints;
/// <summary>
/// Construct a new BaseBlueprintPackager.
/// </summary>
/// <param name="blueprintRoot">root to look for blueprint-manifest.json in</param>
/// <param name="excludeBlueprints">names of blueprints to exclude from this BaseBlueprintPackager</param>
public BaseBlueprintPackager(string blueprintRoot, IList<string> excludeBlueprints = null)
{
if (excludeBlueprints == null)
{
excludeBlueprints = new List<string>();
}
this._blueprintRoot = blueprintRoot;
this._excludeBlueprints = excludeBlueprints;
}
protected IList<string> SearchForblueprintManifests()
{
var temp = Directory.GetFiles(_blueprintRoot, "blueprint-manifest.json", SearchOption.AllDirectories);
var result = new List<string>();
foreach(string possible in temp)
{
var include = true;
foreach (var excludeBlueprint in _excludeBlueprints)
{
if (Path.GetFileName(Path.GetDirectoryName(possible)) == excludeBlueprint)
{
include = false;
break;
}
}
if (include)
{
result.Add(possible);
}
}
return result;
}
}
} | 59 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Packager
{
public class BlueprintManifest
{
[JsonProperty(PropertyName = "display-name")]
public string DisplayName { get; set; }
[JsonProperty(PropertyName = "system-name")]
public string SystemName { get; set; }
public string Description { get; set; }
[JsonProperty(PropertyName = "sort-order")]
public int SortOrder { get; set; }
public List<string> Tags { get; set; }
[JsonProperty(PropertyName = "hidden-tags")]
public List<string> HiddenTags { get; set; }
}
}
| 26 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Linq;
namespace Packager
{
public class Program
{
public static void Main(string[] args)
{
ProcessArgs(args, out var updateVersions);
var outputDirectory = GetFullPath(@"../../Deployment/Blueprints");
var blueprintPaths = new (string Source, string Output)[] { (Source: GetFullPath(@"../BlueprintDefinitions/vs2022"), Output: "vs2022"), (Source: GetFullPath(@"../BlueprintDefinitions/vs2017"), Output: "vs2017"), (Source: GetFullPath(@"../BlueprintDefinitions/vs2019"), Output: "vs2019") };
try
{
Init(outputDirectory);
foreach(var blueprintPath in blueprintPaths)
{
if (updateVersions)
{
var versionUpdater = new UpdatePackageReferenceVersions(blueprintPath.Source);
versionUpdater.Execute();
}
foreach(var jsonFile in Directory.GetFiles(blueprintPath.Source, "*.*", SearchOption.AllDirectories).Where(x => string.Equals(Path.GetExtension(x), ".json") || string.Equals(Path.GetExtension(x), ".template")))
{
Utilities.FormatJsonFile(jsonFile);
}
var packager = new VSMsbuildBlueprintPackager(blueprintPath.Source, Path.Combine(outputDirectory, new DirectoryInfo(blueprintPath.Output).Name));
packager.Execute();
}
}
catch(Exception e)
{
Console.WriteLine($"Unknown error processing blueprints: {e.Message}");
Console.WriteLine(e.StackTrace);
Environment.Exit(-1);
}
}
private static void ProcessArgs(string[] args, out bool updateVersions)
{
updateVersions = false;
if (args.Length == 1 && args[0] == "--updateVersions")
{
updateVersions = true;
}
else if (args.Length != 0)
{
Console.Error.WriteLine("usage: BlueprintPackager [--updateVersions]");
Console.Error.WriteLine("--updateVersions Run job to automatically update nuget package versions for template projects.");
Environment.Exit(-1);
}
}
public static string GetFullPath(string relativePath)
{
if (Directory.GetCurrentDirectory().Contains("Debug") || Directory.GetCurrentDirectory().Contains("Release"))
relativePath = Path.Combine("../../../", relativePath);
return Path.GetFullPath(relativePath);
}
private static void Init(string outputDirectory)
{
var di = new DirectoryInfo(outputDirectory);
if (di.Exists)
{
di.Delete(true);
}
di.Create();
}
}
}
| 79 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Xml;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Packager
{
public class UpdatePackageReferenceVersions
{
const string MicrosoftAspNetCoreAppVersion = "2.1.4";
const string AWSSDK_VERSION_MANIFEST = "https://raw.githubusercontent.com/aws/aws-sdk-net/master/generator/ServiceModels/_sdk-versions.json";
string BlueprintRoot { get; }
public UpdatePackageReferenceVersions(string blueprintRoot)
{
this.BlueprintRoot = blueprintRoot;
}
public void Execute()
{
var versions = LoadKnownVersions();
ProcessBlueprints(versions);
}
public void ProcessBlueprints(IDictionary<string, string> versions)
{
Console.WriteLine("Updating versions in blueprints");
var projectFiles = GetProjectFiles(this.BlueprintRoot);
foreach (var projectfile in projectFiles)
{
Console.WriteLine($"Processing {projectfile}");
var xdoc = new XmlDocument();
xdoc.Load(projectfile);
bool changed = false;
var packageReferenceNodes = xdoc.SelectNodes("//ItemGroup/PackageReference");
foreach(XmlElement packageReferenceNode in packageReferenceNodes)
{
var packageId = packageReferenceNode.GetAttribute("Include");
var blueprintVersion = packageReferenceNode.GetAttribute("Version");
if (string.IsNullOrEmpty(packageId) || string.IsNullOrEmpty(blueprintVersion) || !versions.ContainsKey(packageId))
continue;
var latestVersion = versions[packageId];
if (string.Equals(latestVersion, blueprintVersion))
continue;
Console.WriteLine($"\tUpdated {packageId}: {blueprintVersion} -> {latestVersion}");
changed = true;
packageReferenceNode.SetAttribute("Version", latestVersion);
}
if(changed)
{
xdoc.Save(projectfile);
}
}
}
public IDictionary<string, string> LoadKnownVersions()
{
Console.WriteLine("Looking up Lambda package version numbers");
var versions = new Dictionary<string, string>();
versions["Microsoft.AspNetCore.App"] = MicrosoftAspNetCoreAppVersion;
var librariesDir = Path.GetFullPath(Path.Combine(this.BlueprintRoot, "../../../Libraries/src"));
var projectFiles = GetProjectFiles(librariesDir);
foreach(var projectfile in projectFiles)
{
var xdoc = new XmlDocument();
xdoc.Load(projectfile);
var packageId = xdoc.SelectSingleNode("//PropertyGroup/PackageId")?.InnerText;
var versionPrefix = xdoc.SelectSingleNode("//PropertyGroup/VersionPrefix")?.InnerText ?? xdoc.SelectSingleNode("//PropertyGroup/Version")?.InnerText;
if(!string.IsNullOrEmpty(packageId) && !string.IsNullOrEmpty(versionPrefix))
{
Console.WriteLine($"\t{packageId}: {versionPrefix}");
versions[packageId] = versionPrefix;
}
}
// Capture version numbers for packages created via a nuspec file like the Amazon.Lambda.Annotations package.
foreach(var nuspecFile in Directory.GetFiles(Path.Combine(this.BlueprintRoot, "../../../Libraries/src"), "*.nuspec"))
{
var xdoc = new XmlDocument();
xdoc.Load(nuspecFile);
var metadata = xdoc.DocumentElement["metadata"];
var packageId = metadata["id"]?.InnerText;
var version = metadata["version"]?.InnerText;
if (!string.IsNullOrEmpty(packageId) && !string.IsNullOrEmpty(version))
{
Console.WriteLine($"\t{packageId}: {version}");
versions[packageId] = version;
}
}
try
{
string jsonContent;
using (var client = new HttpClient())
{
jsonContent = client.GetStringAsync(AWSSDK_VERSION_MANIFEST).Result;
}
var root = JsonConvert.DeserializeObject(jsonContent) as JObject;
var serviceVersions = root["ServiceVersions"] as JObject;
foreach(var service in serviceVersions.Properties())
{
var packageId = "AWSSDK." + service.Name;
var version = service.Value["Version"]?.ToString();
versions[packageId] = version;
}
}
catch(Exception e)
{
if (e is AggregateException)
e = e.InnerException;
Console.WriteLine($"Error fetching version numbers from AWS SDK for .NET: {e.Message}");
}
return versions;
}
public static IEnumerable<string> GetProjectFiles(string directory)
{
var projectFiles = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".csproj") || s.EndsWith(".fsproj"));
return projectFiles;
}
}
}
| 149 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using Newtonsoft.Json;
namespace Packager
{
public static class Utilities
{
public static void ZipCode(string sourceDirectory, string zipArchivePath)
{
sourceDirectory = sourceDirectory.Replace("\\", "/");
using (var stream = File.Open(zipArchivePath, FileMode.Create, FileAccess.Write))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
foreach (var file in Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories))
{
var normalized = file.Replace("\\", "/");
var relativePath = normalized.Substring(sourceDirectory.Length);
if (relativePath.StartsWith("/"))
{
relativePath = relativePath.Substring(1);
}
if (relativePath.StartsWith("bin/") ||
relativePath.Contains("/bin/") ||
relativePath.StartsWith("obj/") ||
relativePath.Contains("/obj/") ||
relativePath.StartsWith(".vs/") ||
relativePath.Contains("/.vs/"))
continue;
var entry = archive.CreateEntry(relativePath);
using (var fileStream = File.OpenRead(file))
using (var entryStream = entry.Open())
{
fileStream.CopyTo(entryStream);
}
}
}
}
public static void FormatJsonFile(string file)
{
var rootObj = JsonConvert.DeserializeObject(File.ReadAllText(file));
var formattedJson = JsonConvert.SerializeObject(rootObj, Formatting.Indented);
File.WriteAllText(file, formattedJson);
}
}
}
| 55 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
namespace Packager
{
public class VSMsbuildBlueprintPackager : BaseBlueprintPackager
{
private static IList<string> ExcludeBlueprints = new List<string>() { };
string _outputDirectory;
public VSMsbuildBlueprintPackager(string blueprintRoot, string outputDirectory)
: base(blueprintRoot, ExcludeBlueprints)
{
_outputDirectory = outputDirectory; // Path.Combine(outputDirectory, "VisualStudioBlueprintsMsbuild");
if(!Directory.Exists(_outputDirectory))
new DirectoryInfo(_outputDirectory).Create();
}
public void Execute()
{
var manifests = SearchForblueprintManifests();
var vsblueprintManifestPath = Path.Combine(_outputDirectory, "vs-lambda-blueprint-manifest.xml");
using (var manifestStream = File.Create(vsblueprintManifestPath))
using (var vsManifestWriter = XmlWriter.Create(manifestStream, new XmlWriterSettings {Indent = true }))
{
vsManifestWriter.WriteStartElement("BlueprintManifest");
vsManifestWriter.WriteElementString("ManifestVersion", "1");
vsManifestWriter.WriteStartElement("Blueprints");
foreach (var manifest in manifests)
{
ProcessblueprintManifest(vsManifestWriter, manifest);
}
vsManifestWriter.WriteEndElement();
vsManifestWriter.WriteEndElement();
}
}
private void ProcessblueprintManifest(XmlWriter vsManifestWriter, string manifest)
{
Console.WriteLine($"Processing blueprint manifest {manifest}");
var blueprintZip = Path.Combine(_outputDirectory, Directory.GetParent(manifest).Name + ".zip");
Utilities.ZipCode(Path.Combine(Directory.GetParent(manifest).FullName, "template"), blueprintZip);
var blueprintManifest = JsonConvert.DeserializeObject<BlueprintManifest>(File.ReadAllText(manifest));
vsManifestWriter.WriteStartElement("Blueprint");
vsManifestWriter.WriteElementString("Name", blueprintManifest.DisplayName);
vsManifestWriter.WriteElementString("Description", blueprintManifest.Description);
vsManifestWriter.WriteElementString("SortOrder", blueprintManifest.SortOrder.ToString());
vsManifestWriter.WriteElementString("File", new FileInfo(blueprintZip).Name);
vsManifestWriter.WriteStartElement("Tags");
foreach (var tag in blueprintManifest.Tags)
{
vsManifestWriter.WriteElementString("Tag", tag);
}
vsManifestWriter.WriteEndElement();
vsManifestWriter.WriteStartElement("HiddenTags");
foreach (var tag in blueprintManifest.HiddenTags)
{
vsManifestWriter.WriteElementString("HiddenTag", tag);
}
vsManifestWriter.WriteEndElement();
vsManifestWriter.WriteEndElement();
}
}
} | 80 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace Infrastructure
{
internal class Configuration
{
public string AccountId { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_ACCOUNT_ID");
public string CodeCommitAccountId { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_CODECOMMIT_ACCOUNT_ID");
public string Region { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_REGION");
public Source Source { get; } = new Source();
public Ecrs Ecrs { get; } = new Ecrs();
public readonly string[] EcrRepositoryNames = Environment.GetEnvironmentVariable("AWS_LAMBDA_ECR_REPOSITORY_NAME")?.Split(";");
public const string ProjectRoot = "LambdaRuntimeDockerfiles/Infrastructure/src/Infrastructure";
public const string ProjectName = "aws-lambda-container-images";
public readonly string[] DockerARM64Images = new string[] { "net6", "net7" };
// DotnetSdkVersions is used to specify a specific version of the .NET SDK to be installed on the CodeBuild image
// The default behavior is to specify a channel and that installs the latest version in that channel
// By specifying a specific .NET SDK version, you override the default channel behavior
public readonly Dictionary<string, string> DotnetSdkVersions = new Dictionary<string, string> { };
public readonly Dictionary<string, string> DockerBuildImages = new Dictionary<string, string> { {"net5", "5.0-buster-slim"}, {"net6", "6.0-bullseye-slim"}, {"net7", "7.0-bullseye-slim"} };
public readonly Dictionary<string, string> BaseImageAMD64Tags = new Dictionary<string, string> { { "net5", "base-image-x86_64" }, { "net6", "contributed-base-image-x86_64" }, { "net7", "contributed-base-image-x86_64" } };
public readonly Dictionary<string, string> BaseImageARM64Tags = new Dictionary<string, string> { { "net5", "base-image-arm64" }, { "net6", "contributed-base-image-arm64" }, { "net7", "contributed-base-image-arm64" } };
public readonly string[] Frameworks = Environment.GetEnvironmentVariable("AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION")?.Split(";");
public readonly string[] Channels = Environment.GetEnvironmentVariable("AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL")?.Split(";");
}
internal class Source
{
public string RepositoryArn { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_SOURCE_REPOSITORY_ARN");
public string BranchName { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_SOURCE_BRANCH_NAME");
}
internal class Ecrs
{
public string Stage { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_STAGE_ECR");
public string Beta { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_BETA_ECRS");
public string Prod { get; } = Environment.GetEnvironmentVariable("AWS_LAMBDA_PROD_ECRS");
}
} | 56 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
| 17 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.CDK;
using Amazon.CDK.AWS.CodeBuild;
using Amazon.CDK.AWS.CodeCommit;
using Amazon.CDK.AWS.CodePipeline;
using Amazon.CDK.AWS.CodePipeline.Actions;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.Pipelines;
using Constructs;
using Action = Amazon.CDK.AWS.CodePipeline.Actions.Action;
using RepositoryProps = Amazon.CDK.AWS.ECR.RepositoryProps;
namespace Infrastructure
{
public class PipelineStack : Stack
{
private const string cdkCliVersion = "2.44.0";
private const string PowershellArm64 = "7.1.3 powershell-7.1.3-linux-arm64.tar.gz";
private const string PowershellAmd64 = "7.1.3 powershell-7.1.3-linux-x64.tar.gz";
private const string BaseImageMultiArch = "contributed-base-image-multi-arch";
internal PipelineStack(
Construct scope,
string id,
string ecrRepositoryName,
string framework,
string channel,
string dockerBuildImage,
Configuration configuration,
IStackProps props = null) : base(scope, id, props)
{
var repository = Repository.FromRepositoryArn(this, "Repository", configuration.Source.RepositoryArn);
var artifactBucket = new Bucket(this, "ArtifactBucket", new BucketProps
{
AutoDeleteObjects = true,
BucketName = $"{id}-{configuration.AccountId}",
EncryptionKey = new Key(this, $"{id}-crossaccountaccess-encryptionkey"),
RemovalPolicy = RemovalPolicy.DESTROY
});
var sourceArtifact = new Artifact_();
var ecrPolicy = new PolicyStatement(new PolicyStatementProps
{
Effect = Effect.ALLOW,
Actions = new[] { "ecr:*" },
Resources = new[] { "*" }
});
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps
{
ActionName = repository.RepositoryName,
Output = sourceArtifact,
Repository = repository,
Branch = configuration.Source.BranchName,
Trigger = CodeCommitTrigger.POLL
});
var basePipeline = new Pipeline(this, "CodePipeline", new PipelineProps
{
PipelineName = id,
RestartExecutionOnUpdate = true,
ArtifactBucket = artifactBucket,
Stages = new StageOptions[] {
new StageOptions
{
StageName = "Source",
Actions = new Action[] { sourceAction }
}
}
});
var environmentVariables =
new Dictionary<string, IBuildEnvironmentVariable>
{
{ "AWS_LAMBDA_PIPELINE_ACCOUNT_ID",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_ACCOUNT_ID") ?? string.Empty } },
{ "AWS_LAMBDA_PIPELINE_CODECOMMIT_ACCOUNT_ID",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_CODECOMMIT_ACCOUNT_ID") ?? string.Empty } },
{ "AWS_LAMBDA_PIPELINE_REGION",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_PIPELINE_REGION") ?? string.Empty } },
{ "AWS_LAMBDA_SOURCE_REPOSITORY_ARN",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_SOURCE_REPOSITORY_ARN") ?? string.Empty } },
{ "AWS_LAMBDA_SOURCE_BRANCH_NAME",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_SOURCE_BRANCH_NAME") ?? string.Empty } },
{ "AWS_LAMBDA_STAGE_ECR",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_STAGE_ECR") ?? string.Empty } },
{ "AWS_LAMBDA_BETA_ECRS",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_BETA_ECRS") ?? string.Empty } },
{ "AWS_LAMBDA_PROD_ECRS",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_PROD_ECRS") ?? string.Empty } },
{ "AWS_LAMBDA_ECR_REPOSITORY_NAME",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_ECR_REPOSITORY_NAME") ?? string.Empty } },
{ "AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION") ?? string.Empty } },
{ "AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL",
new BuildEnvironmentVariable { Type = BuildEnvironmentVariableType.PLAINTEXT, Value =
System.Environment.GetEnvironmentVariable("AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL") ?? string.Empty } },
};
// Self mutation
var pipeline = new CodePipeline(this, "Pipeline", new CodePipelineProps
{
CodePipeline = basePipeline,
// It synthesizes CDK code to cdk.out directory which is picked by SelfMutate stage to mutate the pipeline
Synth = new ShellStep("Synth", new ShellStepProps
{
Input = CodePipelineFileSet.FromArtifact(sourceArtifact),
InstallCommands = new[] { $"npm install -g aws-cdk@{cdkCliVersion}" },
Commands = new[] { $"dotnet build {Configuration.ProjectRoot}", "cdk synth" }
}),
CodeBuildDefaults = new CodeBuildOptions
{
BuildEnvironment = new BuildEnvironment
{
EnvironmentVariables = environmentVariables
}
},
SelfMutationCodeBuildDefaults = new CodeBuildOptions
{
RolePolicy = new PolicyStatement[]
{
new PolicyStatement(new PolicyStatementProps
{
Effect = Effect.ALLOW,
Actions = new[] { "sts:AssumeRole" },
Resources = new[] { $"arn:aws:iam::{configuration.CodeCommitAccountId}:role/*" }
})
}
}
});
pipeline.BuildPipeline();
var stageEcr = GetStageEcr(this, ecrRepositoryName, configuration);
var dockerBuildActions = new List<Action>();
// Stage
// Build AMD64 image
var dockerBuildAmd64 = new Project(this, "DockerBuild-amd64", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerBuild/buildspec.yml"),
Description = $"Builds and pushes image to {stageEcr}",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_STAGE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_ARCHITECTURE", new BuildEnvironmentVariable {Value = "amd64"}},
{"AWS_LAMBDA_POWERSHELL_VERSION", new BuildEnvironmentVariable {Value = PowershellAmd64}},
{"AWS_LAMBDA_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageAMD64Tags[framework]}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION", new BuildEnvironmentVariable {Value = framework}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL", new BuildEnvironmentVariable {Value = channel}},
{"AWS_LAMBDA_DOTNET_SDK_VERSION", new BuildEnvironmentVariable {Value = configuration.DotnetSdkVersions.ContainsKey(framework) ? configuration.DotnetSdkVersions[framework] : string.Empty }}
}
});
dockerBuildAmd64.AddToRolePolicy(ecrPolicy);
dockerBuildActions.Add(new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = dockerBuildAmd64,
ActionName = "amd64"
}));
if (configuration.DockerARM64Images.Contains(framework))
{
// Build ARM64 image
var dockerBuildArm64 = new Project(this, "DockerBuild-arm64", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerBuild/buildspec.yml"),
Description = $"Builds and pushes image to {stageEcr}",
Environment = new BuildEnvironment
{
BuildImage = LinuxArmBuildImage.AMAZON_LINUX_2_STANDARD_1_0,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_STAGE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_ARCHITECTURE", new BuildEnvironmentVariable {Value = "arm64"}},
{"AWS_LAMBDA_POWERSHELL_VERSION", new BuildEnvironmentVariable {Value = PowershellArm64}},
{"AWS_LAMBDA_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageARM64Tags[framework]}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION", new BuildEnvironmentVariable {Value = framework}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL", new BuildEnvironmentVariable {Value = channel}},
{"AWS_LAMBDA_DOTNET_SDK_VERSION", new BuildEnvironmentVariable {Value = configuration.DotnetSdkVersions.ContainsKey(framework) ? configuration.DotnetSdkVersions[framework] : string.Empty }}
}
});
dockerBuildArm64.AddToRolePolicy(ecrPolicy);
dockerBuildActions.Add(new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = dockerBuildArm64,
ActionName = "arm64"
}));
}
basePipeline.AddStage(new StageOptions
{
StageName = "DockerBuild",
Actions = dockerBuildActions.ToArray()
});
// Create multi arch image manifest
var dockerImageManifest = new Project(this, "DockerImageManifest", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerImageManifest/buildspec.yml"),
Description = $"Creates image manifest and pushes to {stageEcr}",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_STAGE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_MULTI_ARCH_IMAGE_TAG", new BuildEnvironmentVariable {Value = BaseImageMultiArch}},
{"AWS_LAMBDA_AMD64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageAMD64Tags[framework]}},
{"AWS_LAMBDA_ARM64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageARM64Tags[framework]}},
{"AWS_LAMBDA_INCLUDE_ARM64", new BuildEnvironmentVariable {Value = configuration.DockerARM64Images.Contains(framework).ToString()}},
}
});
dockerImageManifest.AddToRolePolicy(ecrPolicy);
basePipeline.AddStage(new StageOptions
{
StageName = "DockerImageManifest",
Actions = new Action[] {
new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = dockerImageManifest,
ActionName = "DockerImageManifest"
})
}
});
// Smoke test AMD64 image
var amd64SmokeTests = new Project(this, "SmokeTests-amd64", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/SmokeTests/buildspec.yml"),
Description = "Runs smoke tests on the built image.",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_SOURCE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_SOURCE_IMAGE_TAG", new BuildEnvironmentVariable {Value = BaseImageMultiArch}},
{"AWS_LAMBDA_POWERSHELL_VERSION", new BuildEnvironmentVariable {Value = PowershellAmd64}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION", new BuildEnvironmentVariable {Value = framework}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL", new BuildEnvironmentVariable {Value = channel}},
{"AWS_LAMBDA_DOTNET_BUILD_IMAGE", new BuildEnvironmentVariable {Value = dockerBuildImage}},
{"AWS_LAMBDA_DOTNET_SDK_VERSION", new BuildEnvironmentVariable {Value = configuration.DotnetSdkVersions.ContainsKey(framework) ? configuration.DotnetSdkVersions[framework] : string.Empty }}
}
});
var smokeTestsPolicy = new PolicyStatement(new PolicyStatementProps
{
Effect = Effect.ALLOW,
Actions = new[]
{
"sts:*",
"iam:*",
"ecr:*",
"lambda:*"
},
Resources = new[] { "*" }
});
amd64SmokeTests.AddToRolePolicy(smokeTestsPolicy);
var smokeTestsActions = new List<Action>();
smokeTestsActions.Add(new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = amd64SmokeTests,
ActionName = "amd64"
}));
if (configuration.DockerARM64Images.Contains(framework))
{
// Smoke test ARM64 image
var arm64SmokeTests = new Project(this, "SmokeTests-arm64", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/SmokeTests/buildspec.yml"),
Description = "Runs smoke tests on the built image.",
Environment = new BuildEnvironment
{
BuildImage = LinuxArmBuildImage.AMAZON_LINUX_2_STANDARD_1_0,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_SOURCE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_SOURCE_IMAGE_TAG", new BuildEnvironmentVariable {Value = BaseImageMultiArch}},
{"AWS_LAMBDA_POWERSHELL_VERSION", new BuildEnvironmentVariable {Value = PowershellArm64}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_VERSION", new BuildEnvironmentVariable {Value = framework}},
{"AWS_LAMBDA_DOTNET_FRAMEWORK_CHANNEL", new BuildEnvironmentVariable {Value = channel}},
{"AWS_LAMBDA_DOTNET_BUILD_IMAGE", new BuildEnvironmentVariable {Value = dockerBuildImage}},
{"AWS_LAMBDA_DOTNET_SDK_VERSION", new BuildEnvironmentVariable {Value = configuration.DotnetSdkVersions.ContainsKey(framework) ? configuration.DotnetSdkVersions[framework] : string.Empty }}
}
});
arm64SmokeTests.AddToRolePolicy(smokeTestsPolicy);
smokeTestsActions.Add(new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = arm64SmokeTests,
ActionName = "arm64"
}));
}
basePipeline.AddStage(new StageOptions
{
StageName = "SmokeTests",
Actions = smokeTestsActions.ToArray()
});
// Beta
if (!string.IsNullOrWhiteSpace(configuration.Ecrs.Beta))
{
var betaDockerPush = new Project(this, "Beta-DockerPush", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerPush/buildspec.yml"),
Description = $"Pushes staged image to {configuration.Ecrs.Beta}",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_SOURCE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_DESTINATION_ECRS", new BuildEnvironmentVariable {Value = configuration.Ecrs.Beta}},
{"AWS_LAMBDA_MULTI_ARCH_IMAGE_TAG", new BuildEnvironmentVariable {Value = BaseImageMultiArch}},
{"AWS_LAMBDA_AMD64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageAMD64Tags[framework]}},
{"AWS_LAMBDA_ARM64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageARM64Tags[framework]}},
{"AWS_LAMBDA_INCLUDE_ARM64", new BuildEnvironmentVariable {Value = configuration.DockerARM64Images.Contains(framework).ToString()}},
}
});
betaDockerPush.AddToRolePolicy(ecrPolicy);
basePipeline.AddStage(new StageOptions
{
StageName = "Beta-DockerPush",
Actions = new Action[]
{
new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = betaDockerPush,
ActionName = "DockerPush"
})
}
});
}
// Prod
if (!string.IsNullOrWhiteSpace(configuration.Ecrs.Prod))
{
// Manual Approval
basePipeline.AddStage(new StageOptions
{
StageName = "Prod-ManualApproval",
Actions = new Action[]
{
new ManualApprovalAction(new ManualApprovalActionProps
{
ActionName = "ManualApproval"
})
}
});
var prodDockerPush = new Project(this, "Prod-DockerPush", new ProjectProps
{
BuildSpec = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerPush/buildspec.yml"),
Description = $"Pushes staged image to {configuration.Ecrs.Prod}",
Environment = new BuildEnvironment
{
BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
Privileged = true
},
Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps
{
Repository = repository,
BranchOrRef = configuration.Source.BranchName
}),
EnvironmentVariables = new Dictionary<string, IBuildEnvironmentVariable>
{
{"AWS_LAMBDA_SOURCE_ECR", new BuildEnvironmentVariable {Value = stageEcr}},
{"AWS_LAMBDA_ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {Value = ecrRepositoryName}},
{"AWS_LAMBDA_DESTINATION_ECRS", new BuildEnvironmentVariable {Value = configuration.Ecrs.Prod}},
{"AWS_LAMBDA_MULTI_ARCH_IMAGE_TAG", new BuildEnvironmentVariable {Value = BaseImageMultiArch}},
{"AWS_LAMBDA_AMD64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageAMD64Tags[framework]}},
{"AWS_LAMBDA_ARM64_IMAGE_TAG", new BuildEnvironmentVariable {Value = configuration.BaseImageARM64Tags[framework]}},
{"AWS_LAMBDA_INCLUDE_ARM64", new BuildEnvironmentVariable {Value = configuration.DockerARM64Images.Contains(framework).ToString()}},
}
});
prodDockerPush.AddToRolePolicy(ecrPolicy);
basePipeline.AddStage(new StageOptions
{
StageName = "Prod-DockerPush",
Actions = new Action[]
{
new CodeBuildAction(new CodeBuildActionProps
{
Input = sourceArtifact,
Project = prodDockerPush,
ActionName = "DockerPush"
})
}
});
}
}
private string GetStageEcr(Construct scope, string ecrRepositoryName, Configuration configuration)
{
if (string.IsNullOrWhiteSpace(configuration.Ecrs.Stage))
{
var repository = new Amazon.CDK.AWS.ECR.Repository(scope, "StageEcr", new RepositoryProps
{
RepositoryName = ecrRepositoryName
});
return GetEcr(repository.RepositoryUri);
}
return configuration.Ecrs.Stage;
}
private static string GetEcr(string ecrRepositoryUri)
{
return ecrRepositoryUri.Split('/')[0];
}
}
} | 515 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using Amazon.CDK;
namespace Infrastructure
{
sealed class Program
{
public static void Main(string[] args)
{
var configuration = new Configuration();
var app = new App();
if (configuration.EcrRepositoryNames.Length != configuration.Frameworks.Length &&
configuration.EcrRepositoryNames.Length != configuration.Channels.Length)
throw new ArgumentException(
"There is a mismatch between the number of ECR Repositories, .NET Versions and .NET Channels.");
for (var i = 0; i < configuration.Frameworks.Length; i++)
{
new PipelineStack(app, $"{Configuration.ProjectName}-{configuration.Frameworks[i]}", configuration.EcrRepositoryNames[i], configuration.Frameworks[i], configuration.Channels[i], configuration.DockerBuildImages[configuration.Frameworks[i]], configuration, new StackProps
{
TerminationProtection = true,
Env = new Amazon.CDK.Environment
{
Account = configuration.AccountId,
Region = configuration.Region
}
});
}
app.Synth();
}
}
} | 48 |
aws-lambda-dotnet | 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 Sample
{
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)
{
return input?.ToUpper();
}
}
}
| 28 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Net.Http;
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 ImageFunction
{
internal class Function
{
private const string FailureResult = "FAILURE";
private const string SuccessResult = "SUCCESS";
private const string TestUrl = "https://www.amazon.com";
private static readonly Lazy<string> SevenMbString = new Lazy<string>(() => new string('X', 1024 * 1024 * 7));
#region Test methods
public string ToUpper(string input, ILambdaContext context)
{
return input?.ToUpper();
}
public string Ping(string input)
{
if (input == "ping")
{
return "pong";
}
else
{
throw new Exception($"Expected input: ping but recevied {input}");
}
}
public async Task<string> HttpsWorksAsync()
{
var isSuccess = false;
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(TestUrl);
if (response.IsSuccessStatusCode)
{
isSuccess = true;
}
Console.WriteLine($"Response from HTTP get: {response}");
}
return GetResponse(isSuccess);
}
public async Task<string> ThrowExceptionAsync()
{
// do something async so this function is compiled as async
var dummy = await Task.FromResult("xyz");
throw new Exception("Exception thrown from an async handler.");
}
public void ThrowException()
{
throw new Exception("Exception thrown from a synchronous handler.");
}
public async Task<string> AggregateExceptionNotUnwrappedAsync()
{
// do something async so this function is compiled as async
var dummy = await Task.FromResult("xyz");
throw new AggregateException("AggregateException thrown from an async handler.");
}
public void AggregateExceptionNotUnwrapped()
{
throw new AggregateException("AggregateException thrown from a synchronous handler.");
}
public string TooLargeResponseBody()
{
return SevenMbString.Value;
}
public string VerifyLambdaContext(ILambdaContext lambdaContext)
{
AssertNotNull(lambdaContext.AwsRequestId, nameof(lambdaContext.AwsRequestId));
AssertNotNull(lambdaContext.ClientContext, nameof(lambdaContext.ClientContext));
AssertNotNull(lambdaContext.FunctionName, nameof(lambdaContext.FunctionName));
AssertNotNull(lambdaContext.FunctionVersion, nameof(lambdaContext.FunctionVersion));
AssertNotNull(lambdaContext.Identity, nameof(lambdaContext.Identity));
AssertNotNull(lambdaContext.InvokedFunctionArn, nameof(lambdaContext.InvokedFunctionArn));
AssertNotNull(lambdaContext.Logger, nameof(lambdaContext.Logger));
AssertNotNull(lambdaContext.LogGroupName, nameof(lambdaContext.LogGroupName));
AssertNotNull(lambdaContext.LogStreamName, nameof(lambdaContext.LogStreamName));
AssertTrue(lambdaContext.MemoryLimitInMB >= 128,
$"{nameof(lambdaContext.MemoryLimitInMB)}={lambdaContext.MemoryLimitInMB} is not >= 128");
AssertTrue(lambdaContext.RemainingTime > TimeSpan.Zero,
$"{nameof(lambdaContext.RemainingTime)}={lambdaContext.RemainingTime} is not >= 0");
return GetResponse(true);
}
#endregion
#region Private methods
private static string GetResponse(bool isSuccess)
{
return $"{(isSuccess ? SuccessResult : FailureResult)}";
}
private static void AssertNotNull(object value, string valueName)
{
if (value == null)
{
throw new Exception($"{valueName} cannot be null.");
}
}
private static void AssertTrue(bool value, string errorMessage)
{
if (!value)
{
throw new Exception(errorMessage);
}
}
#endregion
}
}
| 147 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Amazon;
using Amazon.ECR;
using Amazon.ECR.Model;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using Environment = System.Environment;
namespace ImageFunction.SmokeTests
{
public class ImageFunctionTests : IDisposable
{
private static readonly RegionEndpoint TestRegion = RegionEndpoint.USWest2;
private readonly AmazonLambdaClient _lambdaClient;
private readonly AmazonIdentityManagementServiceClient _iamClient;
private readonly string _executionRoleName;
private string _executionRoleArn;
private static readonly string LambdaAssumeRolePolicy =
@"
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Sid"": """",
""Effect"": ""Allow"",
""Principal"": {
""Service"": ""lambda.amazonaws.com""
},
""Action"": ""sts:AssumeRole""
}
]
}".Trim();
private readonly string _functionName;
private readonly string _imageUri;
private const string TestIdentifier = "image-function-tests";
private bool _disposed = false;
public ImageFunctionTests()
{
_executionRoleName = $"{TestIdentifier}-{Guid.NewGuid()}";
_functionName = $"{TestIdentifier}-{Guid.NewGuid()}";
var lambdaConfig = new AmazonLambdaConfig()
{
RegionEndpoint = TestRegion
};
_lambdaClient = new AmazonLambdaClient(lambdaConfig);
_iamClient = new AmazonIdentityManagementServiceClient(TestRegion);
_imageUri = Environment.GetEnvironmentVariable("AWS_LAMBDA_IMAGE_URI");
Assert.NotNull(_imageUri);
SetupAsync().GetAwaiter().GetResult();
}
[Theory]
[InlineData("ImageFunction::ImageFunction.Function::ToUpper", "message", "MESSAGE")]
[InlineData("ImageFunction::ImageFunction.Function::Ping", "ping", "pong")]
[InlineData("ImageFunction::ImageFunction.Function::HttpsWorksAsync", "", "SUCCESS")]
[InlineData("ImageFunction::ImageFunction.Function::VerifyLambdaContext", "", "SUCCESS")]
public async Task SuccessfulTests(string handler, string input, string expectedResponse)
{
await UpdateHandlerAsync(handler);
var payload = JsonConvert.SerializeObject(input);
var invokeResponse = await InvokeFunctionAsync(payload);
Assert.True(invokeResponse.HttpStatusCode == HttpStatusCode.OK);
if(invokeResponse.FunctionError != null)
{
throw new Exception($"Lambda function {handler} failed: {invokeResponse.FunctionError}");
}
await using var responseStream = invokeResponse.Payload;
using var sr = new StreamReader(responseStream);
var responseString = JsonConvert.DeserializeObject<string>(await sr.ReadToEndAsync());
Assert.Equal(expectedResponse, responseString);
}
[Theory]
[InlineData("ImageFunction::ImageFunction.Function::ThrowExceptionAsync", "", "Exception", "Exception thrown from an async handler.")]
[InlineData("ImageFunction::ImageFunction.Function::ThrowException", "", "Exception", "Exception thrown from a synchronous handler.")]
[InlineData("ImageFunction::ImageFunction.Function::AggregateExceptionNotUnwrappedAsync", "", "AggregateException", "AggregateException thrown from an async handler.")]
[InlineData("ImageFunction::ImageFunction.Function::AggregateExceptionNotUnwrapped", "", "AggregateException", "AggregateException thrown from a synchronous handler.")]
[InlineData("ImageFunction::ImageFunction.Function::TooLargeResponseBody", "", "Function.ResponseSizeTooLarge",
"Response payload size exceeded maximum allowed payload size (6291556 bytes).")]
public async Task ExceptionTests(string handler, string input, string expectedErrorType, string expectedErrorMessage)
{
await UpdateHandlerAsync(handler);
var payload = JsonConvert.SerializeObject(input);
var invokeResponse = await InvokeFunctionAsync(payload);
Assert.True(invokeResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);
Assert.True(invokeResponse.FunctionError != null);
await using var responseStream = invokeResponse.Payload;
using var sr = new StreamReader(responseStream);
var exception = (JObject)JsonConvert.DeserializeObject(await sr.ReadToEndAsync());
Assert.Equal(expectedErrorType, exception["errorType"].ToString());
Assert.Equal(expectedErrorMessage, exception["errorMessage"].ToString());
}
private async Task UpdateHandlerAsync(string handler)
{
var updateFunctionConfigurationRequest = new UpdateFunctionConfigurationRequest
{
FunctionName = _functionName,
ImageConfig = new ImageConfig()
{
Command = {handler},
}
};
await _lambdaClient.UpdateFunctionConfigurationAsync(updateFunctionConfigurationRequest);
await WaitUntilHelper.WaitUntil(async () =>
{
var getFunctionRequest = new GetFunctionRequest()
{
FunctionName = _functionName
};
var getFunctionResponse = await _lambdaClient.GetFunctionAsync(getFunctionRequest);
return getFunctionResponse.Configuration.LastUpdateStatus != LastUpdateStatus.Successful;
}, TimeSpan.Zero, TimeSpan.FromMinutes(5), CancellationToken.None);
}
private async Task<InvokeResponse> InvokeFunctionAsync(string payload)
{
var request = new InvokeRequest
{
FunctionName = _functionName,
Payload = string.IsNullOrEmpty(payload) ? null : payload
};
return await _lambdaClient.InvokeAsync(request);
}
#region Setup
private async Task SetupAsync()
{
await CreateRoleAsync();
await CreateFunctionAsync();
}
private async Task CreateFunctionAsync()
{
var tryCount = 3;
while (true)
{
try
{
await _lambdaClient.CreateFunctionAsync(new CreateFunctionRequest
{
FunctionName = _functionName,
Code = new FunctionCode
{
ImageUri = _imageUri
},
MemorySize = 512,
Role = _executionRoleArn,
PackageType = PackageType.Image,
Architectures = new List<string> {GetArchitecture()}
});
break;
}
catch (InvalidParameterValueException)
{
tryCount--;
if (tryCount == 0)
{
throw;
}
// Wait another 5 seconds to let execution role propagate
await Task.Delay(5000);
}
}
var endTime = DateTime.Now.AddSeconds(30);
var isActive = false;
while (DateTime.Now < endTime)
{
var response = await _lambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest
{
FunctionName = _functionName
});
if (response.State == State.Active)
{
isActive = true;
break;
}
await Task.Delay(2000);
}
if (!isActive)
{
throw new Exception($"Timed out trying to create Lambda function {_functionName}");
}
}
private async Task CreateRoleAsync()
{
var response = await _iamClient.CreateRoleAsync(new CreateRoleRequest
{
RoleName = _executionRoleName,
Description = $"Test role for {TestIdentifier}.",
AssumeRolePolicyDocument = LambdaAssumeRolePolicy
});
_executionRoleArn = response.Role.Arn;
// Wait 10 seconds to let execution role propagate
await Task.Delay(10000);
await _iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest
{
RoleName = _executionRoleName,
PolicyArn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
});
// Wait 10 seconds to let execution role propagate
await Task.Delay(10000);
}
private static string GetArchitecture()
{
switch (RuntimeInformation.ProcessArchitecture)
{
case System.Runtime.InteropServices.Architecture.X86:
case System.Runtime.InteropServices.Architecture.X64:
return Amazon.Lambda.Architecture.X86_64;
case System.Runtime.InteropServices.Architecture.Arm:
case System.Runtime.InteropServices.Architecture.Arm64:
return Amazon.Lambda.Architecture.Arm64;
default:
throw new NotImplementedException(RuntimeInformation.ProcessArchitecture.ToString());
}
}
#endregion
#region TearDown
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
// Dispose of managed resources here.
if (disposing)
{
TearDownAsync().GetAwaiter().GetResult();
_lambdaClient?.Dispose();
_iamClient?.Dispose();
}
// Dispose of any unmanaged resources not wrapped in safe handles.
_disposed = true;
}
private async Task TearDownAsync()
{
await DeleteRoleIfExistsAsync();
await DeleteFunctionIfExistsAsync();
}
private async Task DeleteFunctionIfExistsAsync()
{
try
{
await _lambdaClient.DeleteFunctionAsync(new DeleteFunctionRequest
{
FunctionName = _functionName
});
}
catch (ResourceNotFoundException)
{
// No action required
}
}
private async Task DeleteRoleIfExistsAsync()
{
try
{
await _iamClient.DetachRolePolicyAsync(new DetachRolePolicyRequest
{
RoleName = _executionRoleName,
PolicyArn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
});
// Wait 10 seconds to let execution role propagate
await Task.Delay(10000);
await _iamClient.DeleteRoleAsync(new DeleteRoleRequest
{
RoleName = _executionRoleName
});
}
catch (NoSuchEntityException)
{
// No action required
}
}
#endregion
}
} | 345 |
aws-lambda-dotnet | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace ImageFunction.SmokeTests
{
public static class WaitUntilHelper
{
public static async Task WaitUntil(Func<Task<bool>> predicate, TimeSpan frequency, TimeSpan timeout, CancellationToken cancellationToken)
{
var waitTask = Task.Run(async () =>
{
while (await predicate())
{
await Task.Delay(frequency, cancellationToken);
}
});
if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout, cancellationToken)))
{
throw new TimeoutException();
}
}
}
} | 42 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations
{
/// <summary>
/// Indicates that this service parameter will be injected into the Lambda function invocation.
/// </summary>
/// <remarks>
/// Services injected using the FromServices attribute are created within the scope
/// that is created for each Lambda invocation.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromServicesAttribute : Attribute
{
}
} | 16 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations
{
public interface INamedAttribute
{
string Name { get; set; }
}
} | 7 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations
{
/// <summary>
/// Indicates this method should be exposed as a Lambda function
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class LambdaFunctionAttribute : Attribute
{
/// <summary>
/// The name of the CloudFormation resource that is associated with the Lambda function.
/// </summary>
public string ResourceName { get; set; }
/// <summary>
/// The amount of time in seconds that Lambda allows a function to run before stopping it.
/// </summary>
public uint Timeout { get; set; }
/// <summary>
/// The amount of memory available to your Lambda function at runtime.
/// </summary>
public uint MemorySize { get; set; }
/// <summary>
/// The IAM Role assumed by the Lambda function during its execution.
/// </summary>
public string Role { get; set; }
/// <summary>
/// Resource based policies that grants permissions to access other AWS resources.
/// </summary>
public string Policies { get; set; }
/// <inheritdoc cref="LambdaPackageType" />
public LambdaPackageType PackageType { get; set; }
}
} | 39 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations
{
/// <summary>
/// The deployment package type of the Lambda function. The supported values are Zip or Image. The default value is Zip.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html">here</a>
/// </summary>
public enum LambdaPackageType
{
Zip=0,
Image=1
}
} | 12 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations
{
/// <summary>
/// Indicates that the class will be used for registering services that
/// can be injected into Lambda functions.
/// </summary>
/// <remarks>
/// The class should implement a ConfigureServices method that
/// adds one or more services to an IServiceCollection.
/// </remarks>
[AttributeUsage(AttributeTargets.Class)]
public class LambdaStartupAttribute : Attribute
{
}
}
| 18 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Maps this parameter to the HTTP request body
/// </summary>
/// <remarks>
/// If the parameter is a complex type then the request body will be assumed to be JSON and deserialized into the type.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromBodyAttribute : Attribute
{
}
} | 15 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Maps this parameter to an HTTP header value
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromHeaderAttribute : Attribute, INamedAttribute
{
/// <summary>
/// Name of the parameter
/// </summary>
public string Name { get; set; }
}
} | 16 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Maps this parameter to a query string parameter
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromQueryAttribute : Attribute, INamedAttribute
{
/// <summary>
/// Name of the parameter
/// </summary>
public string Name { get; set; }
}
} | 16 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Maps this parameter to a resource path segment
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromRouteAttribute : Attribute, INamedAttribute
{
/// <summary>
/// Name of the parameter
/// </summary>
public string Name { get; set; }
}
} | 16 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Configures the Lambda function to be called from an API Gateway HTTP API
/// </summary>
/// <remarks>
/// The HTTP method, HTTP API payload version and resource path are required to be set on the attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Method)]
public class HttpApiAttribute : Attribute
{
/// <inheritdoc cref="HttpApiVersion"/>
public HttpApiVersion Version { get; set; } = HttpApiVersion.V2;
/// <summary>
/// Resource path
/// </summary>
public string Template { get; set; }
/// <inheritdoc cref="LambdaHttpMethod"/>
public LambdaHttpMethod Method { get; set; }
public HttpApiAttribute(LambdaHttpMethod method, string template)
{
Template = template;
Method = method;
}
}
} | 31 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// The <see href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html#http-api-develop-integrations-lambda.proxy-format">
/// Payload Format Version</see> for an API Gateway HTTP API.
/// </summary>
public enum HttpApiVersion
{
V1,
V2
}
} | 12 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
#if NET6_0_OR_GREATER
using System.Buffers;
using System.Text.Json;
using System.Text.Json.Serialization;
#endif
// This assembly is also used in the source generator which needs the .NET attributes and type infos defined in this project.
// The source generator requires all dependencies to target .NET Standard 2.0 to be compatible with .NET Framework used
// by Visual Studio. Several APIs are used in this file that are not available in .NET Standard 2.0 but the source
// generator doesn't use the methods that use those .NET APIs. Several areas in this file put stub implementations
// for .NET Standard 2.0 to allow the types to be available in the source generator but the implementations
// are not actually called in the source generator.
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// The options used by the IHttpResult to serialize into the required format for the event source of the Lambda funtion.
/// </summary>
public class HttpResultSerializationOptions
{
/// <summary>
/// The API Gateway protocol format used as the event source.
/// </summary>
public enum ProtocolFormat {
/// <summary>
/// Used when a function is defined with the RestApiAttribute.
/// </summary>
RestApi,
/// <summary>
/// Used when a function is defined with the HttpApiAttribute.
/// </summary>
HttpApi
}
/// <summary>
/// The API Gateway protocol version.
/// </summary>
public enum ProtocolVersion {
/// <summary>
/// V1 format for API Gateway Proxy responses. Used for functions defined with RestApiAttribute or HttpApiAttribute with explicit setting to V1.
/// </summary>
V1,
/// <summary>
/// V2 format for API Gateway Proxy responses. Used for functions defined with HttpApiAttribute with an implicit version of an explicit setting to V2.
/// </summary>
V2
}
/// <summary>
/// The API Gateway protocol used as the event source.
/// RestApi -> RestApiAttrbute
/// HttpApi -> HttpApiAttribute
/// </summary>
public ProtocolFormat Format { get; set; }
/// <summary>
/// The API Gateway protocol version used as the event source.
/// V1 -> RestApi or HttpApi specifically set as V1
/// V2 -> HttpApi either implicit or explicit set to V2
/// </summary>
public ProtocolVersion Version { get; set; }
}
/// <summary>
/// If this inteface is returned for an API Gateway Lambda function it will serialize itself to the correct JSON format for the
/// configured event source's protocol format and version.
///
/// Users should use the implementation class HttpResults to construct an instance of IHttpResult with the configured, status code, response body and headers.
/// </summary>
/// <example>
/// return HttpResults.Ok("All Good")
/// .AddHeader("Custom-Header", "FooBar");
///
/// </example>
public interface IHttpResult
{
/// <summary>
/// The Status code of the HttpResult
/// </summary>
HttpStatusCode StatusCode { get; }
/// <summary>
/// Used by the Lambda Annotations framework to serialize the IHttpResult to the correct JSON response.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
Stream Serialize(HttpResultSerializationOptions options);
/// <summary>
/// Add header to the IHttpResult. The AddHeader method can be called multiple times for the same header to add multi values for a header.
/// HTTP header names are case insensitive and the AddHeader method will normalize header name casing by calling ToLower on them.
/// </summary>
/// <param name="name">HTTP header name</param>
/// <param name="value">HTTP header value</param>
/// <returns>The same instance to allow fluent call pattern.</returns>
IHttpResult AddHeader(string name, string value);
}
/// <summary>
/// Implementation class for IHttpResult. Consumers should use one of the static methods to create the a result with the desired status code.
/// </summary>
/// <remarks>
/// If a response body is provided it is format using the following rules:
/// <list type="bullet">
/// <item>
/// <description>For string then returned as is.</description>
/// </item>
/// <item>
/// <description>For Stream, byte[] or IList<byte> the data is consided binary and base 64 encoded.</description>
/// </item>
/// <item>
/// <description>Anything other type is serialized to JSON.</description>
/// </item>
/// </list>
/// </remarks>
/// <example>
/// return HttpResults.Ok("All Good")
/// .AddHeader("Custom-Header", "FooBar");
///
/// </example>
public class HttpResults : IHttpResult
{
private const string HEADER_NAME_CONTENT_TYPE = "content-type";
private const string CONTENT_TYPE_APPLICATION_JSON = "application/json";
private const string CONTENT_TYPE_TEXT_PLAIN = "text/plain";
private const string CONTENT_TYPE_APPLICATION_OCTET_STREAM = "application/octet-stream";
private string _body;
private IDictionary<string, IList<string>> _headers;
private bool _isBase64Encoded;
private string _defaultContentType;
private HttpResults(HttpStatusCode statusCode, object body = null)
{
StatusCode = statusCode;
FormatBody(body);
}
/// <inheritdoc/>
public IHttpResult AddHeader(string name, string value)
{
name = name.ToLower();
if (_headers == null)
{
_headers = new Dictionary<string, IList<string>>();
}
if (!_headers.TryGetValue(name, out var values))
{
values = new List<string>();
_headers[name] = values;
}
values.Add(value);
return this;
}
/// <summary>
/// Creates an IHttpResult for a Accepted (202) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult Accepted(object body = null)
{
return new HttpResults(HttpStatusCode.Accepted, body);
}
/// <summary>
/// Creates an IHttpResult for a Bad Gateway (502) status code.
/// </summary>
/// <returns></returns>
public static IHttpResult BadGateway()
{
return new HttpResults(HttpStatusCode.BadGateway);
}
/// <summary>
/// Creates an IHttpResult for a BadRequest (400) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult BadRequest(object body = null)
{
return new HttpResults(HttpStatusCode.BadRequest, body);
}
/// <summary>
/// Creates an IHttpResult for a Conflict (409) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult Conflict(object body = null)
{
return new HttpResults(HttpStatusCode.Conflict, body);
}
/// <summary>
/// Creates an IHttpResult for a Created (201) status code.
/// </summary>
/// <param name="uri">Optional URI for the created resource. The value is set to the Location response header.</param>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult Created(string uri = null, object body = null)
{
var result = new HttpResults(HttpStatusCode.Created, body);
if (uri != null)
{
result.AddHeader("location", uri);
}
return result;
}
/// <summary>
/// Creates an IHttpResult for a Forbidden (403) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult Forbid(object body = null)
{
return new HttpResults(HttpStatusCode.Forbidden, body);
}
/// <summary>
/// Creates an IHttpResult for an Internal Server Error (500) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult InternalServerError(object body = null)
{
return new HttpResults(HttpStatusCode.InternalServerError, body);
}
/// <summary>
/// Creates an IHttpResult for a NotFound (404) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult NotFound(object body = null)
{
return new HttpResults(HttpStatusCode.NotFound, body);
}
/// <summary>
/// Creates an IHttpResult for a Ok (200) status code.
/// </summary>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult Ok(object body = null)
{
return new HttpResults(HttpStatusCode.OK, body);
}
/// <summary>
/// Creates an IHttpResult for redirect responses.
/// </summary>
/// <remarks>
/// This method uses the same logic for determing the the Http status code as the Microsoft.AspNetCore.Http.TypedResults.Redirect uses.
/// https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.typedresults.redirect
/// </remarks>
/// <param name="uri">The URI to redirect to. The value will be set in the location header.</param>
/// <param name="permanent">Whether the redirect should be a permanet (301) or temporary (302) redirect.</param>
/// <param name="preserveMethod">Whether the request method should be preserved. If set to true use 308 for permanent or 307 for temporary redirects.</param>
/// <returns></returns>
public static IHttpResult Redirect(string uri, bool permanent = false, bool preserveMethod = false)
{
HttpStatusCode code;
if (permanent && preserveMethod)
{
code = (HttpStatusCode)308; // .NET Standard 2.0 does not have the enum value for PermanentRedirect so using direct number;
}
else if (!permanent && preserveMethod)
{
code = HttpStatusCode.TemporaryRedirect;
}
else if (permanent && !preserveMethod)
{
code = HttpStatusCode.MovedPermanently;
}
else
{
code = HttpStatusCode.Redirect;
}
var result = new HttpResults(code, null);
if (uri != null)
{
result.AddHeader("location", uri);
}
return result;
}
/// <summary>
/// Creates an IHttpResult for a Service Unavailable (503) status code.
/// </summary>
/// <param name="delaySeconds">Optional number of seconds to return in a Retry-After header</param>
/// <returns></returns>
public static IHttpResult ServiceUnavailable(int? delaySeconds = null)
{
var result = new HttpResults(HttpStatusCode.ServiceUnavailable);
if (delaySeconds != null && delaySeconds > 0)
{
result.AddHeader("Retry-After", delaySeconds.ToString());
}
return result;
}
/// <summary>
/// Creates an IHttpResult for a Unauthorized (401) status code.
/// </summary>
/// <returns></returns>
public static IHttpResult Unauthorized()
{
return new HttpResults(HttpStatusCode.Unauthorized);
}
/// <summary>
/// Creates an IHttpResult for the specified status code.
/// </summary>
/// <param name="statusCode">Http status code used to create the IHttpResult instance.</param>
/// <param name="body">Optional response body</param>
/// <returns></returns>
public static IHttpResult NewResult(HttpStatusCode statusCode, object body = null)
{
return new HttpResults(statusCode, body);
}
#region Serialization
// See comment in class documentation on the rules for serializing. If any changes are made in this method be sure to update
// the comment above.
private void FormatBody(object body)
{
// See comment at the top about .NET Standard 2.0
#if NETSTANDARD2_0
throw new NotImplementedException();
#else
if (body == null)
return;
if (body is string str)
{
_defaultContentType = CONTENT_TYPE_TEXT_PLAIN;
_body = str;
}
else if (body is Stream stream)
{
_defaultContentType = CONTENT_TYPE_APPLICATION_OCTET_STREAM;
_isBase64Encoded = true;
var buffer = ArrayPool<byte>.Shared.Rent((int)stream.Length);
try
{
var readLength = stream.Read(buffer, 0, buffer.Length);
_body = Convert.ToBase64String(buffer, 0, readLength);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
else if (body is byte[] binaryData)
{
_defaultContentType = CONTENT_TYPE_APPLICATION_OCTET_STREAM;
_isBase64Encoded = true;
_body = Convert.ToBase64String(binaryData, 0, binaryData.Length);
}
else if (body is IList<byte> listBinaryData)
{
_defaultContentType = CONTENT_TYPE_APPLICATION_OCTET_STREAM;
_isBase64Encoded = true;
_body = Convert.ToBase64String(listBinaryData.ToArray(), 0, listBinaryData.Count);
}
else
{
_defaultContentType = CONTENT_TYPE_APPLICATION_JSON;
_body = JsonSerializer.Serialize(body);
}
#endif
}
/// <inheritdoc/>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Serialize the IHttpResult into the expect format for the event source.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public Stream Serialize(HttpResultSerializationOptions options)
{
// See comment at the top about .NET Standard 2.0
#if NETSTANDARD2_0
throw new NotImplementedException();
#else
// If the user didn't explicit set the content type then default to application/json
if(!string.IsNullOrEmpty(_body) && (_headers == null || !_headers.ContainsKey(HEADER_NAME_CONTENT_TYPE)))
{
AddHeader(HEADER_NAME_CONTENT_TYPE, _defaultContentType);
}
var stream = new MemoryStream();
if (options.Format == HttpResultSerializationOptions.ProtocolFormat.RestApi ||
(options.Format == HttpResultSerializationOptions.ProtocolFormat.HttpApi && options.Version == HttpResultSerializationOptions.ProtocolVersion.V1))
{
var response = new APIGatewayV1Response
{
StatusCode = (int)StatusCode,
Body = _body,
MultiValueHeaders = _headers,
IsBase64Encoded = _isBase64Encoded
};
JsonSerializer.Serialize(stream, response);
}
else
{
var response = new APIGatewayV2Response
{
StatusCode = (int)StatusCode,
Body = _body,
Headers = ConvertToV2MultiValueHeaders(_headers),
IsBase64Encoded = _isBase64Encoded
};
JsonSerializer.Serialize(stream, response);
}
stream.Position = 0;
return stream;
#endif
}
/// <summary>
/// The V2 format used by HttpApi handles multi value headers by having the value be comma delimited. This
/// utility method handles converting the collection from the V1 format to the V2.
/// </summary>
/// <param name="v1MultiHeaders"></param>
/// <returns></returns>
private static IDictionary<string, string> ConvertToV2MultiValueHeaders(IDictionary<string, IList<string>> v1MultiHeaders)
{
if (v1MultiHeaders == null)
return null;
var v2MultiHeaders = new Dictionary<string, string>();
foreach (var kvp in v1MultiHeaders)
{
var values = string.Join(",", kvp.Value);
v2MultiHeaders[kvp.Key] = values;
}
return v2MultiHeaders;
}
// See comment at the top about .NET Standard 2.0
#if !NETSTANDARD2_0
// Class representing the V1 API Gateway response. Very similiar to Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse but this library can
// not take a dependency on Amazon.Lambda.APIGatewayEvents so it has to have its own version.
private class APIGatewayV1Response
{
[JsonPropertyName("statusCode")]
public int StatusCode { get; set; }
[JsonPropertyName("multiValueHeaders")]
public IDictionary<string, IList<string>> MultiValueHeaders { get; set; }
[JsonPropertyName("body")]
public string Body { get; set; }
[JsonPropertyName("isBase64Encoded")]
public bool IsBase64Encoded { get; set; }
}
// Class representing the V2 API Gateway response. Very similiar to Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse but this library can
// not take a dependency on Amazon.Lambda.APIGatewayEvents so it has to have its own version.
private class APIGatewayV2Response
{
[JsonPropertyName("statusCode")]
public int StatusCode { get; set; }
[JsonPropertyName("headers")]
public IDictionary<string, string> Headers { get; set; }
public string[] Cookies { get; set; }
[JsonPropertyName("body")]
public string Body { get; set; }
[JsonPropertyName("isBase64Encoded")]
public bool IsBase64Encoded { get; set; }
}
#endif
#endregion
}
} | 507 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// HTTP Method/Verb
/// </summary>
public enum LambdaHttpMethod
{
Any,
Get,
Post,
Put,
Patch,
Head,
Delete,
Options
}
} | 17 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Configures the Lambda function to be called from an API Gateway REST API
/// </summary>
/// <remarks>
/// The HTTP method and resource path are required to be set on the attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Method)]
public class RestApiAttribute : Attribute
{
/// <summary>
/// Resource path
/// </summary>
public string Template { get; set; }
/// <inheritdoc cref="LambdaHttpMethod" />
public LambdaHttpMethod Method { get; set; }
public RestApiAttribute(LambdaHttpMethod method, string template)
{
Template = template;
Method = method;
}
}
} | 28 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations.SourceGenerator
{
/// <summary>
/// Specifies the format for the CloudFormation template.
/// </summary>
public enum CloudFormationTemplateFormat
{
Json,
Yaml
}
} | 11 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
/// <summary>
/// This class contains utility methods to determine the .NET project's root directory and resolve the AWS serverless template file path.
/// </summary>
public class CloudFormationTemplateHandler
{
private const string DEFAULT_CONFIG_FILE_NAME = "aws-lambda-tools-defaults.json";
private const string DEFAULT_SERVERLESS_TEMPLATE_NAME = "serverless.template";
private readonly IFileManager _fileManager;
private readonly IDirectoryManager _directoryManager;
public CloudFormationTemplateHandler(IFileManager fileManager, IDirectoryManager directoryManager)
{
_fileManager = fileManager;
_directoryManager = directoryManager;
}
/// <summary>
/// This method takes any file path in the customer's .NET project and resolves the path to the .csproj file.
/// </summary>
/// <remarks>
/// This is the first .csproj file we find searching upward from the source file, where there
/// is only a single .csproj in the current directory.
/// </remarks>
/// <returns>The .NET project path</returns>
public string DetermineProjectPath(string sourceFilePath)
{
if (!_fileManager.Exists(sourceFilePath))
return string.Empty;
var directoryPath = _directoryManager.GetDirectoryName(sourceFilePath);
while (!string.IsNullOrEmpty(directoryPath))
{
var csprojFilesInDirectory = _directoryManager.GetFiles(directoryPath, "*.csproj");
if (csprojFilesInDirectory.Length == 1)
{
return csprojFilesInDirectory[0];
}
directoryPath = _directoryManager.GetDirectoryName(directoryPath);
}
return string.Empty;
}
/// <summary>
/// Determines the path to the AWS serverless template file.
/// If the file does not exist then an empty file is created before returning the path.
/// </summary>
public string FindTemplate(string projectRootDirectory)
{
var templateAbsolutePath = DetermineTemplatePath(projectRootDirectory);
if (!_fileManager.Exists(templateAbsolutePath))
_fileManager.Create(templateAbsolutePath).Close();
return templateAbsolutePath;
}
/// <summary>
/// Checks if the AWS serverless template file exists.
/// </summary>
public bool DoesTemplateExist(string projectRootDirectory)
{
var templateAbsolutePath = DetermineTemplatePath(projectRootDirectory);
return _fileManager.Exists(templateAbsolutePath);
}
/// <summary>
/// Determines the file format of the AWS serverless template.
/// If the template does not exist or if the template is empty, then by default <see cref="CloudFormationTemplateFormat.Json"/> is returned.
/// </summary>
public CloudFormationTemplateFormat DetermineTemplateFormat(string templatePath)
{
if (!_fileManager.Exists(templatePath))
{
return CloudFormationTemplateFormat.Json;
}
var content = _fileManager.ReadAllText(templatePath);
content = content.Trim();
if (string.IsNullOrEmpty(content))
{
return CloudFormationTemplateFormat.Json;
}
return content[0] == '{' ? CloudFormationTemplateFormat.Json : CloudFormationTemplateFormat.Yaml;
}
/// <summary>
/// This is a helper method to determine the path to the AWS serverless template file.
/// It will first look for <see cref="DEFAULT_CONFIG_FILE_NAME"/> inside the project root directory and will try to resolve the template file path from the `template` property.
/// If <see cref="DEFAULT_CONFIG_FILE_NAME"/> does not exist or if the 'template' property is not found, then default to projectRootDirectory/<see cref="DEFAULT_SERVERLESS_TEMPLATE_NAME"/>
/// </summary>
private string DetermineTemplatePath(string projectRootDirectory)
{
if (!_directoryManager.Exists(projectRootDirectory))
throw new DirectoryNotFoundException("Failed to find the project root directory");
var templateAbsolutePath = string.Empty;
var defaultConfigFile = _directoryManager.GetFiles(projectRootDirectory, DEFAULT_CONFIG_FILE_NAME, SearchOption.AllDirectories)
.FirstOrDefault();
if (_fileManager.Exists(defaultConfigFile))
// the templateAbsolutePath will be empty if the template property is not found in the default config file
templateAbsolutePath = GetTemplatePathFromDefaultConfigFile(defaultConfigFile);
// if the default config file does not exist or if the template property is not found in the default config file
// set the template path inside the project root directory.
if (string.IsNullOrEmpty(templateAbsolutePath))
templateAbsolutePath = Path.Combine(projectRootDirectory, DEFAULT_SERVERLESS_TEMPLATE_NAME);
return templateAbsolutePath;
}
/// <summary>
/// This method parses the default config file and tries to resolve the serverless template path from the 'template' property.
/// </summary>
private string GetTemplatePathFromDefaultConfigFile(string defaultConfigFile)
{
JToken rootToken;
try
{
rootToken = JObject.Parse(_fileManager.ReadAllText(defaultConfigFile));
}
catch (Exception)
{
return string.Empty;
}
var templateRelativePath = rootToken["template"]?
.ToObject<string>()?
.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
if (string.IsNullOrEmpty(templateRelativePath))
return string.Empty;
var templateAbsolutePath = Path.Combine(_directoryManager.GetDirectoryName(defaultConfigFile), templateRelativePath);
return templateAbsolutePath;
}
}
} | 151 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Amazon.Lambda.Annotations.SourceGenerator.Diagnostics;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Amazon.Lambda.Annotations.SourceGenerator.Templates;
using Amazon.Lambda.Annotations.SourceGenerator.Writers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
[Generator]
public class Generator : ISourceGenerator
{
private readonly IFileManager _fileManager = new FileManager();
private readonly IDirectoryManager _directoryManager = new DirectoryManager();
// Only allow alphanumeric characters
private readonly Regex _resourceNameRegex = new Regex("^[a-zA-Z0-9]+$");
public Generator()
{
#if DEBUG
//if (!Debugger.IsAttached)
//{
// Debugger.Launch();
//}
#endif
}
public void Execute(GeneratorExecutionContext context)
{
var diagnosticReporter = new DiagnosticReporter(context);
try
{
// retrieve the populated receiver
if (!(context.SyntaxContextReceiver is SyntaxReceiver receiver))
{
return;
}
// Check to see if any of the current syntax trees has any error diagnostics. If so
// Skip generation. We only want to sync the CloudFormation template if the project
// can compile.
foreach(var syntaxTree in context.Compilation.SyntaxTrees)
{
if(syntaxTree.GetDiagnostics().Any(x => x.Severity == DiagnosticSeverity.Error))
{
return;
}
}
// If no project directory was detected then skip the generator.
// This is most likely to happen when the project is empty and doesn't have any classes in it yet.
if(string.IsNullOrEmpty(receiver.ProjectDirectory))
{
return;
}
var semanticModelProvider = new SemanticModelProvider(context);
if (receiver.StartupClasses.Count > 1)
{
foreach (var startup in receiver.StartupClasses)
{
// If there are more than one startup class, report them as errors
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MultipleStartupNotAllowed,
Location.Create(startup.SyntaxTree, startup.Span),
startup.SyntaxTree.FilePath));
}
}
var configureMethodModel = semanticModelProvider.GetConfigureMethodModel(receiver.StartupClasses.FirstOrDefault());
var annotationReport = new AnnotationReport();
var templateHandler = new CloudFormationTemplateHandler(_fileManager, _directoryManager);
bool foundFatalError = false;
foreach (var lambdaMethod in receiver.LambdaMethods)
{
var lambdaMethodModel = semanticModelProvider.GetMethodSemanticModel(lambdaMethod);
if (!HasSerializerAttribute(context, lambdaMethodModel))
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MissingLambdaSerializer,
lambdaMethod.GetLocation()));
foundFatalError = true;
continue;
}
// Check for necessary references
if (lambdaMethodModel.HasAttribute(context, TypeFullNames.RestApiAttribute)
|| lambdaMethodModel.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
// Check for arbitrary type from "Amazon.Lambda.APIGatewayEvents"
if (context.Compilation.ReferencedAssemblyNames.FirstOrDefault(x => x.Name == "Amazon.Lambda.APIGatewayEvents") == null)
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MissingDependencies,
lambdaMethod.GetLocation(),
"Amazon.Lambda.APIGatewayEvents"));
foundFatalError = true;
continue;
}
}
var model = LambdaFunctionModelBuilder.Build(lambdaMethodModel, configureMethodModel, context);
// If there are more than one event, report them as errors
if (model.LambdaMethod.Events.Count > 1)
{
foreach (var attribute in lambdaMethodModel.GetAttributes().Where(attribute => TypeFullNames.Events.Contains(attribute.AttributeClass.ToDisplayString())))
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MultipleEventsNotSupported,
Location.Create(attribute.ApplicationSyntaxReference.SyntaxTree, attribute.ApplicationSyntaxReference.Span),
DiagnosticSeverity.Error));
}
foundFatalError = true;
// Skip multi-event lambda method from processing and check remaining lambda methods for diagnostics
continue;
}
if(model.LambdaMethod.ReturnsIHttpResults && !model.LambdaMethod.Events.Contains(EventType.API))
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.HttpResultsOnNonApiFunction,
Location.Create(lambdaMethod.SyntaxTree, lambdaMethod.Span),
DiagnosticSeverity.Error));
foundFatalError = true;
continue;
}
if (!_resourceNameRegex.IsMatch(model.ResourceName))
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.InvalidResourceName,
Location.Create(lambdaMethod.SyntaxTree, lambdaMethod.Span),
DiagnosticSeverity.Error));
foundFatalError = true;
continue;
}
if (!AreLambdaMethodParamatersValid(lambdaMethod, model, diagnosticReporter))
{
foundFatalError = true;
continue;
}
var template = new LambdaFunctionTemplate(model);
string sourceText;
try
{
sourceText = template.TransformText().ToEnvironmentLineEndings();
context.AddSource($"{model.GeneratedMethod.ContainingType.Name}.g.cs", SourceText.From(sourceText, Encoding.UTF8, SourceHashAlgorithm.Sha256));
}
catch (Exception e) when (e is NotSupportedException || e is InvalidOperationException)
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGenerationFailed, Location.Create(lambdaMethod.SyntaxTree, lambdaMethod.Span), e.Message));
return;
}
// report every generated file to build output
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGeneration, Location.None, $"{model.GeneratedMethod.ContainingType.Name}.g.cs", sourceText));
annotationReport.LambdaFunctions.Add(model);
}
// Run the CloudFormation sync if any LambdaMethods exists. Also run if no LambdaMethods exists but there is a
// CloudFormation template in case orphaned functions in the template need to be removed.
// Both checks are required because if there is no template but there are LambdaMethods the CF template the template will be created.
if (!foundFatalError && (receiver.LambdaMethods.Any() || templateHandler.DoesTemplateExist(receiver.ProjectDirectory)))
{
annotationReport.CloudFormationTemplatePath = templateHandler.FindTemplate(receiver.ProjectDirectory);
annotationReport.ProjectRootDirectory = receiver.ProjectDirectory;
annotationReport.IsTelemetrySuppressed = ProjectFileHandler.IsTelemetrySuppressed(receiver.ProjectPath, _fileManager);
var templateFormat = templateHandler.DetermineTemplateFormat(annotationReport.CloudFormationTemplatePath);
ITemplateWriter templateWriter;
if (templateFormat == CloudFormationTemplateFormat.Json)
{
templateWriter = new JsonWriter();
}
else
{
templateWriter = new YamlWriter();
}
var cloudFormationWriter = new CloudFormationWriter(_fileManager, _directoryManager, templateWriter, diagnosticReporter);
cloudFormationWriter.ApplyReport(annotationReport);
}
}
catch (Exception e)
{
// this is a generator failure, report this as error
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.UnhandledException, Location.None, e.PrettyPrint()));
#if DEBUG
throw;
#endif
}
}
private bool HasSerializerAttribute(GeneratorExecutionContext context, IMethodSymbol methodModel)
{
return methodModel.ContainingAssembly.HasAttribute(context, TypeFullNames.LambdaSerializerAttribute);
}
public void Initialize(GeneratorInitializationContext context)
{
// Register a syntax receiver that will be created for each generation pass
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver(_fileManager, _directoryManager));
}
private bool AreLambdaMethodParamatersValid(MethodDeclarationSyntax declarationSyntax, LambdaFunctionModel model, DiagnosticReporter diagnosticReporter)
{
var isValid = true;
foreach (var parameter in model.LambdaMethod.Parameters)
{
if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromQueryAttribute))
{
var fromQueryAttribute = parameter.Attributes.First(att => att.Type.FullName == TypeFullNames.FromQueryAttribute) as AttributeModel<APIGateway.FromQueryAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var parameterKey = fromQueryAttribute?.Data?.Name ?? parameter.Name;
if (!parameter.Type.IsPrimitiveType() && !parameter.Type.IsPrimitiveEnumerableType())
{
isValid = false;
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.UnsupportedMethodParamaterType,
Location.Create(declarationSyntax.SyntaxTree, declarationSyntax.Span),
parameterKey, parameter.Type.FullName));
}
}
}
return isValid;
}
}
} | 247 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations.SourceGenerator
{
/// <summary>
/// Contains namespace constants.
/// </summary>
public static class Namespaces
{
public static string Annotations = "Amazon.Lambda.Annotations";
}
} | 10 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using System;
using System.Xml;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
/// <summary>
/// Utilities for working with project (.csproj) files
/// </summary>
public class ProjectFileHandler
{
private const string OptOutNodeXpath = "//PropertyGroup/AWSSuppressLambdaAnnotationsTelemetry";
/// <summary>
/// Determines if the project has opted out of any Lambda Annotations telemetry
/// </summary>
/// <param name="projectFilePath">Path to a .csproj file</param>
/// <param name="fileManager">FileManager instance used to read the csproj contents</param>
/// <returns>True if opted out of telemetry, false otherwise</returns>
public static bool IsTelemetrySuppressed(string projectFilePath, IFileManager fileManager)
{
// If we were unable to find the csproj file, treat as if not opted out
if (string.IsNullOrEmpty(projectFilePath))
{
return false;
}
var projectfileContent = fileManager.ReadAllText(projectFilePath);
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(projectfileContent);
var optOutNode = xmlDoc.SelectSingleNode(OptOutNodeXpath) as XmlElement;
if (optOutNode != null && !string.IsNullOrEmpty(optOutNode.InnerText))
{
if (string.Equals("true", optOutNode.InnerText, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
| 47 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
public class SemanticModelProvider
{
private readonly GeneratorExecutionContext _context;
public SemanticModelProvider(GeneratorExecutionContext context)
{
_context = context;
}
/// <summary>
/// Returns the Configure(IServiceCollection) method's semantic model in the LambdaStartup attributed class.
/// If <see cref="startupSyntax"/> is null, returns null.
/// </summary>
/// <param name="startupSyntax">LambdaStartup attributed class syntax</param>
public IMethodSymbol GetConfigureMethodModel(ClassDeclarationSyntax startupSyntax)
{
if (startupSyntax == null)
{
return null;
}
IMethodSymbol configureMethodSymbol = null;
var iServiceCollectionSymbol = _context.Compilation.GetTypeByMetadataName("Microsoft.Extensions.DependencyInjection.IServiceCollection");
var classModel = _context.Compilation.GetSemanticModel(startupSyntax.SyntaxTree);
// Filter the methods which can potentially have Configure(IServiceCollection) parameter signature
var members = startupSyntax.Members.Where(member => member.Kind() == SyntaxKind.MethodDeclaration);
foreach (var member in members)
{
var methodSyntax = (MethodDeclarationSyntax) member;
var methodSymbol = classModel.GetDeclaredSymbol(methodSyntax);
if (methodSymbol != null
&& methodSymbol.Name == "ConfigureServices"
&& methodSymbol.Parameters.Count() == 1
&& methodSymbol.Parameters[0].Type
.Equals(iServiceCollectionSymbol, SymbolEqualityComparer.Default))
{
configureMethodSymbol = methodSymbol;
break;
}
}
return configureMethodSymbol;
}
/// <summary>
/// Returns semantic model of <see cref="syntax"/>
/// </summary>
/// <param name="syntax">Method declaration syntax used for representing method by compiler.</param>
public IMethodSymbol GetMethodSemanticModel(MethodDeclarationSyntax syntax)
{
var methodModel = _context.Compilation.GetSemanticModel(syntax.SyntaxTree);
return methodModel.GetDeclaredSymbol(syntax);
}
}
} | 68 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
internal class SyntaxReceiver : ISyntaxContextReceiver
{
public List<MethodDeclarationSyntax> LambdaMethods { get; } = new List<MethodDeclarationSyntax>();
public List<ClassDeclarationSyntax> StartupClasses { get; private set; } = new List<ClassDeclarationSyntax>();
/// <summary>
/// Path to the directory containing the .csproj file
/// </summary>
public string ProjectDirectory
{
get
{
return _directoryManager.GetDirectoryName(ProjectPath);
}
}
/// <summary>
/// Path to the .csproj file
/// </summary>
public string ProjectPath { get; private set; }
private readonly IFileManager _fileManager;
private readonly IDirectoryManager _directoryManager;
public SyntaxReceiver(IFileManager fileManager, IDirectoryManager directoryManager)
{
_fileManager = fileManager;
_directoryManager = directoryManager;
}
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if(this.ProjectDirectory == null && context.Node is ClassDeclarationSyntax)
{
var templateHandler = new CloudFormationTemplateHandler(_fileManager, _directoryManager);
this.ProjectPath = templateHandler.DetermineProjectPath(context.Node.SyntaxTree.FilePath);
}
// any method with at least one attribute is a candidate of function generation
if (context.Node is MethodDeclarationSyntax methodDeclarationSyntax && methodDeclarationSyntax.AttributeLists.Count > 0)
{
// Get the symbol being declared by the method, and keep it if its annotated
var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclarationSyntax);
if (methodSymbol.GetAttributes().Any(attr => attr.AttributeClass.Name == nameof(LambdaFunctionAttribute)))
{
LambdaMethods.Add(methodDeclarationSyntax);
}
}
// any class with at least one attribute is a candidate of Startup class
if (context.Node is ClassDeclarationSyntax classDeclarationSyntax && classDeclarationSyntax.AttributeLists.Count > 0)
{
// Get the symbol being declared by the class, and keep it if its annotated
var methodSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax);
if (methodSymbol.GetAttributes().Any(attr => attr.AttributeClass.Name == nameof(LambdaStartupAttribute)))
{
StartupClasses.Add(classDeclarationSyntax);
}
}
}
}
} | 72 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
namespace Amazon.Lambda.Annotations.SourceGenerator
{
/// <summary>
/// Contains fully qualified name constants for various C# types
/// </summary>
public static class TypeFullNames
{
public const string IEnumerable = "System.Collections.IEnumerable";
public const string Task1 = "System.Threading.Tasks.Task`1";
public const string Task = "System.Threading.Tasks.Task";
public const string MemoryStream = "System.IO.MemoryStream";
public const string Stream = "System.IO.Stream";
public const string ILambdaContext = "Amazon.Lambda.Core.ILambdaContext";
public const string APIGatewayProxyRequest = "Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest";
public const string APIGatewayProxyResponse = "Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse";
public const string APIGatewayHttpApiV2ProxyRequest = "Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest";
public const string APIGatewayHttpApiV2ProxyResponse = "Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse";
public const string IHttpResult = "Amazon.Lambda.Annotations.APIGateway.IHttpResult";
public const string LambdaFunctionAttribute = "Amazon.Lambda.Annotations.LambdaFunctionAttribute";
public const string FromServiceAttribute = "Amazon.Lambda.Annotations.FromServicesAttribute";
public const string HttpApiVersion = "Amazon.Lambda.Annotations.APIGateway.HttpApiVersion";
public const string RestApiAttribute = "Amazon.Lambda.Annotations.APIGateway.RestApiAttribute";
public const string HttpApiAttribute = "Amazon.Lambda.Annotations.APIGateway.HttpApiAttribute";
public const string FromQueryAttribute = "Amazon.Lambda.Annotations.APIGateway.FromQueryAttribute";
public const string FromHeaderAttribute = "Amazon.Lambda.Annotations.APIGateway.FromHeaderAttribute";
public const string FromBodyAttribute = "Amazon.Lambda.Annotations.APIGateway.FromBodyAttribute";
public const string FromRouteAttribute = "Amazon.Lambda.Annotations.APIGateway.FromRouteAttribute";
public const string LambdaSerializerAttribute = "Amazon.Lambda.Core.LambdaSerializerAttribute";
public static HashSet<string> Requests = new HashSet<string>
{
APIGatewayProxyRequest,
APIGatewayHttpApiV2ProxyRequest
};
public static HashSet<string> Events = new HashSet<string>
{
RestApiAttribute,
HttpApiAttribute
};
}
} | 49 |
aws-lambda-dotnet | aws | C# | using System;
using Microsoft.CodeAnalysis;
using Amazon.Lambda.Annotations.APIGateway;
namespace Amazon.Lambda.Annotations.SourceGenerator.Diagnostics
{
public static class DiagnosticDescriptors
{
/// Generic errors
public static readonly DiagnosticDescriptor UnhandledException = new DiagnosticDescriptor(id: "AWSLambda0001",
title: "Unhandled exception",
messageFormat: "This is a bug. Please run the build with detailed verbosity (dotnet build --verbosity detailed) and file a bug at https://github.com/aws/aws-lambda-dotnet with the build output and stack trace {0}.",
category: "AWSLambda",
DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "{0}.",
helpLinkUri: "https://github.com/aws/aws-lambda-dotnet");
/// AWSLambdaCSharpGenerator starts from 0101
public static readonly DiagnosticDescriptor MultipleStartupNotAllowed = new DiagnosticDescriptor(id: "AWSLambda0101",
title: "Multiple LambdaStartup classes not allowed",
messageFormat: "Multiple LambdaStartup classes are not allowed in Lambda AWSProjectType",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor MultipleEventsNotSupported = new DiagnosticDescriptor(id: "AWSLambda0102",
title: "Multiple events on Lambda function not supported",
messageFormat: "Multiple event attributes on LambdaFunction are not supported",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor CodeGeneration = new DiagnosticDescriptor(id: "AWSLambda0103",
title: "Generated Code",
messageFormat: $"{{0}}{Environment.NewLine}{{1}}",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Info,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor MissingDependencies = new DiagnosticDescriptor(id: "AWSLambda0104",
title: "Missing reference to a required dependency",
messageFormat: "Your project has a missing required package dependency. Please add a reference to the following package: {0}.",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor HttpResultsOnNonApiFunction = new DiagnosticDescriptor(id: "AWSLambda0105",
title: $"Invalid return type {nameof(IHttpResult)}",
messageFormat: $"{nameof(IHttpResult)} is not a valid return type for LambdaFunctions without {nameof(HttpApiAttribute)} or {nameof(RestApiAttribute)} attributes",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor InvalidResourceName = new DiagnosticDescriptor(id: "AWSLambda0106",
title: $"Invalid CloudFormation resource name",
messageFormat: "The specified CloudFormation resource name is not valid. It must only contain alphanumeric characters.",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor CodeGenerationFailed = new DiagnosticDescriptor(id: "AWSLambda0107",
title: "Failed Code Generation",
messageFormat: "{0}",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor MissingLambdaSerializer = new DiagnosticDescriptor(id: "AWSLambda0108",
title: "Failed Code Generation",
messageFormat: "Assembly attribute Amazon.Lambda.Core.LambdaSerializerAttribute is missing. Add serialization package like " +
"Amazon.Lambda.Serialization.SystemTextJson and add the assembly attribute to register the JSON serializer for Lambda events.",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly DiagnosticDescriptor UnsupportedMethodParamaterType = new DiagnosticDescriptor(id: "AWSLambda0109",
title: "Unsupported Method Paramater Type",
messageFormat: "Unsupported query paramter '{0}' of type '{1}' encountered. Only primitive .NET types and their corresponding enumerables can be used as query parameters.",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
} | 84 |
aws-lambda-dotnet | aws | C# | using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Diagnostics
{
/// <summary>
/// Wrapper for GeneratorExecutionContext.ReportDiagnostic method
/// because GeneratorExecutionContext is a struct and can't be mocked easily.
/// </summary>
public interface IDiagnosticReporter
{
void Report(Diagnostic diagnostic);
}
public class DiagnosticReporter : IDiagnosticReporter
{
private readonly GeneratorExecutionContext _context;
public DiagnosticReporter(GeneratorExecutionContext context)
{
_context = context;
}
public void Report(Diagnostic diagnostic)
{
_context.ReportDiagnostic(diagnostic);
}
}
} | 28 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Extensions
{
public static class ParameterListExtension
{
public static bool HasConvertibleParameter(this IList<ParameterModel> parameters)
{
return parameters.Any(p =>
{
// All request types are forwarded to lambda method if specified, there is no parameter conversion required.
if (TypeFullNames.Requests.Contains(p.Type.FullName))
{
return false;
}
// ILambdaContext is forwarded to lambda method if specified, there is no parameter conversion required.
if (p.Type.FullName == TypeFullNames.ILambdaContext)
{
return false;
}
// Body parameter with target type as string doesn't require conversion because body is string by nature.
if (p.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromBodyAttribute) && p.Type.IsString())
{
return false;
}
// All other parameters either have From* attribute or considered as FromRoute parameter which require type conversion
return true;
});
}
}
} | 37 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.SourceGenerator.Extensions
{
public static class StringExtensions
{
public static string ToCamelCase(this string str)
{
if(!string.IsNullOrEmpty(str) && str.Length > 1)
{
return char.ToLowerInvariant(str[0]) + str.Substring(1);
}
return str;
}
}
public static class ExceptionExtensions
{
public static string PrettyPrint(this Exception e)
{
if (null == e)
{
return string.Empty;
}
return $"{e.Message}{e.StackTrace}{PrettyPrint(e.InnerException)}";
}
}
public static class EnvironmentExtensions
{
public static string ToEnvironmentLineEndings(this string str)
{
return str.Replace("\r\n", Environment.NewLine).
Replace("\n", Environment.NewLine).
Replace("\r\r\n", Environment.NewLine);
}
}
} | 39 |
aws-lambda-dotnet | aws | C# | using System.Linq;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Extensions
{
public static class SymbolHasAttributeExtension
{
/// <summary>
/// Returns true if symbol has an given attribute.
/// </summary>
/// <param name="symbol">Symbol exposed by the compiler.</param>
/// <param name="context">Source generator context.</param>
/// <param name="fullyQualifiedName">Fully qualified type name.</param>
/// <returns></returns>
public static bool HasAttribute(this ISymbol symbol, GeneratorExecutionContext context,
string fullyQualifiedName)
{
return symbol.GetAttributes()
.Any(att =>
{
if (att.AttributeClass == null)
{
return false;
}
return att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(fullyQualifiedName),
SymbolEqualityComparer.Default);
});
}
/// <summary>
/// Returns attribute data if symbol has an given attribute.
/// If there symbol doesn't have the attribute, returns null.
/// </summary>
/// <param name="symbol">Symbol exposed by the compiler.</param>
/// <param name="context">Source generator context.</param>
/// <param name="fullyQualifiedName">Fully qualified type name.</param>
/// <returns><see cref="AttributeData"/> for the given attribute.</returns>
public static AttributeData GetAttributeData(this ISymbol symbol, GeneratorExecutionContext context,
string fullyQualifiedName)
{
return symbol.GetAttributes()
.FirstOrDefault(att =>
{
if (att.AttributeClass == null)
{
return false;
}
return att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(fullyQualifiedName),
SymbolEqualityComparer.Default);
});
}
}
} | 55 |
aws-lambda-dotnet | aws | C# | using System;
using System.IO;
using System.Text;
namespace Amazon.Lambda.Annotations.SourceGenerator.FileIO
{
public class DirectoryManager : IDirectoryManager
{
public string GetDirectoryName(string path) => Path.GetDirectoryName(path);
public bool Exists(string path) => Directory.Exists(path);
/// <summary>
/// This method mimics the behaviour of <see href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath?view=net-6.0"/>
/// This logic already exists in the aws-extensions-for-dotnet-cli package. <see href="https://github.com/aws/aws-extensions-for-dotnet-cli/blob/9639f8f4902349d289491b290979a3a1671cc0a5/src/Amazon.Common.DotNetCli.Tools/Utilities.cs#L91">see here</see>
/// Note - Path.GetRelativePath() was introduced in .NET Standard 2.1 but source generators can only be used in .NET Standard 2.0 therefore this
/// custom implementation is needed.
/// </summary>
public string GetRelativePath(string relativeTo, string path)
{
if (string.IsNullOrEmpty(relativeTo) || string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"{nameof(relativeTo)} or {nameof(path)} cannot be null or empty");
}
// If there is no common ancestor, just return the path.
if (!string.Equals(SanitizePath(relativeTo).Split('/')[0], SanitizePath(path).Split('/')[0]))
{
return path;
}
// Calculate the full paths by preserving the OS specific directory separator character and then perform the sanitization.
relativeTo = SanitizePath(new DirectoryInfo(relativeTo).FullName);
path = SanitizePath(new DirectoryInfo(path).FullName);
var relativeToDirs = relativeTo.Split('/');
var pathDirs = path.Split('/');
var len = Math.Min(relativeToDirs.Length, pathDirs.Length);
var lastCommonRoot = -1;
int index;
for (index = 0; index < len && string.Equals(relativeToDirs[index], pathDirs[index]); index++)
{
lastCommonRoot = index;
}
var relativePath = new StringBuilder();
for (index = lastCommonRoot + 1; index < relativeToDirs.Length; index++)
{
if (relativeToDirs[index].Length > 0) relativePath.Append("../");
}
for (index = lastCommonRoot + 1; index < pathDirs.Length; index++)
{
relativePath.Append(pathDirs[index]);
if(index + 1 < pathDirs.Length)
{
relativePath.Append("/");
}
}
var result = relativePath.ToString();
if (result.EndsWith("/"))
result = result.Substring(0, result.Length - 1);
return string.IsNullOrEmpty(result) ? "." : result;
}
public string[] GetFiles(string path, string searchPattern, SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return Directory.GetFiles(path, searchPattern, searchOption);
}
private string SanitizePath(string path)
{
return path
.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
.Replace(Path.DirectorySeparatorChar, '/');
}
}
} | 81 |
aws-lambda-dotnet | aws | C# | using System.IO;
namespace Amazon.Lambda.Annotations.SourceGenerator.FileIO
{
public class FileManager : IFileManager
{
public string ReadAllText(string path) => File.ReadAllText(path);
public void WriteAllText(string path, string content) => File.WriteAllText(path, content);
public bool Exists(string path) => File.Exists(path);
public FileStream Create(string path) => File.Create(path);
}
} | 15 |
aws-lambda-dotnet | aws | C# | using System.IO;
namespace Amazon.Lambda.Annotations.SourceGenerator.FileIO
{
public interface IDirectoryManager
{
string GetDirectoryName(string path);
string[] GetFiles(string path, string searchPattern, SearchOption searchOption = SearchOption.TopDirectoryOnly);
bool Exists(string path);
string GetRelativePath(string relativeTo, string path);
}
} | 12 |
aws-lambda-dotnet | aws | C# | using System.IO;
namespace Amazon.Lambda.Annotations.SourceGenerator.FileIO
{
public interface IFileManager
{
string ReadAllText(string path);
void WriteAllText(string path, string content);
bool Exists(string path);
FileStream Create(string path);
}
} | 12 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
public class AnnotationReport
{
/// <summary>
/// Collection of annotated Lambda functions detected in the project
/// </summary>
public IList<ILambdaFunctionSerializable> LambdaFunctions { get; } = new List<ILambdaFunctionSerializable>();
/// <summary>
/// Path to the CloudFormation template for the Lambda project
/// </summary>
public string CloudFormationTemplatePath{ get; set; }
/// <summary>
/// Path to the directory containing the csproj file for the Lambda project
/// </summary>
public string ProjectRootDirectory { get; set; }
/// <summary>
/// Whether the flag to suppress telemetry about Lambda Annotations
/// projects is set to true in the Lambda project csproj
/// </summary>
public bool IsTelemetrySuppressed { get; set; }
}
} | 28 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Type of Lambda event
/// <see href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-eventsource.html">Supported Lambda events</see>
/// </summary>
public enum EventType
{
API,
S3,
SQS,
DynamoDB,
Schedule
}
} | 15 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="EventType"/> builder.
/// </summary>
public class EventTypeBuilder
{
public static List<EventType> Build(IMethodSymbol lambdaMethodSymbol,
GeneratorExecutionContext context)
{
var events = new List<EventType>();
foreach (var attribute in lambdaMethodSymbol.GetAttributes())
{
if (attribute.AttributeClass.ToDisplayString() == TypeFullNames.RestApiAttribute
|| attribute.AttributeClass.ToDisplayString() == TypeFullNames.HttpApiAttribute)
{
events.Add(EventType.API);
}
}
return events;
}
}
} | 30 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Represents generated method model used for generating the code from the template.
/// </summary>
public class GeneratedMethodModel
{
/// <summary>
/// Gets or sets type of response returned by the generated Lambda function.
/// </summary>
public TypeModel ReturnType { get; set; }
/// <summary>
/// Gets or sets type of parameters accepted by the generated Lambda function.
/// </summary>
public IList<ParameterModel> Parameters { get; set; }
/// <summary>
/// Gets or sets list of namespaces required to facilitate generated statements.
/// </summary>
public IList<string> Usings { get; set; }
/// <summary>
/// Gets or sets containing type of the generated Lambda function.
/// </summary>
public TypeModel ContainingType { get; set; }
}
} | 30 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="GeneratedMethodModel"/> builder.
/// </summary>
public static class GeneratedMethodModelBuilder
{
public static GeneratedMethodModel Build(IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
LambdaMethodModel lambdaMethodModel,
GeneratorExecutionContext context)
{
var model = new GeneratedMethodModel
{
Usings = BuildUsings(lambdaMethodModel, lambdaMethodSymbol, configureMethodSymbol, context),
Parameters = BuildParameters(lambdaMethodSymbol, lambdaMethodModel, context),
ReturnType = BuildResponseType(lambdaMethodSymbol, lambdaMethodModel, context),
ContainingType = BuildContainingType(lambdaMethodSymbol),
};
return model;
}
private static IList<string> BuildUsings(LambdaMethodModel lambdaMethodModel,
IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
GeneratorExecutionContext context)
{
var namespaces = new List<string>
{
"System",
"System.Linq",
"System.Collections.Generic",
"System.Text"
};
if (configureMethodSymbol != null)
{
namespaces.Add("Microsoft.Extensions.DependencyInjection");
}
namespaces.Add("Amazon.Lambda.Core");
if(lambdaMethodModel.ReturnsIHttpResults)
{
namespaces.Add("Amazon.Lambda.Annotations.APIGateway");
}
return namespaces;
}
private static TypeModel BuildResponseType(IMethodSymbol lambdaMethodSymbol,
LambdaMethodModel lambdaMethodModel, GeneratorExecutionContext context)
{
var task = context.Compilation.GetTypeByMetadataName(TypeFullNames.Task1);
if (lambdaMethodModel.ReturnsIHttpResults)
{
var typeStream = context.Compilation.GetTypeByMetadataName(TypeFullNames.Stream);
if (lambdaMethodModel.ReturnsGenericTask)
{
var genericTask = task.Construct(typeStream);
return TypeModelBuilder.Build(genericTask, context);
}
return TypeModelBuilder.Build(typeStream, context);
}
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAttribute))
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
var version = GetHttpApiVersion(lambdaMethodSymbol, context);
switch (version)
{
case HttpApiVersion.V1:
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
case HttpApiVersion.V2:
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
default:
throw new ArgumentOutOfRangeException();
}
}
else
{
return lambdaMethodModel.ReturnType;
}
}
private static HttpApiVersion GetHttpApiVersion(IMethodSymbol lambdaMethodSymbol, GeneratorExecutionContext context)
{
var httpApiAttribute = lambdaMethodSymbol.GetAttributeData(context, TypeFullNames.HttpApiAttribute);
if (httpApiAttribute.ConstructorArguments.IsDefaultOrEmpty)
{
throw new InvalidOperationException($"{TypeFullNames.HttpApiAttribute} must have a constructor with parameter.");
}
var versionArgument = httpApiAttribute.NamedArguments.FirstOrDefault(arg => arg.Key == "Version").Value;
if (versionArgument.Type == null)
{
return HttpApiVersion.V2;
}
if (!versionArgument.Type.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.HttpApiVersion), SymbolEqualityComparer.Default))
{
throw new InvalidOperationException($"Constructor parameter must be of type {TypeFullNames.HttpApiVersion}.");
}
if (versionArgument.Value == null)
{
throw new InvalidOperationException($"{versionArgument.Type} value cannot be null for {TypeFullNames.HttpApiAttribute}.");
}
return (HttpApiVersion)versionArgument.Value;
}
private static IList<ParameterModel> BuildParameters(IMethodSymbol lambdaMethodSymbol,
LambdaMethodModel lambdaMethodModel, GeneratorExecutionContext context)
{
var parameters = new List<ParameterModel>();
var contextParameter = new ParameterModel
{
Name = "__context__",
Type = new TypeModel
{
FullName = TypeFullNames.ILambdaContext
}
};
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAttribute))
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyRequest);
var type = TypeModelBuilder.Build(symbol, context);
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
var version = GetHttpApiVersion(lambdaMethodSymbol, context);
TypeModel type;
switch (version)
{
case HttpApiVersion.V1:
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyRequest);
type = TypeModelBuilder.Build(symbol, context);
break;
}
case HttpApiVersion.V2:
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyRequest);
type = TypeModelBuilder.Build(symbol, context);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else
{
// Lambda method with no event attribute are plain lambda functions, therefore, generated method will have
// same parameter as original method except DI injected parameters
foreach (var param in lambdaMethodModel.Parameters)
{
if (param.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
continue;
}
// If the Lambda function is taking in the ILambdaContext object make sure in the generated wrapper code we
// use the same system name for the ILambdaContext variable as all of the other places use.
else if(param.Type.FullName == TypeFullNames.ILambdaContext)
{
param.Name = "__context__";
}
parameters.Add(param);
}
}
return parameters;
}
private static TypeModel BuildContainingType(IMethodSymbol lambdaMethodSymbol)
{
var name = $"{lambdaMethodSymbol.ContainingType.Name}_{lambdaMethodSymbol.Name}_Generated";
var fullName = $"{lambdaMethodSymbol.ContainingNamespace}.{name}";
var model = new TypeModel
{
Name = name,
FullName = fullName,
IsValueType = false
};
return model;
}
}
} | 232 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
public interface ILambdaFunctionSerializable
{
/// <summary>
/// <para>
/// The name of the method within your code that Lambda calls to execute your function.
/// The format includes the file name. It can also include namespaces and other qualifiers, depending on the runtime.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/csharp-handler.html">here</a>
/// </para>
/// </summary>
string Handler { get; }
/// <summary>
/// The name of the CloudFormation resource that is associated with the Lambda function.
/// </summary>
string ResourceName { get; }
/// <summary>
/// The amount of time in seconds that Lambda allows a function to run before stopping it.
/// </summary>
uint? Timeout { get; }
/// <summary>
/// The amount of memory available to your Lambda function at runtime.
/// </summary>
uint? MemorySize { get; }
/// <summary>
/// The IAM Role assumed by the Lambda function during its execution.
/// </summary>
string Role { get; }
/// <summary>
/// Resource based policies that grants permissions to access other AWS resources.
/// </summary>
string Policies { get; }
/// <summary>
/// The deployment package type of the Lambda function. The supported values are Zip and Image.
/// For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html">here</a>
/// </summary>
LambdaPackageType PackageType { get; }
/// <summary>
/// List of attributes applied to the Lambda method that are used to generate serverless.template.
/// There always exists <see cref="Annotations.LambdaFunctionAttribute"/> in the list.
/// </summary>
IList<AttributeModel> Attributes { get; }
/// <summary>
/// The assembly version of the Amazon.Lambda.Annotations.SourceGenerator package.
/// </summary>
string SourceGeneratorVersion { get; set; }
}
} | 60 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Represents container class for the Lambda function.
/// </summary>
public class LambdaFunctionModel : ILambdaFunctionSerializable
{
/// <summary>
/// Gets or sets original method model.
/// </summary>
public LambdaMethodModel LambdaMethod { get; set; }
/// <summary>
/// Gets or sets generated method model.
/// </summary>
public GeneratedMethodModel GeneratedMethod { get; set; }
/// <summary>
/// Gets or sets the type of the Startup.cs class that contains the Configure method.
/// Returns null if there doesn't exist a Startup class.
/// </summary>
public TypeModel StartupType { get; set; }
/// <summary>
/// Gets or sets fully qualified name of the serializer used for serialization or deserialization.
/// </summary>
public string Serializer { get; set; }
/// <inheritdoc />
public string Handler => $"{LambdaMethod.ContainingAssembly}::{GeneratedMethod.ContainingType.FullName}::{LambdaMethod.Name}";
/// <inheritdoc />
public string ResourceName => LambdaMethod.LambdaFunctionAttribute.Data.ResourceName ??
string.Join(string.Empty, GeneratedMethod.ContainingType.FullName.Where(char.IsLetterOrDigit));
/// <inheritdoc />
public uint? Timeout => LambdaMethod.LambdaFunctionAttribute.Data.Timeout;
/// <inheritdoc />
public uint? MemorySize => LambdaMethod.LambdaFunctionAttribute.Data.MemorySize;
/// <inheritdoc />
public string Role => LambdaMethod.LambdaFunctionAttribute.Data.Role;
/// <inheritdoc />
public string Policies => LambdaMethod.LambdaFunctionAttribute.Data.Policies;
/// <inheritdoc />
/// The default value is set to Zip
public LambdaPackageType PackageType => LambdaMethod.LambdaFunctionAttribute.Data.PackageType;
/// <inheritdoc />
public IList<AttributeModel> Attributes => LambdaMethod.Attributes ?? new List<AttributeModel>();
/// <inheritdoc />
public string SourceGeneratorVersion { get; set; }
}
} | 63 |
aws-lambda-dotnet | aws | C# | using System.Linq;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="LambdaFunctionModel"/> builder.
/// </summary>
public static class LambdaFunctionModelBuilder
{
public static LambdaFunctionModel Build(IMethodSymbol lambdaMethodSymbol, IMethodSymbol configureMethodSymbol, GeneratorExecutionContext context)
{
var lambdaMethod = LambdaMethodModelBuilder.Build(lambdaMethodSymbol, configureMethodSymbol, context);
var generatedMethod = GeneratedMethodModelBuilder.Build(lambdaMethodSymbol, configureMethodSymbol, lambdaMethod, context);
var model = new LambdaFunctionModel()
{
GeneratedMethod = generatedMethod,
LambdaMethod = lambdaMethod,
Serializer = "System.Text.Json.JsonSerializer", // TODO: replace serializer with assembly serializer
StartupType = configureMethodSymbol != null ? TypeModelBuilder.Build(configureMethodSymbol.ContainingType, context) : null,
SourceGeneratorVersion = context.Compilation
.ReferencedAssemblyNames.FirstOrDefault(x => string.Equals(x.Name, "Amazon.Lambda.Annotations"))
?.Version.ToString()
};
return model;
}
}
} | 29 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Represents original method model used for generating the code from the template.
/// </summary>
public class LambdaMethodModel
{
private AttributeModel<LambdaFunctionAttribute> _lambdaFunctionAttribute;
/// <summary>
/// Returns true if original method returns void
/// </summary>
public bool ReturnsVoid { get; set; }
/// <summary>
/// Returns true if original method returns <see cref="System.Threading.Tasks.Task"/>
/// </summary>
public bool ReturnsVoidTask { get; set; }
/// <summary>
/// Returns true if original method returns <see cref="System.Threading.Tasks.Task<T>"/>
/// </summary>
public bool ReturnsGenericTask { get; set; }
/// <summary>
/// Returns true if either the ReturnsVoidTask or ReturnsGenericTask are true
/// </summary>
public bool ReturnsVoidOrGenericTask => ReturnsVoidTask || ReturnsGenericTask;
/// <summary>
/// Gets or sets the return type of the method.
/// </summary>
public TypeModel ReturnType { get; set; }
/// <summary>
/// Returns true if the Lambda function returns either IHttpResult or Task<IHttpResult>
/// </summary>
public bool ReturnsIHttpResults
{
get
{
if(ReturnsVoid)
{
return false;
}
if(ReturnType.FullName == TypeFullNames.IHttpResult)
{
return true;
}
if(ReturnsGenericTask && ReturnType.TypeArguments.Count == 1 && ReturnType.TypeArguments[0].FullName == TypeFullNames.IHttpResult)
{
return true;
}
return false;
}
}
/// <summary>
/// Gets or sets the parameters of original method. If this method has no parameters, returns
/// an empty list.
/// </summary>
public IList<ParameterModel> Parameters { get; set; }
/// <summary>
/// Gets or sets name of the original method.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Returns true if original method uses dependency injection.
/// </summary>
public bool UsingDependencyInjection { get; set; }
/// <summary>
/// Gets or sets the namespace for the nearest enclosing namespace. Returns null if the
/// symbol isn't contained in a namespace.
/// </summary>
public string ContainingNamespace { get; set; }
/// <summary>
/// Gets or sets the name of the assemblying containing the Lambda function.
/// </summary>
public string ContainingAssembly { get; set; }
/// <summary>
/// Gets or sets type of Lambda event
/// </summary>
public List<EventType> Events { get; set; }
/// <summary>
/// Gets or sets the <see cref="TypeModel"/> for the containing type. Returns null if the
/// symbol is not contained within a type.
/// </summary>
public TypeModel ContainingType { get; set; }
/// <summary>
/// Gets or sets the attributes of original method. There always exist <see cref="Annotations.LambdaFunctionAttribute"/> in the list.
/// </summary>
public IList<AttributeModel> Attributes { get; set; }
/// <summary>
/// Gets <see cref="Annotations.LambdaFunctionAttribute"/> attribute.
/// </summary>
public AttributeModel<LambdaFunctionAttribute> LambdaFunctionAttribute
{
get
{
if (_lambdaFunctionAttribute == null)
{
var model = Attributes.First(att => att.Type.FullName == TypeFullNames.LambdaFunctionAttribute);
if (model is AttributeModel<LambdaFunctionAttribute> lambdaFunctionAttributeModel)
{
_lambdaFunctionAttribute = lambdaFunctionAttributeModel;
}
else
{
throw new InvalidOperationException($"Lambda method must has a {TypeFullNames.LambdaFunctionAttribute} attribute");
}
}
return _lambdaFunctionAttribute;
}
}
}
} | 134 |
aws-lambda-dotnet | aws | C# | using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="LambdaMethodModel"/> builder.
/// </summary>
public static class LambdaMethodModelBuilder
{
public static LambdaMethodModel Build(IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
GeneratorExecutionContext context)
{
var model = new LambdaMethodModel
{
ReturnType = TypeModelBuilder.Build(lambdaMethodSymbol.ReturnType, context),
ReturnsVoid = lambdaMethodSymbol.ReturnsVoid,
ReturnsVoidTask = lambdaMethodSymbol.ReturnType.Equals(context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"), SymbolEqualityComparer.Default),
ReturnsGenericTask = (lambdaMethodSymbol.ReturnType.BaseType?.Equals(context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"), SymbolEqualityComparer.Default)).GetValueOrDefault(),
Parameters = ParameterModelBuilder.Build(lambdaMethodSymbol, context),
Name = lambdaMethodSymbol.Name,
ContainingAssembly = lambdaMethodSymbol.ContainingAssembly.Name,
ContainingNamespace = lambdaMethodSymbol.ContainingNamespace.ToDisplayString(),
Events = EventTypeBuilder.Build(lambdaMethodSymbol, context),
ContainingType = TypeModelBuilder.Build(lambdaMethodSymbol.ContainingType, context),
UsingDependencyInjection = configureMethodSymbol != null,
Attributes = lambdaMethodSymbol.GetAttributes().Select(att => AttributeModelBuilder.Build(att, context)).ToList()
};
return model;
}
}
} | 36 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Represents parameters of the original method used for generating the code from the template.
/// </summary>
public class ParameterModel
{
/// <summary>
/// Gets or sets type of the parameter.
/// </summary>
public TypeModel Type { get; set; }
/// <summary>
/// Gets or sets the display name of the parameter.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the attributes of parameter. If this parameter has no attributes, returns
/// an empty list.
/// </summary>
public IList<AttributeModel> Attributes { get; set; } = new List<AttributeModel>();
}
} | 27 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="ParameterModel"/> builder.
/// </summary>
public static class ParameterModelBuilder
{
public static IList<ParameterModel> Build(IMethodSymbol methodSymbol,
GeneratorExecutionContext context)
{
var models = new List<ParameterModel>();
foreach (var parameter in methodSymbol.Parameters)
{
models.Add(new ParameterModel
{
Name = parameter.Name,
Type = TypeModelBuilder.Build(parameter.Type, context),
Attributes = parameter.GetAttributes().Select(att => AttributeModelBuilder.Build(att, context)).ToList()
});
}
return models;
}
}
} | 32 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// Represents a type.
/// </summary>
public class TypeModel
{
private readonly HashSet<string> _primitiveTypes = new HashSet<string>()
{
"bool",
"char", "string",
"byte", "sbyte",
"double", "decimal", "float",
"short", "int", "long",
"ushort", "uint", "ulong",
"System.DateTime"
};
/// <summary>
/// Gets or sets the name of the type.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the full qualified name of the type.
/// In some cases such as value types (ex. int), FullName will be the alias i.e. int in spite of System.Int32.
/// </summary>
public string FullName { get; set; }
/// <summary>
/// True if this type is a value type.
/// </summary>
public bool IsValueType { get; set; }
/// <summary>
/// True if this type or some containing type has type parameters.
/// </summary>
public bool IsGenericType { get; set; }
/// <summary>
/// Gets or sets the type arguments that have been substituted for the type parameters.
/// Returns empty when there are not type arguments
/// </summary>
public IList<TypeModel> TypeArguments { get; set; }
/// <summary>
/// True if the type has the "?" annotation for nullable.
/// </summary>
public bool HasNullableAnnotations { get; set; }
public string FullNameWithoutAnnotations
{
get
{
if(!HasNullableAnnotations)
{
return this.FullName;
}
return this.FullName.Substring(0, this.FullName.Length - 1);
}
}
/// <summary>
/// Gets type argument of the <see cref="Task{TResult}"/> type.
/// If the type is not a generic or <see cref="Task{TResult}"/> type, returns null.
/// </summary>
public string TaskTypeArgument
{
get
{
if (!IsGenericType)
{
return null;
}
if (!FullName.StartsWith($"{TypeFullNames.Task}<"))
{
return null;
}
return TypeArguments[0].FullName;
}
}
/// <summary>
/// True, if the type implements IEnumerable interface.
/// </summary>
public bool IsEnumerable { get; set; }
/// <summary>
/// True if this type is a <see cref="string"/> type.
/// </summary>
/// <returns></returns>
public bool IsString()
{
return FullName == "string";
}
/// <summary>
/// True, if the type is a primitive .NET type.
/// </summary>
public bool IsPrimitiveType()
{
return _primitiveTypes.Contains(FullNameWithoutAnnotations);
}
/// <summary>
/// True, if type model is an enumerable and its argument type is a primitive .NET type.
/// </summary>
public bool IsPrimitiveEnumerableType()
{
if (!IsEnumerable)
return false;
if (TypeArguments.Count != 1)
{
throw new NotSupportedException("Exactly one type argument is required for enumerables");
}
var typeArgument = TypeArguments.First();
return _primitiveTypes.Contains(typeArgument.FullNameWithoutAnnotations);
}
}
} | 131 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="TypeModel"/> builder.
/// </summary>
public static class TypeModelBuilder
{
public static TypeModel Build(ITypeSymbol symbol, GeneratorExecutionContext context)
{
bool isGenericType;
if (symbol is INamedTypeSymbol)
isGenericType = ((INamedTypeSymbol)symbol)?.IsGenericType ?? false;
else
isGenericType = false;
IList<TypeModel> typeArguments;
if (symbol is INamedTypeSymbol)
typeArguments = ((INamedTypeSymbol)symbol)?.TypeArguments.Select(arg => Build(arg, context)).ToList();
else
typeArguments = new List<TypeModel>();
bool isEnumerable;
if (symbol is INamedTypeSymbol)
isEnumerable = ((INamedTypeSymbol)symbol)?.Interfaces.Any(it => it.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.IEnumerable), SymbolEqualityComparer.Default)) ?? false;
else if (symbol is IDynamicTypeSymbol)
isEnumerable = ((IDynamicTypeSymbol)symbol)?.Interfaces.Any(it => it.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.IEnumerable), SymbolEqualityComparer.Default)) ?? false;
else
isEnumerable = false;
var model = new TypeModel
{
Name = symbol.Name,
FullName = symbol.ToDisplayString(),
IsValueType = symbol.IsValueType,
IsGenericType = isGenericType,
TypeArguments = typeArguments,
IsEnumerable = isEnumerable,
HasNullableAnnotations = symbol.NullableAnnotation == NullableAnnotation.Annotated
};
return model;
}
}
} | 48 |
aws-lambda-dotnet | aws | C# | using System;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Represents attribute used on a type.
/// </summary>
public class AttributeModel
{
/// <summary>
/// Gets or sets type of the attribute
/// </summary>
public TypeModel Type { get; set; }
}
/// <summary>
/// Represents attribute used on a type.
/// </summary>
/// <typeparam name="T">
/// Type of attribute data, for example a FromRoute attribute can optionally have Name
/// which can be modeled using attribute data.
/// </typeparam>
public class AttributeModel<T> : AttributeModel where T : Attribute
{
/// <summary>
/// Gets or sets data associated with attribute.
/// </summary>
public T Data { get; set; }
}
} | 30 |
aws-lambda-dotnet | aws | C# | using System;
using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// <see cref="AttributeModel"/> builder.
/// </summary>
public static class AttributeModelBuilder
{
public static AttributeModel Build(AttributeData att, GeneratorExecutionContext context)
{
if (att.AttributeClass == null)
{
throw new NotSupportedException($"An attribute must have an attribute class. Attribute class is not found for {att}");
}
AttributeModel model;
if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.LambdaFunctionAttribute), SymbolEqualityComparer.Default))
{
var data = LambdaFunctionAttributeDataBuilder.Build(att);
model = new AttributeModel<LambdaFunctionAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.FromQueryAttribute), SymbolEqualityComparer.Default))
{
var data = FromQueryAttributeBuilder.Build(att);
model = new AttributeModel<FromQueryAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.FromHeaderAttribute), SymbolEqualityComparer.Default))
{
var data = FromHeaderAttributeBuilder.Build(att);
model = new AttributeModel<FromHeaderAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.FromRouteAttribute), SymbolEqualityComparer.Default))
{
var data = FromRouteAttributeBuilder.Build(att);
model = new AttributeModel<FromRouteAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.HttpApiAttribute), SymbolEqualityComparer.Default))
{
var data = HttpApiAttributeBuilder.Build(att);
model = new AttributeModel<HttpApiAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.RestApiAttribute), SymbolEqualityComparer.Default))
{
var data = RestApiAttributeBuilder.Build(att);
model = new AttributeModel<RestApiAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else
{
model = new AttributeModel
{
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
return model;
}
}
} | 85 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="FromHeaderAttribute"/>.
/// </summary>
public class FromHeaderAttributeBuilder
{
public static FromHeaderAttribute Build(AttributeData att)
{
var data = new FromHeaderAttribute();
foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.Name) && pair.Value.Value is string value)
{
data.Name = value;
}
}
return data;
}
}
} | 25 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="FromQueryAttribute"/>.
/// </summary>
public class FromQueryAttributeBuilder
{
public static FromQueryAttribute Build(AttributeData att)
{
var data = new FromQueryAttribute();
foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.Name) && pair.Value.Value is string value)
{
data.Name = value;
}
}
return data;
}
}
} | 25 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="FromRouteAttribute"/>.
/// </summary>
public class FromRouteAttributeBuilder
{
public static FromRouteAttribute Build(AttributeData att)
{
var data = new FromRouteAttribute();
foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.Name) && pair.Value.Value is string value)
{
data.Name = value;
}
}
return data;
}
}
} | 25 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
public static class HttpApiAttributeBuilder
{
public static HttpApiAttribute Build(AttributeData att)
{
if (att.ConstructorArguments.Length != 2)
{
throw new NotSupportedException($"{TypeFullNames.HttpApiAttribute} must have constructor with 2 arguments.");
}
var method = (LambdaHttpMethod)att.ConstructorArguments[0].Value;
var template = att.ConstructorArguments[1].Value as string;
var version = att.NamedArguments.FirstOrDefault(arg => arg.Key == "Version").Value.Value;
var data = new HttpApiAttribute(method, template)
{
Version = version == null ? HttpApiVersion.V2 : (HttpApiVersion)version
};
return data;
}
}
} | 28 |
aws-lambda-dotnet | aws | C# | using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="LambdaFunctionAttributeData"/>.
/// </summary>
public static class LambdaFunctionAttributeDataBuilder
{
public static LambdaFunctionAttribute Build(AttributeData att)
{
var data = new LambdaFunctionAttribute();
foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.ResourceName) && pair.Value.Value is string value)
{
data.ResourceName = value;
}
if (pair.Key == nameof(data.Policies) && pair.Value.Value is string policies)
{
data.Policies = policies;
}
if (pair.Key == nameof(data.Role) && pair.Value.Value is string role)
{
data.Role = role;
}
if (pair.Key == nameof(data.Timeout) && pair.Value.Value is uint timeout)
{
data.Timeout = timeout;
}
if (pair.Key == nameof(data.MemorySize) && pair.Value.Value is uint memorySize)
{
data.MemorySize = memorySize;
}
if (pair.Key == nameof(data.PackageType) && pair.Value.Value is int)
{
data.PackageType = (LambdaPackageType)pair.Value.Value;
}
}
return data;
}
}
} | 50 |
aws-lambda-dotnet | aws | C# | using System;
using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="RestApiAttribute"/>.
/// </summary>
public class RestApiAttributeBuilder
{
public static RestApiAttribute Build(AttributeData att)
{
if (att.ConstructorArguments.Length != 2)
{
throw new NotSupportedException($"{TypeFullNames.RestApiAttribute} must have constructor with 2 arguments.");
}
var method = (LambdaHttpMethod)att.ConstructorArguments[0].Value;
var template = att.ConstructorArguments[1].Value as string;
var data = new RestApiAttribute(method, template);
return data;
}
}
} | 27 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.APIGateway;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
public static class TemplateParametersExtension
{
/// <summary>
/// Returns aa <see cref="HashSet{T}"/> of string containing template parameter
/// parsed from the <see cref="RestApiAttribute.Template"/>.
/// </summary>
/// <param name="attribute">this <see cref="RestApiAttribute"/> object.</param>
public static HashSet<string> GetTemplateParameters(this RestApiAttribute attribute)
{
var template = attribute.Template;
return GetTemplateParameters(template);
}
/// <summary>
/// Returns aa <see cref="HashSet{T}"/> of string containing template parameter
/// parsed from the <see cref="HttpApiAttribute.Template"/>.
/// </summary>
/// <param name="attribute">this <see cref="HttpApiAttribute"/> object.</param>
public static HashSet<string> GetTemplateParameters(this HttpApiAttribute attribute)
{
var template = attribute.Template;
return GetTemplateParameters(template);
}
private static HashSet<string> GetTemplateParameters(string template)
{
var parameters = new HashSet<string>();
var components = template.Split('/').Where(c => !string.IsNullOrWhiteSpace(c));
foreach (var component in components)
{
if (component.StartsWith("{") && component.EndsWith("}"))
{
var parameter = component.Substring(1, component.Length - 2);
parameters.Add(parameter);
}
}
return parameters;
}
}
} | 49 |
aws-lambda-dotnet | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.Validation;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class APIGatewayInvoke : APIGatewayInvokeBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 10 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
var restApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.RestApiAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.RestApiAttribute>;
var httpApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.HttpApiAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.HttpApiAttribute>;
if (_model.LambdaMethod.ReturnsIHttpResults)
{
#line default
#line hidden
this.Write(" var httpResults = ");
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnsGenericTask ? "await " : ""));
#line default
#line hidden
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_parameterSignature));
#line default
#line hidden
this.Write(");\r\n HttpResultSerializationOptions.ProtocolFormat serializationFormat" +
" = ");
#line 18 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(restApiAttribute != null ? "HttpResultSerializationOptions.ProtocolFormat.RestApi" : "HttpResultSerializationOptions.ProtocolFormat.HttpApi"));
#line default
#line hidden
this.Write(";\r\n HttpResultSerializationOptions.ProtocolVersion serializationVersio" +
"n = ");
#line 19 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(restApiAttribute != null || httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V1 ? "HttpResultSerializationOptions.ProtocolVersion.V1" : "HttpResultSerializationOptions.ProtocolVersion.V2"));
#line default
#line hidden
this.Write(";\r\n var serializationOptions = new HttpResultSerializationOptions { Fo" +
"rmat = serializationFormat, Version = serializationVersion };\r\n var r" +
"esponse = httpResults.Serialize(serializationOptions);\r\n");
#line 22 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
else if (_model.LambdaMethod.ReturnsVoid)
{
#line default
#line hidden
this.Write(" ");
#line 27 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 27 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 27 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_parameterSignature));
#line default
#line hidden
this.Write(");\r\n");
#line 28 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
else if (_model.LambdaMethod.ReturnsVoidTask)
{
#line default
#line hidden
this.Write(" await ");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_parameterSignature));
#line default
#line hidden
this.Write(");\r\n");
#line 34 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
else
{
#line default
#line hidden
this.Write(" var response = ");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnsGenericTask ? "await " : ""));
#line default
#line hidden
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_parameterSignature));
#line default
#line hidden
this.Write(");\r\n");
#line 40 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
if (_model.GeneratedMethod.ReturnType.FullName == _model.LambdaMethod.ReturnType.FullName || _model.LambdaMethod.ReturnsIHttpResults)
{
#line default
#line hidden
this.Write(" return response;\r\n");
#line 47 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
else
{
if (!_model.LambdaMethod.ReturnsVoid && !_model.LambdaMethod.ReturnsVoidTask)
{
if (_model.LambdaMethod.ReturnType.IsValueType)
{
#line default
#line hidden
this.Write("\r\n var body = response.ToString();\r\n");
#line 58 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
else if (_model.LambdaMethod.ReturnType.IsString())
{
// no action
}
else
{
#line default
#line hidden
this.Write("\r\n var body = ");
#line 68 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.Serializer));
#line default
#line hidden
this.Write(".Serialize(response);\r\n");
#line 69 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
}
#line default
#line hidden
this.Write("\r\n return new ");
#line 74 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnsVoidOrGenericTask ? _model.GeneratedMethod.ReturnType.TaskTypeArgument : _model.GeneratedMethod.ReturnType.FullName));
#line default
#line hidden
this.Write("\r\n {\r\n");
#line 76 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
if (!_model.LambdaMethod.ReturnsVoid && !_model.LambdaMethod.ReturnsVoidTask)
{
#line default
#line hidden
this.Write(" Body = ");
#line 80 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnType.IsString() ? "response" : "body"));
#line default
#line hidden
this.Write(",\r\n Headers = new Dictionary<string, string>\r\n {\r\n " +
" {\"Content-Type\", ");
#line 83 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnType.IsString() ? "\"text/plain\"" : "\"application/json\""));
#line default
#line hidden
this.Write("}\r\n },\r\n");
#line 85 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
#line default
#line hidden
this.Write(" StatusCode = 200\r\n };\r\n");
#line 90 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewayInvoke.tt"
}
#line default
#line hidden
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class APIGatewayInvokeBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 582 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
public partial class APIGatewayInvoke
{
private readonly LambdaFunctionModel _model;
public readonly string _parameterSignature;
public APIGatewayInvoke(LambdaFunctionModel model, string parameterSignature)
{
_model = model;
_parameterSignature = parameterSignature;
}
}
} | 17 |
aws-lambda-dotnet | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.Validation;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class APIGatewaySetupParameters : APIGatewaySetupParametersBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 10 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
ParameterSignature = string.Join(", ", _model.LambdaMethod.Parameters
.Select(p =>
{
// Pass the same context parameter for ILambdaContext that comes from the generated method.
if (p.Type.FullName == TypeFullNames.ILambdaContext)
{
return "__context__";
}
// Pass the same request parameter for Request Type that comes from the generated method.
if (TypeFullNames.Requests.Contains(p.Type.FullName))
{
return "__request__";
}
return p.Name;
}));
var restApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.RestApiAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.RestApiAttribute>;
var httpApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.HttpApiAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.HttpApiAttribute>;
if (restApiAttribute != null && httpApiAttribute != null)
{
throw new NotSupportedException($"A method cannot have both {TypeFullNames.RestApiAttribute} and {TypeFullNames.HttpApiAttribute} attribute at the same time.");
}
var routeParameters = restApiAttribute?.Data?.GetTemplateParameters() ?? httpApiAttribute?.Data?.GetTemplateParameters() ?? new HashSet<string>();
var (routeTemplateValid, missingRouteParams) = RouteParametersValidator.Validate(routeParameters, _model.LambdaMethod.Parameters);
if (!routeTemplateValid)
{
var template = restApiAttribute?.Data?.Template ?? httpApiAttribute?.Data?.Template ?? string.Empty;
throw new InvalidOperationException($"Route template {template} is invalid. Missing {string.Join(",", missingRouteParams)} parameters in method definition.");
}
if (_model.LambdaMethod.Parameters.HasConvertibleParameter())
{
#line default
#line hidden
this.Write(" var validationErrors = new List<string>();\r\n\r\n");
#line 50 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
foreach (var parameter in _model.LambdaMethod.Parameters)
{
if (parameter.Type.FullName == TypeFullNames.ILambdaContext || TypeFullNames.Requests.Contains(parameter.Type.FullName))
{
// No action required for ILambdaContext and RequestType, they are passed from the generated method parameter directly to the original method.
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
#line default
#line hidden
this.Write(" var ");
#line 62 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 62 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">();\r\n");
#line 63 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromQueryAttribute))
{
var fromQueryAttribute = parameter.Attributes.First(att => att.Type.FullName == TypeFullNames.FromQueryAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.FromQueryAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var parameterKey = fromQueryAttribute?.Data?.Name ?? parameter.Name;
var queryStringParameters = "QueryStringParameters";
#line default
#line hidden
this.Write(" var ");
#line 75 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 75 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n");
#line 76 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
if (parameter.Type.IsEnumerable && parameter.Type.IsGenericType)
{
// In HTTP API V2 multiple values for the same parameter are represented via comma separated string
// Therefore, it is required to split the string to convert to an enumerable
// and convert individual item to target data type.
var commaSplit = "";
if (httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V2)
{
commaSplit = @".Split("","")";
}
// HTTP API V1 and Rest API, multiple values for the same parameter are provided
// dedicated dictionary of string key and list value.
if (restApiAttribute != null || httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V1)
{
queryStringParameters = "MultiValueQueryStringParameters";
}
if (parameter.Type.TypeArguments.Count != 1)
{
throw new NotSupportedException("Only one type argument is supported for generic types.");
}
// Generic types are mapped using Select statement to the target parameter type argument.
var typeArgument = parameter.Type.TypeArguments.First();
#line default
#line hidden
this.Write(" if (__request__.");
#line 104 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 104 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n ");
#line 106 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = __request__.");
#line 106 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 106 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"]");
#line 106 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(commaSplit));
#line default
#line hidden
this.Write("\r\n .Select(q =>\r\n {\r\n " +
" try\r\n {\r\n return (");
#line 111 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(q, typeof(");
#line 111 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullNameWithoutAnnotations));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {q} at '");
#line 115 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n retur" +
"n default;\r\n }\r\n })\r\n " +
" .ToList();\r\n }\r\n\r\n");
#line 122 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else
{
// Non-generic types are mapped directly to the target parameter.
#line default
#line hidden
this.Write(" if (__request__.");
#line 128 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 128 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n try\r\n {\r\n " +
" ");
#line 132 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 132 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(__request__.");
#line 132 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 132 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"], typeof(");
#line 132 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullNameWithoutAnnotations));
#line default
#line hidden
this.Write("));\r\n }\r\n catch (Exception e) when (e is InvalidCas" +
"tException || e is FormatException || e is OverflowException || e is ArgumentExc" +
"eption)\r\n {\r\n validationErrors.Add($\"Value {__" +
"request__.");
#line 136 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 136 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"]} at \'");
#line 136 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 140 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromHeaderAttribute))
{
var fromHeaderAttribute =
parameter.Attributes.First(att => att.Type.FullName == TypeFullNames.FromHeaderAttribute) as
AttributeModel<Amazon.Lambda.Annotations.APIGateway.FromHeaderAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var headerKey = fromHeaderAttribute?.Data?.Name ?? parameter.Name;
var headers = "Headers";
#line default
#line hidden
this.Write(" var ");
#line 156 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 156 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n");
#line 157 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
if (parameter.Type.IsEnumerable && parameter.Type.IsGenericType)
{
// In HTTP API V2 multiple values for the same header are represented via comma separated string
// Therefore, it is required to split the string to convert to an enumerable
// and convert individual item to target data type.
var commaSplit = "";
if (httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V2)
{
commaSplit = @".Split("","")";
}
// HTTP API V1 and Rest API, multiple values for the same header are provided
// dedicated dictionary of string key and list value.
if (restApiAttribute != null || httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V1)
{
headers = "MultiValueHeaders";
}
if (parameter.Type.TypeArguments.Count != 1)
{
throw new NotSupportedException("Only one type argument is supported for generic types.");
}
// Generic types are mapped using Select statement to the target parameter type argument.
var typeArgument = parameter.Type.TypeArguments.First();
#line default
#line hidden
this.Write(" if (__request__.");
#line 185 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("?.Any(x => string.Equals(x.Key, \"");
#line 185 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\", StringComparison.OrdinalIgnoreCase)) == true)\r\n {\r\n " +
"");
#line 187 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = __request__.");
#line 187 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write(".First(x => string.Equals(x.Key, \"");
#line 187 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\", StringComparison.OrdinalIgnoreCase)).Value");
#line 187 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(commaSplit));
#line default
#line hidden
this.Write("\r\n .Select(q =>\r\n {\r\n " +
" try\r\n {\r\n return (");
#line 192 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(q, typeof(");
#line 192 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullNameWithoutAnnotations));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {q} at '");
#line 196 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n retur" +
"n default;\r\n }\r\n })\r\n " +
" .ToList();\r\n }\r\n\r\n");
#line 203 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else
{
// Non-generic types are mapped directly to the target parameter.
#line default
#line hidden
this.Write(" if (__request__.");
#line 209 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("?.Any(x => string.Equals(x.Key, \"");
#line 209 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\", StringComparison.OrdinalIgnoreCase)) == true)\r\n {\r\n " +
"try\r\n {\r\n ");
#line 213 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 213 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(__request__.");
#line 213 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write(".First(x => string.Equals(x.Key, \"");
#line 213 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\", StringComparison.OrdinalIgnoreCase)).Value, typeof(");
#line 213 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullNameWithoutAnnotations));
#line default
#line hidden
this.Write("));\r\n }\r\n catch (Exception e) when (e is InvalidCas" +
"tException || e is FormatException || e is OverflowException || e is ArgumentExc" +
"eption)\r\n {\r\n validationErrors.Add($\"Value {__" +
"request__.");
#line 217 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write(".First(x => string.Equals(x.Key, \"");
#line 217 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\", StringComparison.OrdinalIgnoreCase)).Value} at \'");
#line 217 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 221 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromBodyAttribute))
{
// string parameter does not need to be de-serialized
if (parameter.Type.IsString())
{
#line default
#line hidden
this.Write(" var ");
#line 230 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = __request__.Body;\r\n\r\n");
#line 232 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else
{
#line default
#line hidden
this.Write(" var ");
#line 237 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 237 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n try\r\n {\r\n ");
#line 240 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = ");
#line 240 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.Serializer));
#line default
#line hidden
this.Write(".Deserialize<");
#line 240 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">(__request__.Body);\r\n }\r\n catch (Exception e)\r\n " +
" {\r\n validationErrors.Add($\"Value {__request__.Body} at \'body\' fa" +
"iled to satisfy constraint: {e.Message}\");\r\n }\r\n\r\n");
#line 247 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromRouteAttribute) || routeParameters.Contains(parameter.Name))
{
var fromRouteAttribute = parameter.Attributes?.FirstOrDefault(att => att.Type.FullName == TypeFullNames.FromRouteAttribute) as AttributeModel<Amazon.Lambda.Annotations.APIGateway.FromRouteAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var routeKey = fromRouteAttribute?.Data?.Name ?? parameter.Name;
#line default
#line hidden
this.Write(" var ");
#line 257 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 257 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n if (__request__.PathParameters?.ContainsKey(\"");
#line 258 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n try\r\n {\r\n " +
" ");
#line 262 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 262 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(__request__.PathParameters[\"");
#line 262 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\"], typeof(");
#line 262 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullNameWithoutAnnotations));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {__request__.PathParameters[""");
#line 266 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\"]} at \'");
#line 266 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 270 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else
{
throw new NotSupportedException($"{parameter.Name} parameter of type {parameter.Type.FullName} passing is not supported.");
}
}
if (_model.LambdaMethod.Parameters.HasConvertibleParameter())
{
#line default
#line hidden
this.Write(" // return 400 Bad Request if there exists a validation error\r\n " +
" if (validationErrors.Any())\r\n {\r\n var errorResult" +
" = new ");
#line 284 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(restApiAttribute != null || httpApiAttribute?.Data.Version == Amazon.Lambda.Annotations.APIGateway.HttpApiVersion.V1 ? "Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse" : "Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse"));
#line default
#line hidden
this.Write(@"
{
Body = @$""{{""""message"""": """"{validationErrors.Count} validation error(s) detected: {string.Join("","", validationErrors)}""""}}"",
Headers = new Dictionary<string, string>
{
{""Content-Type"", ""application/json""},
{""x-amzn-ErrorType"", ""ValidationException""}
},
StatusCode = 400
};
");
#line 294 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
if(_model.LambdaMethod.ReturnsIHttpResults)
{
#line default
#line hidden
this.Write(" var errorStream = new System.IO.MemoryStream();\r\n " +
"System.Text.Json.JsonSerializer.Serialize(errorStream, errorResult);\r\n " +
" return errorStream;\r\n");
#line 301 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
else
{
#line default
#line hidden
this.Write(" return errorResult;\r\n");
#line 307 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
#line default
#line hidden
this.Write(" }\r\n\r\n");
#line 312 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\APIGatewaySetupParameters.tt"
}
#line default
#line hidden
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class APIGatewaySetupParametersBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 1,072 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
public partial class APIGatewaySetupParameters
{
private readonly LambdaFunctionModel _model;
public string ParameterSignature { get; set; }
public APIGatewaySetupParameters(LambdaFunctionModel model)
{
_model = model;
}
}
} | 16 |
aws-lambda-dotnet | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class FieldsAndConstructor : FieldsAndConstructorBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 7 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(" private readonly ServiceProvider serviceProvider;\r\n");
#line 12 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
else
{
#line default
#line hidden
this.Write(" private readonly ");
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(" ");
#line 17 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(";\r\n");
#line 18 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
#line default
#line hidden
this.Write("\r\n public ");
#line 22 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ContainingType.Name));
#line default
#line hidden
this.Write("()\r\n {\r\n SetExecutionEnvironment();\r\n");
#line 25 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(@" var services = new ServiceCollection();
// By default, Lambda function class is added to the service container using the singleton lifetime
// To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method.
services.AddSingleton<");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n\r\n var startup = new ");
#line 35 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.StartupType.FullName));
#line default
#line hidden
this.Write("();\r\n startup.ConfigureServices(services);\r\n serviceProvide" +
"r = services.BuildServiceProvider();\r\n");
#line 38 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
else
{
#line default
#line hidden
this.Write(" ");
#line 43 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(" = new ");
#line 43 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write("();\r\n");
#line 44 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt"
}
#line default
#line hidden
this.Write(" }");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class FieldsAndConstructorBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 425 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
public partial class FieldsAndConstructor
{
private readonly LambdaFunctionModel _model;
public FieldsAndConstructor(LambdaFunctionModel model)
{
_model = model;
}
}
} | 14 |
aws-lambda-dotnet | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Microsoft.CodeAnalysis;
using Amazon.Lambda.Annotations.SourceGenerator.Validation;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class LambdaFunctionTemplate : LambdaFunctionTemplateBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 11 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
foreach (var ns in _model.GeneratedMethod.Usings)
{
#line default
#line hidden
this.Write("using ");
#line 15 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(ns));
#line default
#line hidden
this.Write(";\r\n");
#line 16 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
#line default
#line hidden
this.Write("\r\nnamespace ");
#line 20 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingNamespace));
#line default
#line hidden
this.Write("\r\n{\r\n public class ");
#line 22 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ContainingType.Name));
#line default
#line hidden
this.Write("\r\n {\r\n");
#line 24 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(new FieldsAndConstructor(_model).TransformText());
#line default
#line hidden
this.Write("\r\n\r\n public ");
#line 29 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnsVoidOrGenericTask ? "async " : ""));
#line default
#line hidden
#line 29 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ReturnType.FullName));
#line default
#line hidden
this.Write(" ");
#line 29 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 29 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(string.Join(", ", _model.GeneratedMethod.Parameters.Select(p => $"{p.Type.FullName} {p.Name}"))));
#line default
#line hidden
this.Write(")\r\n {\r\n");
#line 31 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(" // Create a scope for every request,\r\n // this allows crea" +
"ting scoped dependencies without creating a scope manually.\r\n using v" +
"ar scope = serviceProvider.CreateScope();\r\n var ");
#line 38 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n\r\n");
#line 41 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
if (_model.LambdaMethod.Events.Contains(EventType.API))
{
var apiParameters = new APIGatewaySetupParameters(_model);
this.Write(apiParameters.TransformText());
this.Write(new APIGatewayInvoke(_model, apiParameters.ParameterSignature).TransformText());
}
else if (_model.LambdaMethod.Events.Count == 0)
{
this.Write(new NoEventMethodBody(_model).TransformText());
}
#line default
#line hidden
this.Write(@" }
private static void SetExecutionEnvironment()
{
const string envName = ""AWS_EXECUTION_ENV"";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($""{Environment.GetEnvironmentVariable(envName)}_"");
}
envValue.Append(""amazon-lambda-annotations_");
#line 69 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.SourceGeneratorVersion));
#line default
#line hidden
this.Write("\");\r\n\r\n Environment.SetEnvironmentVariable(envName, envValue.ToString(" +
"));\r\n }\r\n }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class LambdaFunctionTemplateBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 459 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
public partial class LambdaFunctionTemplate
{
private readonly LambdaFunctionModel _model;
public LambdaFunctionTemplate(LambdaFunctionModel model)
{
_model = model;
}
}
} | 14 |
aws-lambda-dotnet | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class NoEventMethodBody : NoEventMethodBodyBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 7 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
var parameters = string.Join(", ", _model.LambdaMethod.Parameters
.Select(p =>
{
// Pass the same context parameter for ILambdaContext that comes from the generated method.
if (p.Type.FullName == TypeFullNames.ILambdaContext)
{
return "__context__";
}
return p.Name;
}));
foreach (var parameter in _model.LambdaMethod.Parameters)
{
if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
#line default
#line hidden
this.Write(" var ");
#line 25 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 25 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">();\r\n");
#line 26 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
}
}
if (_model.LambdaMethod.ReturnsVoid)
{
#line default
#line hidden
this.Write(" ");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 33 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 34 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
}
else if (_model.LambdaMethod.ReturnsVoidTask)
{
#line default
#line hidden
this.Write(" await ");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 39 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 40 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
}
else
{
#line default
#line hidden
this.Write(" return ");
#line 45 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnsGenericTask ? "await " : ""));
#line default
#line hidden
#line 45 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 45 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 45 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 46 "C:\codebase\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\NoEventMethodBody.tt"
}
#line default
#line hidden
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class NoEventMethodBodyBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 461 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
public partial class NoEventMethodBody
{
private readonly LambdaFunctionModel _model;
public NoEventMethodBody(LambdaFunctionModel model)
{
_model = model;
}
}
} | 14 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
namespace Amazon.Lambda.Annotations.SourceGenerator.Validation
{
public static class RouteParametersValidator
{
public static (bool isValid, IList<string> missingParameters) Validate(HashSet<string> routeParameters, IList<ParameterModel> lambdaMethodParameters)
{
var missingRouteParams = new List<string>();
var isValid = true;
foreach (var routeParam in routeParameters)
{
var fromRouteMethodParam = lambdaMethodParameters
.FirstOrDefault(p => p.Attributes.Any(att => (att as AttributeModel<FromRouteAttribute>)?.Data.Name == routeParam));
// Route parameter valid because there is a matching signature parameter with a FromRoute attribute
if (fromRouteMethodParam != null)
{
continue;
}
var nameMatchingMethodParam = lambdaMethodParameters.FirstOrDefault(p => p.Name == routeParam);
// Route parameter invalid because there is no matching parameter name
if (nameMatchingMethodParam == null)
{
missingRouteParams.Add(routeParam);
isValid = false;
continue;
}
// There exists a route parameter matching with method parameter name but also has one of conflicting From attribute
var conflictingAttributes = nameMatchingMethodParam.Attributes.Where(att => att.Type.FullName.StartsWith(Namespaces.Annotations)).ToList();
if (conflictingAttributes.Count != 0)
{
throw new InvalidOperationException($"Conflicting attribute(s) {string.Join(",", conflictingAttributes.Select(att => att.Type.FullName))} found on {nameMatchingMethodParam.Name} method parameter.");
}
}
return (isValid, missingRouteParams);
}
}
} | 49 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.SourceGenerator.Diagnostics;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
/// <summary>
/// This class contains methods to manipulate the AWS serverless template.
/// It takes the metadata captured by <see cref="AnnotationReport"/> and writes it to the AWS SAM template.
/// <see href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html">see here</see> to know more about configurable properties for AWS::Serverless::Function
/// <see href="https://github.com/aws/aws-lambda-dotnet/blob/master/Libraries/test/TestServerlessApp/serverless.template">see here</see> for an actual serverless template.
/// </summary>
public class CloudFormationWriter : IAnnotationReportWriter
{
private const string CREATION_TOOL = "Amazon.Lambda.Annotations";
private const string PARAMETERS = "Parameters";
private const string GET_ATTRIBUTE = "Fn::GetAtt";
private const string REF = "Ref";
// Constants related to the message we append to the CloudFormation template description
private const string BASE_DESCRIPTION = "This template is partially managed by Amazon.Lambda.Annotations";
private const string END_OF_VESRION_IN_DESCRIPTION = ").";
private readonly IFileManager _fileManager;
private readonly IDirectoryManager _directoryManager;
private readonly ITemplateWriter _templateWriter;
private readonly IDiagnosticReporter _diagnosticReporter;
public CloudFormationWriter(IFileManager fileManager, IDirectoryManager directoryManager, ITemplateWriter templateWriter, IDiagnosticReporter diagnosticReporter)
{
_fileManager = fileManager;
_directoryManager = directoryManager;
_diagnosticReporter = diagnosticReporter;
_templateWriter = templateWriter;
}
/// <summary>
/// It takes the metadata captured by <see cref="AnnotationReport"/> and writes it to the AWS SAM template.
/// </summary>
public void ApplyReport(AnnotationReport report)
{
var originalContent = _fileManager.ReadAllText(report.CloudFormationTemplatePath);
var templateDirectory = _directoryManager.GetDirectoryName(report.CloudFormationTemplatePath);
var relativeProjectUri = _directoryManager.GetRelativePath(templateDirectory, report.ProjectRootDirectory);
if (string.IsNullOrEmpty(originalContent))
CreateNewTemplate();
else
_templateWriter.Parse(originalContent);
ProcessTemplateDescription(report);
var processedLambdaFunctions = new HashSet<string>();
foreach (var lambdaFunction in report.LambdaFunctions)
{
if (!ShouldProcessLambdaFunction(lambdaFunction))
continue;
ProcessLambdaFunction(lambdaFunction, relativeProjectUri);
processedLambdaFunctions.Add(lambdaFunction.ResourceName);
}
RemoveOrphanedLambdaFunctions(processedLambdaFunctions);
var content = _templateWriter.GetContent();
_fileManager.WriteAllText(report.CloudFormationTemplatePath, content);
_diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGeneration, Location.None, $"{report.CloudFormationTemplatePath}", content));
}
/// <summary>
/// Determines if the Lambda function and its properties should be written to the serverless template.
/// It checks the 'Resources.FUNCTION_NAME' path in the serverless template.
/// If the path does not exist, then the function should be processed and its properties must be persisted.
/// If the path exists, the function will only be processed if 'Resources.FUNCTION_NAME.Metadata.Tool' == 'Amazon.Lambda.Annotations'/>
/// </summary>
private bool ShouldProcessLambdaFunction(ILambdaFunctionSerializable lambdaFunction)
{
var lambdaFunctionPath = $"Resources.{lambdaFunction.ResourceName}";
if (!_templateWriter.Exists(lambdaFunctionPath))
return true;
var creationTool = _templateWriter.GetToken<string>($"{lambdaFunctionPath}.Metadata.Tool", string.Empty);
return string.Equals(creationTool, CREATION_TOOL, StringComparison.Ordinal);
}
/// <summary>
/// Captures different properties specified by <see cref="ILambdaFunctionSerializable"/> and attributes specified by <see cref="AttributeModel{T}"/>
/// and writes it to the serverless template.
/// </summary>
private void ProcessLambdaFunction(ILambdaFunctionSerializable lambdaFunction, string relativeProjectUri)
{
var lambdaFunctionPath = $"Resources.{lambdaFunction.ResourceName}";
var propertiesPath = $"{lambdaFunctionPath}.Properties";
if (!_templateWriter.Exists(lambdaFunctionPath))
ApplyLambdaFunctionDefaults(lambdaFunctionPath, propertiesPath);
ProcessLambdaFunctionProperties(lambdaFunction, propertiesPath, relativeProjectUri);
ProcessLambdaFunctionEventAttributes(lambdaFunction);
}
/// <summary>
/// Captures different properties specified by <see cref="ILambdaFunctionSerializable"/> and writes it to the serverless template
/// All properties are specified under 'Resources.FUNCTION_NAME.Properties' path.
/// </summary>
private void ProcessLambdaFunctionProperties(ILambdaFunctionSerializable lambdaFunction, string propertiesPath, string relativeProjectUri)
{
if (lambdaFunction.Timeout > 0)
_templateWriter.SetToken($"{propertiesPath}.Timeout", lambdaFunction.Timeout);
if (lambdaFunction.MemorySize > 0)
_templateWriter.SetToken($"{propertiesPath}.MemorySize", lambdaFunction.MemorySize);
if (!string.IsNullOrEmpty(lambdaFunction.Role))
{
ProcessLambdaFunctionRole(lambdaFunction, $"{propertiesPath}.Role");
_templateWriter.RemoveToken($"{propertiesPath}.Policies");
}
if (!string.IsNullOrEmpty(lambdaFunction.Policies))
{
var policyArray = lambdaFunction.Policies.Split(',').Select(x => _templateWriter.GetValueOrRef(x.Trim())).ToList();
_templateWriter.SetToken($"{propertiesPath}.Policies", policyArray, TokenType.List);
_templateWriter.RemoveToken($"{propertiesPath}.Role");
}
ProcessPackageTypeProperty(lambdaFunction, propertiesPath, relativeProjectUri);
}
/// <summary>
/// Specifies the deployment package type in the serverless template.
/// The package type property is specified under 'Resources.FUNCTION_NAME.Properties.PackageType' path.
/// Depending on the package type, some non-relevant properties will be removed.
/// </summary>
private void ProcessPackageTypeProperty(ILambdaFunctionSerializable lambdaFunction, string propertiesPath, string relativeProjectUri)
{
_templateWriter.SetToken($"{propertiesPath}.PackageType", lambdaFunction.PackageType.ToString());
switch (lambdaFunction.PackageType)
{
case LambdaPackageType.Zip:
_templateWriter.SetToken($"{propertiesPath}.CodeUri", relativeProjectUri);
_templateWriter.SetToken($"{propertiesPath}.Handler", lambdaFunction.Handler);
_templateWriter.RemoveToken($"{propertiesPath}.ImageUri");
_templateWriter.RemoveToken($"{propertiesPath}.ImageConfig");
break;
case LambdaPackageType.Image:
_templateWriter.SetToken($"{propertiesPath}.ImageUri", relativeProjectUri);
_templateWriter.SetToken($"{propertiesPath}.ImageConfig.Command", new List<string>{lambdaFunction.Handler}, TokenType.List);
_templateWriter.RemoveToken($"{propertiesPath}.Handler");
_templateWriter.RemoveToken($"{propertiesPath}.CodeUri");
_templateWriter.RemoveToken($"{propertiesPath}.Runtime");
break;
default:
throw new InvalidEnumArgumentException($"The {nameof(lambdaFunction.PackageType)} does not match any supported enums of type {nameof(LambdaPackageType)}");
}
}
/// <summary>
/// Writes all attributes captured at <see cref="ILambdaFunctionSerializable.Attributes"/> to the serverless template.
/// It also removes all events that exist in the serverless template but were not encountered during the current source generation pass.
/// All events are specified under 'Resources.FUNCTION_NAME.Properties.Events' path.
/// </summary>
private void ProcessLambdaFunctionEventAttributes(ILambdaFunctionSerializable lambdaFunction)
{
var currentSyncedEvents = new List<string>();
foreach (var attributeModel in lambdaFunction.Attributes)
{
string eventName;
switch (attributeModel)
{
case AttributeModel<HttpApiAttribute> httpApiAttributeModel:
eventName = ProcessHttpApiAttribute(lambdaFunction, httpApiAttributeModel.Data);
currentSyncedEvents.Add(eventName);
break;
case AttributeModel<RestApiAttribute> restApiAttributeModel:
eventName = ProcessRestApiAttribute(lambdaFunction, restApiAttributeModel.Data);
currentSyncedEvents.Add(eventName);
break;
}
}
var eventsPath = $"Resources.{lambdaFunction.ResourceName}.Properties.Events";
var syncedEventsMetadataPath = $"Resources.{lambdaFunction.ResourceName}.Metadata.SyncedEvents";
var previousSyncedEvents = _templateWriter.GetToken<List<string>>(syncedEventsMetadataPath, new List<string>());
// Remove all events that exist in the serverless template but were not encountered during the current source generation pass.
foreach (var previousEventName in previousSyncedEvents)
{
if (!currentSyncedEvents.Contains(previousEventName))
_templateWriter.RemoveToken($"{eventsPath}.{previousEventName}");
}
if (currentSyncedEvents.Any())
_templateWriter.SetToken(syncedEventsMetadataPath, currentSyncedEvents, TokenType.List);
else
_templateWriter.RemoveToken(syncedEventsMetadataPath);
}
/// <summary>
/// Writes all properties associated with <see cref="RestApiAttribute"/> to the serverless template.
/// </summary>
private string ProcessRestApiAttribute(ILambdaFunctionSerializable lambdaFunction, RestApiAttribute restApiAttribute)
{
var eventPath = $"Resources.{lambdaFunction.ResourceName}.Properties.Events";
var methodName = restApiAttribute.Method.ToString();
var methodPath = $"{eventPath}.Root{methodName}";
_templateWriter.SetToken($"{methodPath}.Type", "Api");
_templateWriter.SetToken($"{methodPath}.Properties.Path", restApiAttribute.Template);
_templateWriter.SetToken($"{methodPath}.Properties.Method", methodName.ToUpper());
return $"Root{methodName}";
}
/// <summary>
/// Writes all properties associated with <see cref="HttpApiAttribute"/> to the serverless template.
/// </summary>
private string ProcessHttpApiAttribute(ILambdaFunctionSerializable lambdaFunction, HttpApiAttribute httpApiAttribute)
{
var eventPath = $"Resources.{lambdaFunction.ResourceName}.Properties.Events";
var methodName = httpApiAttribute.Method.ToString();
var methodPath = $"{eventPath}.Root{methodName}";
_templateWriter.SetToken($"{methodPath}.Type", "HttpApi");
_templateWriter.SetToken($"{methodPath}.Properties.Path", httpApiAttribute.Template);
_templateWriter.SetToken($"{methodPath}.Properties.Method", methodName.ToUpper());
// Only set the PayloadFormatVersion for 1.0.
// If no PayloadFormatVersion is specified then by default 2.0 is used.
if (httpApiAttribute.Version == HttpApiVersion.V1)
_templateWriter.SetToken($"{methodPath}.Properties.PayloadFormatVersion", "1.0");
return $"Root{methodName}";
}
/// <summary>
/// Writes the default values for the Lambda function's metadata and properties.
/// </summary>
private void ApplyLambdaFunctionDefaults(string lambdaFunctionPath, string propertiesPath)
{
_templateWriter.SetToken($"{lambdaFunctionPath}.Type", "AWS::Serverless::Function");
_templateWriter.SetToken($"{lambdaFunctionPath}.Metadata.Tool", CREATION_TOOL);
_templateWriter.SetToken($"{propertiesPath}.Runtime", "dotnet6");
_templateWriter.SetToken($"{propertiesPath}.CodeUri", "");
_templateWriter.SetToken($"{propertiesPath}.MemorySize", 256);
_templateWriter.SetToken($"{propertiesPath}.Timeout", 30);
_templateWriter.SetToken($"{propertiesPath}.Policies", new List<string>{"AWSLambdaBasicExecutionRole"}, TokenType.List);
}
/// <summary>
/// Creates a new serverless template with no resources.
/// </summary>
private void CreateNewTemplate()
{
_templateWriter.SetToken("AWSTemplateFormatVersion", "2010-09-09");
_templateWriter.SetToken("Transform", "AWS::Serverless-2016-10-31");
}
/// <summary>
/// Removes all Lambda functions that exist in the serverless template but were not encountered during the current source generation pass.
/// Any resource that is removed must be of type 'AWS::Serverless::Function' and must have 'Resources.FUNCTION_NAME.Metadata.Tool' == 'Amazon.Lambda.Annotations'.
/// </summary>
private void RemoveOrphanedLambdaFunctions(HashSet<string> processedLambdaFunctions)
{
if (!_templateWriter.Exists("Resources"))
{
return;
}
var toRemove = new List<string>();
foreach (var resourceName in _templateWriter.GetKeys("Resources"))
{
var resourcePath = $"Resources.{resourceName}";
var type = _templateWriter.GetToken<string>($"{resourcePath}.Type", string.Empty);
var creationTool = _templateWriter.GetToken<string>($"{resourcePath}.Metadata.Tool", string.Empty);
if (string.Equals(type, "AWS::Serverless::Function", StringComparison.Ordinal)
&& string.Equals(creationTool, "Amazon.Lambda.Annotations", StringComparison.Ordinal)
&& !processedLambdaFunctions.Contains(resourceName))
{
toRemove.Add(resourceName);
}
}
foreach (var resourceName in toRemove)
{
_templateWriter.RemoveToken($"Resources.{resourceName}");
}
}
/// <summary>
/// Write the IAM role associated with the Lambda function.
/// The IAM role is specified under 'Resources.FUNCTION_NAME.Properties.Role' path.
/// </summary>
private void ProcessLambdaFunctionRole(ILambdaFunctionSerializable lambdaFunction, string rolePath)
{
if (string.IsNullOrEmpty(lambdaFunction.Role))
{
return;
}
if (!lambdaFunction.Role.StartsWith("@"))
{
_templateWriter.SetToken(rolePath, lambdaFunction.Role);
return;
}
var role = lambdaFunction.Role.Substring(1);
if (_templateWriter.Exists($"{PARAMETERS}.{role}"))
{
_templateWriter.SetToken($"{rolePath}.{REF}", role);
}
else
{
_templateWriter.SetToken($"{rolePath}.{GET_ATTRIBUTE}", new List<string>{role, "Arn"}, TokenType.List);
}
}
/// <summary>
/// Suffix that is appended to the CloudFormation template with the name
/// and version of the Lambda Annotations library
/// </summary>
public static string CurrentDescriptionSuffix
{
get
{
var version = Assembly.GetAssembly(MethodBase.GetCurrentMethod().DeclaringType).GetName().Version.ToString();
return $"{BASE_DESCRIPTION} (v{version}).";
}
}
/// <summary>
/// This appends a string to the CloudFormation template description field with the version
/// of Lambda Annotations that was used during compilation.
///
/// This string allows AWS to report on these templates to measure the usage of this framework.
/// This aids investigations and outreach if we find a critical bug,
/// helps understanding our version adoption, and allows us to prioritize improvements to this
/// library against other .NET projects.
/// </summary>
private void ProcessTemplateDescription(AnnotationReport report)
{
if (report.IsTelemetrySuppressed)
{
RemoveTemplateDescriptionIfSet();
}
else
{
SetOrUpdateTemplateDescription();
}
}
/// <summary>
/// Either appends the new version suffix in the CloudFormation template
/// description, or updates it if an older version is found.
/// </summary>
private void SetOrUpdateTemplateDescription()
{
string updatedDescription;
if (_templateWriter.Exists("Description"))
{
var existingDescription = _templateWriter.GetToken<string>("Description");
var existingDescriptionSuffix = ExtractCurrentDescriptionSuffix(existingDescription);
if (!string.IsNullOrEmpty(existingDescriptionSuffix))
{
updatedDescription = existingDescription.Replace(existingDescriptionSuffix, CurrentDescriptionSuffix);
}
else if (!string.IsNullOrEmpty(existingDescription)) // The version string isn't in the current description, so we just append it.
{
updatedDescription = existingDescription + " " + CurrentDescriptionSuffix;
}
else // "Description" path exists but is null or empty, so just overwrite it
{
updatedDescription = CurrentDescriptionSuffix;
}
}
else // the "Description" path doesn't exist, so set it
{
updatedDescription = CurrentDescriptionSuffix;
}
// In any case if the updated description is longer than CloudFormation's limit, fall back to the existing one.
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-description-structure.html
if (updatedDescription.Length > 1024)
{
return;
}
_templateWriter.SetToken("Description", updatedDescription);
}
/// <summary>
/// Removes the version suffix from a CloudFormation template descripton
/// </summary>
private void RemoveTemplateDescriptionIfSet()
{
if (!_templateWriter.Exists("Description"))
{
return;
}
var existingDescription = _templateWriter.GetToken<string>("Description");
var existingDescriptionSuffix = ExtractCurrentDescriptionSuffix(existingDescription);
if (string.IsNullOrEmpty(existingDescriptionSuffix))
{
return;
}
var updatedDescription = existingDescription.Replace(existingDescriptionSuffix, "");
_templateWriter.SetToken("Description", updatedDescription);
}
/// <summary>
/// Extracts the version suffix from a CloudFormation template description
/// </summary>
/// <param name="templateDescription"></param>
/// <returns></returns>
private string ExtractCurrentDescriptionSuffix(string templateDescription)
{
var startIndex = templateDescription.IndexOf(BASE_DESCRIPTION);
if (startIndex >= 0)
{
// Find the next ")." which will be the end of the old version string
var endIndex = templateDescription.IndexOf(END_OF_VESRION_IN_DESCRIPTION, startIndex);
// If we couldn't find the end of our version string, it's only a fragment, so abort.
if (endIndex == -1)
{
return string.Empty;
}
var lengthOfCurrentDescription = endIndex + END_OF_VESRION_IN_DESCRIPTION.Length - startIndex;
return templateDescription.Substring(startIndex, lengthOfCurrentDescription);
}
return string.Empty;
}
}
} | 460 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Annotations.SourceGenerator.Models;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
public interface IAnnotationReportWriter
{
void ApplyReport(AnnotationReport report);
}
} | 9 |
aws-lambda-dotnet | aws | C# | using System.Collections;
using System.Collections.Generic;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
/// <summary>
/// This interface contains utility methods to manipulate a YAML or JSON blob
/// </summary>
public interface ITemplateWriter
{
/// <summary>
/// Checks if the dot(.) seperated path exists in the blob
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <returns>true if the path exist, else false</returns>
bool Exists(string path);
/// <summary>
/// Gets the object stored at the dot(.) seperated path. If the path does not exist then return the defaultToken.
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if path does not exist.</param>
object GetToken(string path, object defaultToken = null);
/// <summary>
/// Gets the object stored at the dot(.) seperated path. If the path does not exist then return the defaultToken.
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if path does not exist.</param>
T GetToken<T>(string path, object defaultToken = null);
/// <summary>
/// Sets the token at the dot(.) seperated path.
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="token">The object to set at the specified path</param>
/// <param name="tokenType"><see cref="TokenType"/></param>
void SetToken(string path, object token, TokenType tokenType = TokenType.Other);
/// <summary>
/// Deletes the token found at the dot(.) separated path.
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
void RemoveToken(string path);
/// <summary>
/// Returns the template as a string
/// </summary>
string GetContent();
/// <summary>
/// Converts the content into an in-memory representation of JSON or YAML node
/// </summary>
/// <param name="content"></param>
void Parse(string content);
/// <summary>
/// If the string does not start with '@', return it as is.
/// If a string value starts with '@' then a reference node is created and returned.
/// </summary>
object GetValueOrRef(string value);
/// <summary>
/// Retrieves a list of keys for a specified template path.
/// </summary>
/// <param name="path">dot(.) seperated path. Example "Person.Name.FirstName"</param>
IList<string> GetKeys(string path);
}
} | 69 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
/// <summary>
/// This contains the functionality to manipulate a JSON blob
/// </summary>
public class JsonWriter : ITemplateWriter
{
private JObject _rootNode;
public JsonWriter()
{
_rootNode = new JObject();
}
/// <summary>
/// Checks if the dot(.) seperated jsonPath exists in the json blob stored at the _rootNode
/// </summary>
/// <param name="jsonPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <returns>true if the path exist, else false</returns>
/// <exception cref="InvalidDataException">Thrown if the jsonPath is invalid</exception>
public bool Exists(string jsonPath)
{
if (!IsValidPath(jsonPath))
{
throw new InvalidDataException($"'{jsonPath}' is not a valid '{nameof(jsonPath)}'");
}
JToken currentNode = _rootNode;
foreach (var property in jsonPath.Split('.'))
{
if (currentNode == null)
{
return false;
}
currentNode = currentNode[property];
}
return currentNode != null;
}
/// <summary>
/// This method converts the supplied token it into a <see cref="JToken"/> type and sets it at the dot(.) seperated jsonPath.
/// Any non-existing nodes in the jsonPath are created on the fly.
/// All non-terminal nodes in the jsonPath need to be of type <see cref="JObject"/>.
/// </summary>
/// <param name="jsonPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="token">The object to set at the specified jsonPath</param>
/// <param name="tokenType"><see cref="TokenType"/>This does not play any role while setting a token for the JsonWriter</param>
/// <exception cref="InvalidDataException">Thrown if the jsonPath is invalid</exception>
/// <exception cref="InvalidOperationException">Thrown if the terminal property in the jsonPath is null/empty or if any non-terminal nodes in the jsonPath cannot be converted to <see cref="JObject"/></exception>
public void SetToken(string jsonPath, object token, TokenType tokenType = TokenType.Other)
{
if (!IsValidPath(jsonPath))
{
throw new InvalidDataException($"'{jsonPath}' is not a valid '{nameof(jsonPath)}'");
}
if (token == null)
{
return;
}
var pathList = jsonPath.Split('.');
var lastProperty = pathList.LastOrDefault();
if (string.IsNullOrEmpty((lastProperty)))
{
throw new InvalidOperationException($"Cannot set a token at '{jsonPath}' because the terminal property is null or empty");
}
var terminalToken = GetDeserializedToken<JToken>(token);
var currentNode = _rootNode;
for (var i = 0; i < pathList.Length-1; i++)
{
if (currentNode == null)
{
throw new InvalidOperationException($"Cannot set a token at '{jsonPath}' because one of the nodes in the path is null");
}
var property = pathList[i];
if (!currentNode.ContainsKey(property))
{
currentNode[property] = new JObject();
}
currentNode = currentNode[property] as JObject;
if (currentNode == null)
{
throw new InvalidOperationException($"Cannot set a value at '{jsonPath}' because the token at {property} does not represent a {typeof(JObject)}");
}
}
currentNode[lastProperty] = terminalToken;
}
/// <summary>
/// Gets the object stored at the dot(.) seperated jsonPath. If the path does not exist then return the defaultToken.
/// The defaultToken is only returned if it holds a non-null value.
/// </summary>
/// <param name="jsonPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if jsonPath does not exist.</param>
/// <exception cref="InvalidOperationException">Thrown if the jsonPath does not exist and the defaultToken is null</exception>
public object GetToken(string jsonPath, object defaultToken = null)
{
if (!Exists(jsonPath))
{
if (defaultToken != null)
{
return defaultToken;
}
throw new InvalidOperationException($"'{jsonPath}' does not exist in the JSON model");
}
JToken currentNode = _rootNode;
foreach (var property in jsonPath.Split('.'))
{
currentNode = currentNode[property];
}
return currentNode;
}
/// <summary>
/// Gets the object stored at the dot(.) seperated jsonPath. If the path does not exist then return the defaultToken.
/// The defaultToken is only returned if it holds a non-null value.
/// The object is deserialized into type T before being returned.
/// </summary>
/// <param name="jsonPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if jsonPath does not exist in the JSON blob. It will be convert to type T before being returned.</param>
/// <exception cref="InvalidOperationException">Thrown if the jsonPath does not exist and the defaultToken is null</exception>
public T GetToken<T>(string jsonPath, object defaultToken = null)
{
var token = GetToken(jsonPath, defaultToken);
if (token == null)
{
throw new InvalidOperationException($"'{jsonPath}' points to a null token");
}
return GetDeserializedToken<T>(token);
}
/// <summary>
/// Deletes the token found at the dot(.) separated jsonPath. It does not do anything if the jsonPath does not exist.
/// </summary>
/// <param name="jsonPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <exception cref="InvalidOperationException">Thrown if the terminal property in jsonPath is null or empty</exception>
public void RemoveToken(string jsonPath)
{
if (!Exists(jsonPath))
{
return;
}
var pathList = jsonPath.Split('.');
var lastProperty = pathList.LastOrDefault();
if (string.IsNullOrEmpty(lastProperty))
{
throw new InvalidOperationException(
$"Cannot remove the token at '{jsonPath}' because the terminal property is null or empty");
}
var currentNode = _rootNode;
for (var i = 0; i < pathList.Length-1; i++)
{
var property = pathList[i];
currentNode = currentNode[property] as JObject;
}
currentNode.Remove(lastProperty);
}
/// <summary>
/// Returns the template as a string
/// </summary>
public string GetContent()
{
return JsonConvert.SerializeObject(_rootNode, formatting: Formatting.Indented);
}
/// <summary>
/// Converts the JSON string into a <see cref="JObject"/>
/// </summary>
/// <param name="content"></param>
public void Parse(string content)
{
_rootNode = string.IsNullOrEmpty(content) ? new JObject() : JObject.Parse(content);
}
/// <summary>
/// If the string does not start with '@', return it as is.
/// If a string value starts with '@' then a reference node is created and returned.
/// </summary>
public object GetValueOrRef(string value)
{
if (!value.StartsWith("@"))
return value;
var jsonNode = new JObject();
jsonNode["Ref"] = value.Substring(1);
return jsonNode;
}
/// <summary>
/// Validates that the jsonPath is not null or comprises only of white spaces. Also ensures that it does not have consecutive dots(.)
/// </summary>
/// <param name="jsonPath"></param>
/// <returns>true if the path is valid, else fail</returns>
private bool IsValidPath(string jsonPath)
{
if (string.IsNullOrWhiteSpace(jsonPath))
return false;
return !jsonPath.Split('.').Any(string.IsNullOrWhiteSpace);
}
private T GetDeserializedToken<T>(object token)
{
if (token is T deserializedToken)
{
return deserializedToken;
}
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(token));
}
public IList<string> GetKeys(string path)
{
try
{
return GetToken<Dictionary<string, object>>(path).Keys.ToList();
}
catch (Exception ex)
{
throw new InvalidOperationException($"Unable to retrieve keys for the specified JSON path '{path}'.", ex);
}
}
}
} | 242 |
aws-lambda-dotnet | aws | C# | using YamlDotNet.RepresentationModel;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
/// <summary>
/// These enums dictate the deserialized <see cref="YamlNode"/> type during the invocation of YamlWriter.SetToken(..)
/// These token types do not play any roles when using a jsonWriter.
/// </summary>
public enum TokenType
{
/// <summary>
/// This token type is deserialized to a <see cref="YamlSequenceNode"/>.
/// </summary>
List,
/// <summary>
/// This token type is deserialized to a <see cref="YamlMappingNode"/>.
/// </summary>
KeyVal,
/// <summary>
/// This token type is deserialized to a <see cref="YamlMappingNode"/>.
/// </summary>
Object,
/// <summary>
/// This token type is deserialized to a <see cref="YamlScalarNode"/>.
/// </summary>
Other
}
} | 31 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;
namespace Amazon.Lambda.Annotations.SourceGenerator.Writers
{
/// <summary>
/// This contains the functionality to manipulate a YAML blob
/// </summary>
public class YamlWriter : ITemplateWriter
{
private YamlMappingNode _rootNode;
private readonly Serializer _serializer = new Serializer();
private readonly Deserializer _deserializer = new Deserializer();
private readonly SerializerBuilder _serializerBuilder = new SerializerBuilder();
public YamlWriter()
{
_rootNode = new YamlMappingNode();
}
/// <summary>
/// Checks if the dot(.) seperated yamlPath exists in the YAML blob stored at the _rootNode
/// </summary>
/// <param name="yamlPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <returns>true if the path exist, else false</returns>
/// <exception cref="InvalidDataException">Thrown if the yamlPath is invalid</exception>
public bool Exists(string yamlPath)
{
if (!IsValidPath(yamlPath))
{
throw new InvalidDataException($"'{yamlPath}' is not a valid {nameof(yamlPath)}");
}
YamlNode currentNode = _rootNode;
foreach (var property in yamlPath.Split('.'))
{
if (currentNode == null)
{
return false;
}
try
{
currentNode = currentNode[property];
}
catch (KeyNotFoundException)
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the object stored at the dot(.) seperated yamlPath. If the path does not exist then return the defaultToken.
/// The defaultToken is only returned if it holds a non-null value.
/// </summary>
/// <param name="yamlPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if yamlPath does not exist.</param>
/// <exception cref="InvalidOperationException">Thrown if the yamlPath does not exist and the defaultToken is null</exception>
public object GetToken(string yamlPath, object defaultToken = null)
{
if (!Exists(yamlPath))
{
if (defaultToken != null)
{
return defaultToken;
}
throw new InvalidOperationException($"'{yamlPath}' does not exist in the JSON model");
}
YamlNode currentNode = _rootNode;
foreach (var property in yamlPath.Split('.'))
{
currentNode = currentNode[property];
}
return currentNode;
}
/// <summary>
/// Gets the object stored at the dot(.) seperated yamlPath. If the path does not exist then return the defaultToken.
/// The defaultToken is only returned if it holds a non-null value.
/// The object is deserialized into type T before being returned.
/// </summary>
/// <param name="yamlPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="defaultToken">The object that is returned if yamlPath does not exist in the YAML blob. It will be convert to type T before being returned.</param>
/// <exception cref="InvalidOperationException">Thrown if the yamlPath does not exist and the defaultToken is null</exception>
public T GetToken<T>(string yamlPath, object defaultToken = null)
{
var token = GetToken(yamlPath, defaultToken);
if (token == null)
{
throw new InvalidOperationException($"'{yamlPath}' points to a null token");
}
return GetDeserializedToken<T>(token);
}
/// <summary>
/// This method converts the supplied token it into a concrete <see cref="YamlNode"/> type and sets it at the dot(.) seperated yamlPath.
/// Any non-existing nodes in the yamlPath are created on the fly.
/// All non-terminal nodes in the yamlPath need to be of type <see cref="YamlNodeType.Mapping"/>.
/// </summary>
/// <param name="yamlPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <param name="token">The object to set at the specified yamlPath</param>
/// <param name="tokenType"><see cref="TokenType"/></param>
/// <exception cref="InvalidDataException">Thrown if the yamlPath is invalid</exception>
/// <exception cref="InvalidOperationException">Thrown if the terminal property in the yamlPath is null/empty or if any non-terminal nodes in the yamlPath cannot be converted to <see cref="YamlMappingNode"/></exception>
public void SetToken(string yamlPath, object token, TokenType tokenType = TokenType.Other)
{
if (!IsValidPath(yamlPath))
{
throw new InvalidDataException($"'{yamlPath}' is not a valid '{nameof(yamlPath)}'");
}
if (token == null)
{
return;
}
var pathList = yamlPath.Split('.');
var lastProperty = pathList.LastOrDefault();
if (string.IsNullOrEmpty(lastProperty))
{
throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because the terminal property is null or empty");
}
YamlNode terminalToken;
if (token is YamlNode yamlNode)
{
terminalToken = yamlNode;
}
else
{
switch (tokenType)
{
case TokenType.List:
terminalToken = GetDeserializedToken<YamlSequenceNode>(token);
break;
case TokenType.KeyVal:
case TokenType.Object:
terminalToken = GetDeserializedToken<YamlMappingNode>(token);
break;
case TokenType.Other:
terminalToken = GetDeserializedToken<YamlScalarNode>(token);
break;
default:
throw new InvalidOperationException($"Failed to deserialize token because {nameof(tokenType)} is invalid");
}
}
var currentNode = _rootNode;
for (var i = 0; i < pathList.Length - 1; i++)
{
if (currentNode == null)
{
throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because one of the nodes in the path is null");
}
var property = pathList[i];
try
{
currentNode = (YamlMappingNode)currentNode[property];
}
catch (KeyNotFoundException)
{
currentNode.Children[property] = new YamlMappingNode();
currentNode = (YamlMappingNode)currentNode[property];
}
catch (InvalidCastException)
{
throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because one of the nodes in the path cannot be converted to {nameof(YamlMappingNode)}");
}
}
currentNode.Children[lastProperty] = terminalToken;
}
/// <summary>
/// Deletes the token found at the dot(.) separated yamlPath. It does not do anything if the yamlPath does not exist.
/// </summary>
/// <param name="yamlPath">dot(.) seperated path. Example "Person.Name.FirstName"</param>
/// <exception cref="InvalidOperationException"></exception>
public void RemoveToken(string yamlPath)
{
if (!Exists(yamlPath))
{
return;
}
var pathList = yamlPath.Split('.');
var lastProperty = pathList.LastOrDefault();
if (string.IsNullOrEmpty(lastProperty))
{
throw new InvalidOperationException(
$"Cannot remove the token at '{yamlPath}' because the terminal property is null or empty");
}
YamlNode currentNode = _rootNode;
for (var i = 0; i < pathList.Length - 1; i++)
{
var property = pathList[i];
currentNode = currentNode[property];
}
var terminalNode = (YamlMappingNode)currentNode;
terminalNode.Children.Remove(lastProperty);
}
/// <summary>
/// Parses the YAML string as a <see cref="YamlMappingNode"/>
/// </summary>
/// <param name="content"></param>
public void Parse(string content)
{
_rootNode = string.IsNullOrEmpty(content)
? new YamlMappingNode()
: _deserializer.Deserialize<YamlMappingNode>(content);
}
/// <summary>
/// Converts the <see cref="YamlMappingNode"/> to a YAML string
/// </summary>
public string GetContent()
{
return _serializerBuilder
.WithIndentedSequences()
.Build()
.Serialize(_rootNode);
}
/// <summary>
/// If the string does not start with '@', return it as is.
/// If a string value starts with '@' then a reference node is created and returned.
/// </summary>
public object GetValueOrRef(string value)
{
if (!value.StartsWith("@"))
return value;
var yamlNode = new YamlMappingNode();
yamlNode.Children["Ref"] = value.Substring(1);
return yamlNode;
}
/// <summary>
/// Validates that the yamlPath is not null or comprises only of white spaces. Also ensures that it does not have consecutive dots(.)
/// </summary>
/// <param name="yamlPath"></param>
/// <returns>true if the path is valid, else fail</returns>
private bool IsValidPath(string yamlPath)
{
if (string.IsNullOrWhiteSpace(yamlPath))
return false;
return !yamlPath.Split('.').Any(string.IsNullOrWhiteSpace);
}
private T GetDeserializedToken<T>(object token)
{
if (token is T deserializedToken)
{
return deserializedToken;
}
return _deserializer.Deserialize<T>(_serializer.Serialize(token));
}
public IList<string> GetKeys(string path)
{
try
{
return GetToken<Dictionary<string, YamlMappingNode>>(path).Keys.ToList();
}
catch (Exception ex)
{
throw new InvalidOperationException($"Unable to retrieve keys for the specified YAML path '{path}'.", ex);
}
}
}
} | 287 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
#if NETSTANDARD_2_0
using Newtonsoft.Json.Linq;
#else
using System.Text.Json;
#endif
/// <summary>
/// An object representing the expected format of an API Gateway custom authorizer response.
/// </summary>
[DataContract]
public class APIGatewayCustomAuthorizerContext : Dictionary<string, object>
{
/// <summary>
/// Gets or sets the 'principalId' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"principalId\"]")]
public string PrincipalId
{
get
{
object value;
if (this.TryGetValue("principalId", out value))
return value.ToString();
return null;
}
set
{
this["principalId"] = value;
}
}
/// <summary>
/// Gets or sets the 'stringKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"stringKey\"]")]
public string StringKey
{
get
{
object value;
if (this.TryGetValue("stringKey", out value))
return value.ToString();
return null;
}
set
{
this["stringKey"] = value;
}
}
/// <summary>
/// Gets or sets the 'numKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"numKey\"]")]
public int? NumKey
{
get
{
object value;
if (this.TryGetValue("numKey", out value))
{
int i;
if (int.TryParse(value?.ToString(), out i))
{
return i;
}
}
return null;
}
set
{
this["numKey"] = value;
}
}
/// <summary>
/// Gets or sets the 'boolKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"boolKey\"]")]
public bool? BoolKey
{
get
{
object value;
if (this.TryGetValue("boolKey", out value))
{
bool b;
if(bool.TryParse(value?.ToString(), out b))
{
return b;
}
}
return null;
}
set
{
this["boolKey"] = value;
}
}
Dictionary<string, string> _claims;
/// <summary>
/// Gets or sets the claims coming from Cognito
/// </summary>
public Dictionary<string, string> Claims
{
get
{
if(_claims == null)
{
_claims = new Dictionary<string, string>();
object value;
if(this.TryGetValue("claims", out value))
{
#if NETSTANDARD_2_0
JObject jsonClaims = value as JObject;
if (jsonClaims != null)
{
foreach (JProperty property in jsonClaims.Properties())
{
_claims[property.Name] = property.Value?.ToString();
}
}
#else
if(value is JsonElement jsonClaims)
{
foreach(JsonProperty property in jsonClaims.EnumerateObject())
{
if(property.Value.ValueKind == JsonValueKind.String)
{
_claims[property.Name] = property.Value.GetString();
}
}
}
#endif
}
}
return _claims;
}
set
{
this._claims = value;
}
}
}
}
| 159 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// An object representing the expected format of an API Gateway custom authorizer response.
/// </summary>
[DataContract]
public class APIGatewayCustomAuthorizerContextOutput : Dictionary<string, object>
{
/// <summary>
/// Gets or sets the 'stringKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"stringKey\"]")]
public string StringKey
{
get
{
object value;
if (this.TryGetValue("stringKey", out value))
return value.ToString();
return null;
}
set
{
this["stringKey"] = value;
}
}
/// <summary>
/// Gets or sets the 'numKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"numKey\"]")]
public int? NumKey
{
get
{
object value;
if (this.TryGetValue("numKey", out value))
{
int i;
if (int.TryParse(value?.ToString(), out i))
{
return i;
}
}
return null;
}
set
{
this["numKey"] = value;
}
}
/// <summary>
/// Gets or sets the 'boolKey' property.
/// </summary>
[Obsolete("This property is obsolete. Code should be updated to use the string index property like authorizer[\"boolKey\"]")]
public bool? BoolKey
{
get
{
object value;
if (this.TryGetValue("boolKey", out value))
{
bool b;
if (bool.TryParse(value?.ToString(), out b))
{
return b;
}
}
return null;
}
set
{
this["boolKey"] = value;
}
}
}
}
| 85 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System.Collections.Generic;
/// <summary>
/// An object representing an IAM policy.
/// </summary>
public class APIGatewayCustomAuthorizerPolicy
{
/// <summary>
/// Gets or sets the IAM API version.
/// </summary>
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("Version")]
#endif
public string Version { get; set; } = "2012-10-17";
/// <summary>
/// Gets or sets a list of IAM policy statements to apply.
/// </summary>
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("Statement")]
#endif
public List<IAMPolicyStatement> Statement { get; set; } = new List<IAMPolicyStatement>();
/// <summary>
/// A class representing an IAM Policy Statement.
/// </summary>
public class IAMPolicyStatement
{
/// <summary>
/// Gets or sets the effect the statement has.
/// </summary>
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("Effect")]
#endif
public string Effect { get; set; } = "Allow";
/// <summary>
/// Gets or sets the action/s the statement has.
/// </summary>
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("Action")]
#endif
public HashSet<string> Action { get; set; }
/// <summary>
/// Gets or sets the resources the statement applies to.
/// </summary>
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("Resource")]
#endif
public HashSet<string> Resource { get; set; }
}
}
}
| 57 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// For requests coming in to a custom API Gateway authorizer function.
/// </summary>
public class APIGatewayCustomAuthorizerRequest
{
/// <summary>
/// Gets or sets the 'type' property.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the 'authorizationToken' property.
/// </summary>
public string AuthorizationToken { get; set; }
/// <summary>
/// Gets or sets the 'methodArn' property.
/// </summary>
public string MethodArn { get; set; }
/// <summary>
/// The url path for the caller. For Request type API Gateway Custom Authorizer only.
/// </summary>
public string Path { get; set; }
/// <summary>
/// The HTTP method used. For Request type API Gateway Custom Authorizer only.
/// </summary>
public string HttpMethod { get; set; }
/// <summary>
/// The headers sent with the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> Headers {get;set;}
/// <summary>
/// The query string parameters that were part of the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> QueryStringParameters { get; set; }
/// <summary>
/// The path parameters that were part of the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> PathParameters { get; set; }
/// <summary>
/// The stage variables defined for the stage in API Gateway. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> StageVariables { get; set; }
/// <summary>
/// The request context for the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public APIGatewayProxyRequest.ProxyRequestContext RequestContext { get; set; }
}
}
| 62 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System.Runtime.Serialization;
/// <summary>
/// An object representing the expected format of an API Gateway authorization response.
/// </summary>
[DataContract]
public class APIGatewayCustomAuthorizerResponse
{
/// <summary>
/// Gets or sets the ID of the principal.
/// </summary>
[DataMember(Name = "principalId")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("principalId")]
#endif
public string PrincipalID { get; set; }
/// <summary>
/// Gets or sets the <see cref="APIGatewayCustomAuthorizerPolicy"/> policy document.
/// </summary>
[DataMember(Name = "policyDocument")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("policyDocument")]
#endif
public APIGatewayCustomAuthorizerPolicy PolicyDocument { get; set; } = new APIGatewayCustomAuthorizerPolicy();
/// <summary>
/// Gets or sets the <see cref="APIGatewayCustomAuthorizerContext"/> property.
/// </summary>
[DataMember(Name = "context")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("context")]
#endif
public APIGatewayCustomAuthorizerContextOutput Context { get; set; }
/// <summary>
/// Gets or sets the usageIdentifierKey.
/// </summary>
[DataMember(Name = "usageIdentifierKey")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("usageIdentifierKey")]
#endif
public string UsageIdentifierKey { get; set; }
}
}
| 48 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// An object representing the expected format of an API Gateway authorization response.
/// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html
/// </summary>
[DataContract]
public class APIGatewayCustomAuthorizerV2IamResponse
{
/// <summary>
/// Gets or sets the ID of the principal.
/// </summary>
[DataMember(Name = "principalId")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("principalId")]
#endif
public string PrincipalID { get; set; }
/// <summary>
/// Gets or sets the <see cref="APIGatewayCustomAuthorizerPolicy"/> policy document.
/// </summary>
[DataMember(Name = "policyDocument")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("policyDocument")]
#endif
public APIGatewayCustomAuthorizerPolicy PolicyDocument { get; set; } = new APIGatewayCustomAuthorizerPolicy();
/// <summary>
/// Gets or sets the <see cref="APIGatewayCustomAuthorizerContext"/> property.
/// </summary>
[DataMember(Name = "context")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("context")]
#endif
public Dictionary<string, object> Context { get; set; }
}
}
| 41 |
aws-lambda-dotnet | aws | C# | using System.Collections.Generic;
namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// For requests coming in to a custom API Gateway authorizer function.
/// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html
/// </summary>
public class APIGatewayCustomAuthorizerV2Request
{
/// <summary>
/// Gets or sets the 'type' property.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the 'routeArn' property.
/// </summary>
public string RouteArn { get; set; }
/// <summary>
/// List of identity sources for the request.
/// </summary>
public List<string> IdentitySource { get; set; }
/// <summary>
/// Gets or sets the 'routeKey' property.
/// </summary>
public string RouteKey { get; set; }
/// <summary>
/// Raw url path for the caller.
/// </summary>
public string RawPath { get; set; }
/// <summary>
/// Raw query string for the caller.
/// </summary>
public string RawQueryString { get; set; }
/// <summary>
/// The cookies sent with the request.
/// </summary>
public List<string> Cookies { get; set; }
/// <summary>
/// The headers sent with the request.
/// </summary>
public Dictionary<string, string> Headers { get; set; }
/// <summary>
/// The query string parameters that were part of the request.
/// </summary>
public Dictionary<string, string> QueryStringParameters { get; set; }
/// <summary>
/// The path parameters that were part of the request.
/// </summary>
public Dictionary<string, string> PathParameters { get; set; }
/// <summary>
/// The stage variables defined for the stage in API Gateway.
/// </summary>
public Dictionary<string, string> StageVariables { get; set; }
/// <summary>
/// The request context for the request.
/// </summary>
public APIGatewayHttpApiV2ProxyRequest.ProxyRequestContext RequestContext { get; set; }
}
}
| 72 |
aws-lambda-dotnet | aws | C# | namespace Amazon.Lambda.APIGatewayEvents
{
using System.Collections.Generic;
using System.Runtime.Serialization;
/// <summary>
/// An object representing the expected format of an API Gateway authorization response.
/// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html
/// </summary>
[DataContract]
public class APIGatewayCustomAuthorizerV2SimpleResponse
{
/// <summary>
/// Gets or sets authorization result.
/// </summary>
[DataMember(Name = "isAuthorized")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("isAuthorized")]
#endif
public bool IsAuthorized { get; set; }
/// <summary>
/// Gets or sets the <see cref="APIGatewayCustomAuthorizerContext"/> property.
/// </summary>
[DataMember(Name = "context")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("context")]
#endif
public Dictionary<string, object> Context { get; set; }
}
}
| 32 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// For request using using API Gateway HTTP API version 2 payload proxy format
/// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
/// </summary>
public class APIGatewayHttpApiV2ProxyRequest
{
/// <summary>
/// The payload format version
/// </summary>
public string Version { get; set; }
/// <summary>
/// The route key
/// </summary>
public string RouteKey { get; set; }
/// <summary>
/// The raw path
/// </summary>
public string RawPath { get; set; }
/// <summary>
/// The raw query string
/// </summary>
public string RawQueryString { get; set; }
/// <summary>
/// Cookies sent along with the request
/// </summary>
public string[] Cookies { get; set; }
/// <summary>
/// Headers sent with the request. Multiple values for the same header will be separated by a comma.
/// </summary>
public IDictionary<string, string> Headers { get; set; }
/// <summary>
/// Query string parameters sent with the request. Multiple values for the same parameter will be separated by a comma.
/// </summary>
public IDictionary<string, string> QueryStringParameters { get; set; }
/// <summary>
/// The request context for the request
/// </summary>
public ProxyRequestContext RequestContext { get; set; }
/// <summary>
/// The HTTP request body.
/// </summary>
public string Body { get; set; }
/// <summary>
/// Path parameters sent with the request.
/// </summary>
public IDictionary<string, string> PathParameters { get; set; }
/// <summary>
/// True if the body of the request is base 64 encoded.
/// </summary>
public bool IsBase64Encoded { get; set; }
/// <summary>
/// The stage variables defined for the stage in API Gateway
/// </summary>
public IDictionary<string, string> StageVariables { get; set; }
/// <summary>
/// The ProxyRequestContext contains the information to identify the AWS account and resources invoking the
/// Lambda function.
/// </summary>
public class ProxyRequestContext
{
/// <summary>
/// The account id that owns the executing Lambda function
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// The API Gateway rest API Id.
/// </summary>
public string ApiId { get; set; }
/// <summary>
/// Information about the current requesters authorization including claims and scopes.
/// </summary>
public AuthorizerDescription Authorizer { get; set; }
/// <summary>
/// The domin name.
/// </summary>
public string DomainName { get; set; }
/// <summary>
/// The domain prefix
/// </summary>
public string DomainPrefix { get; set; }
/// <summary>
/// Information about the HTTP request like the method and path.
/// </summary>
public HttpDescription Http {get;set;}
/// <summary>
/// The unique request id
/// </summary>
public string RequestId { get; set; }
/// <summary>
/// The route id
/// </summary>
public string RouteId { get; set; }
/// <summary>
/// The selected route key.
/// </summary>
public string RouteKey { get; set; }
/// <summary>
/// The API Gateway stage name
/// </summary>
public string Stage { get; set; }
/// <summary>
/// Gets and sets the request time.
/// </summary>
public string Time { get; set; }
/// <summary>
/// Gets and sets the request time as an epoch.
/// </summary>
public long TimeEpoch { get; set; }
/// <summary>
/// Properties for authentication.
/// </summary>
public ProxyRequestAuthentication Authentication { get; set; }
}
/// <summary>
/// Container for authentication properties.
/// </summary>
public class ProxyRequestAuthentication
{
/// <summary>
/// Properties for a client certificate.
/// </summary>
public ProxyRequestClientCert ClientCert { get; set; }
}
/// <summary>
/// Container for the properties of the client certificate.
/// </summary>
public class ProxyRequestClientCert
{
/// <summary>
/// The PEM-encoded client certificate that the client presented during mutual TLS authentication.
/// Present when a client accesses an API by using a custom domain name that has mutual
/// TLS enabled. Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string ClientCertPem { get; set; }
/// <summary>
/// The distinguished name of the subject of the certificate that a client presents.
/// Present when a client accesses an API by using a custom domain name that has
/// mutual TLS enabled. Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string SubjectDN { get; set; }
/// <summary>
/// The distinguished name of the issuer of the certificate that a client presents.
/// Present when a client accesses an API by using a custom domain name that has
/// mutual TLS enabled. Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string IssuerDN { get; set; }
/// <summary>
/// The serial number of the certificate. Present when a client accesses an API by
/// using a custom domain name that has mutual TLS enabled.
/// Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string SerialNumber { get; set; }
/// <summary>
/// The rules for when the client cert is valid.
/// </summary>
public ClientCertValidity Validity { get; set; }
}
/// <summary>
/// Container for the validation properties of a client cert.
/// </summary>
public class ClientCertValidity
{
/// <summary>
/// The date before which the certificate is invalid. Present when a client accesses an API by using a custom domain name
/// that has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string NotBefore { get; set; }
/// <summary>
/// The date after which the certificate is invalid. Present when a client accesses an API by using a custom domain name that
/// has mutual TLS enabled. Present only in access logs if mutual TLS authentication fails.
/// </summary>
public string NotAfter { get; set; }
}
/// <summary>
/// Information about the HTTP elements for the request.
/// </summary>
public class HttpDescription
{
/// <summary>
/// The HTTP method like POST or GET.
/// </summary>
public string Method { get; set; }
/// <summary>
/// The path of the request.
/// </summary>
public string Path { get; set; }
/// <summary>
/// The protocal used to make the rquest
/// </summary>
public string Protocol { get; set; }
/// <summary>
/// The source ip for the request.
/// </summary>
public string SourceIp { get; set; }
/// <summary>
/// The user agent for the request.
/// </summary>
public string UserAgent { get; set; }
}
/// <summary>
/// Information about the current requesters authorization.
/// </summary>
public class AuthorizerDescription
{
/// <summary>
/// The JWT description including claims and scopes.
/// </summary>
public JwtDescription Jwt { get; set; }
/// <summary>
/// The Lambda authorizer description
/// </summary>
public IDictionary<string, object> Lambda { get; set; }
/// <summary>
/// The IAM authorizer description
/// </summary>
public IAMDescription IAM { get; set; }
/// <summary>
/// Describes the information from an IAM authorizer
/// </summary>
public class IAMDescription
{
/// <summary>
/// The Access Key of the IAM Authorizer
/// </summary>
public string AccessKey { get; set; }
/// <summary>
/// The Account Id of the IAM Authorizer
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// The Caller Id of the IAM Authorizer
/// </summary>
public string CallerId { get; set; }
/// <summary>
/// The Cognito Identity of the IAM Authorizer
/// </summary>
public CognitoIdentityDescription CognitoIdentity { get; set; }
/// <summary>
/// The Principal Org Id of the IAM Authorizer
/// </summary>
public string PrincipalOrgId { get; set; }
/// <summary>
/// The User ARN of the IAM Authorizer
/// </summary>
public string UserARN { get; set; }
/// <summary>
/// The User Id of the IAM Authorizer
/// </summary>
public string UserId { get; set; }
}
/// <summary>
/// The Cognito identity description for an IAM authorizer
/// </summary>
public class CognitoIdentityDescription
{
/// <summary>
/// The AMR of the IAM Authorizer
/// </summary>
public IList<string> AMR { get; set; }
/// <summary>
/// The Identity Id of the IAM Authorizer
/// </summary>
public string IdentityId { get; set; }
/// <summary>
/// The Identity Pool Id of the IAM Authorizer
/// </summary>
public string IdentityPoolId { get; set; }
}
/// <summary>
/// Describes the information in the JWT token
/// </summary>
public class JwtDescription
{
/// <summary>
/// Map of the claims for the requester.
/// </summary>
public IDictionary<string, string> Claims { get; set; }
/// <summary>
/// List of the scopes for the requester.
/// </summary>
public string[] Scopes { get; set; }
}
}
}
}
| 345 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// The response object for Lambda functions handling request from API Gateway HTTP API v2 proxy format
/// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
/// </summary>
[DataContract]
public class APIGatewayHttpApiV2ProxyResponse
{
/// <summary>
/// The HTTP status code for the request
/// </summary>
[DataMember(Name = "statusCode")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("statusCode")]
#endif
public int StatusCode { get; set; }
/// <summary>
/// The Http headers returned in the response. Multiple header values set for the the same header should be separate by a comma.
/// </summary>
[DataMember(Name = "headers")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("headers")]
#endif
public IDictionary<string, string> Headers { get; set; }
/// <summary>
/// Utility method to set a single or multiple values for a header to the Headers collection.
/// </summary>
/// <param name="headerName"></param>
/// <param name="value"></param>
/// <param name="append">If true it will append the values to the existing value in the Headers collection.</param>
public void SetHeaderValues(string headerName, string value, bool append)
{
SetHeaderValues(headerName, new string[] { value }, append);
}
/// <summary>
/// Utility method to set a single or multiple values for a header to the Headers collection.
/// </summary>
/// <param name="headerName"></param>
/// <param name="values"></param>
/// <param name="append">If true it will append the values to the existing value in the Headers collection.</param>
public void SetHeaderValues(string headerName, IEnumerable<string> values, bool append)
{
if (this.Headers == null)
this.Headers = new Dictionary<string, string>();
if(this.Headers.ContainsKey(headerName) && append)
{
this.Headers[headerName] = this.Headers[headerName] + "," + string.Join(",", values);
}
else
{
this.Headers[headerName] = string.Join(",", values);
}
}
/// <summary>
/// The cookies returned in the response.
/// </summary>
[DataMember(Name = "cookies")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("cookies")]
#endif
public string[] Cookies { get; set; }
/// <summary>
/// The response body
/// </summary>
[DataMember(Name = "body")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("body")]
#endif
public string Body { get; set; }
/// <summary>
/// Flag indicating whether the body should be treated as a base64-encoded string
/// </summary>
[DataMember(Name = "isBase64Encoded")]
#if NETCOREAPP_3_1
[System.Text.Json.Serialization.JsonPropertyName("isBase64Encoded")]
#endif
public bool IsBase64Encoded { get; set; }
}
}
| 94 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.