Skip to content

Commit

Permalink
Use MSBuild to find target framework
Browse files Browse the repository at this point in the history
  • Loading branch information
gcbeattyAWS committed Nov 18, 2024
1 parent 21a1bec commit f3fe7a3
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 4 deletions.
7 changes: 7 additions & 0 deletions aws-extensions-for-dotnet-cli.sln
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestNativeAotNet8WebApp", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestIntegerFunction", "testapps\TestIntegerFunction\TestIntegerFunction.csproj", "{D7F1DFA4-066B-469C-B04C-DF032CF152C1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestFunctionBuildProps", "testapps\TestFunctionBuildProps\TestFunctionBuildProps\TestFunctionBuildProps.csproj", "{AFA71B8E-F0AA-4704-8C4E-C11130F82B13}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -169,6 +171,10 @@ Global
{D7F1DFA4-066B-469C-B04C-DF032CF152C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7F1DFA4-066B-469C-B04C-DF032CF152C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7F1DFA4-066B-469C-B04C-DF032CF152C1}.Release|Any CPU.Build.0 = Release|Any CPU
{AFA71B8E-F0AA-4704-8C4E-C11130F82B13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AFA71B8E-F0AA-4704-8C4E-C11130F82B13}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFA71B8E-F0AA-4704-8C4E-C11130F82B13}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFA71B8E-F0AA-4704-8C4E-C11130F82B13}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -200,6 +206,7 @@ Global
{AD31D053-97C5-4262-B187-EC42BFD51A9F} = {BB3CF729-8213-4DDD-85AE-A5E7754F3944}
{69FFA03C-D29F-40E0-9E7F-572D5E10AF77} = {BB3CF729-8213-4DDD-85AE-A5E7754F3944}
{D7F1DFA4-066B-469C-B04C-DF032CF152C1} = {BB3CF729-8213-4DDD-85AE-A5E7754F3944}
{AFA71B8E-F0AA-4704-8C4E-C11130F82B13} = {BB3CF729-8213-4DDD-85AE-A5E7754F3944}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DBFC70D6-49A2-40A1-AB08-5D9504AB7112}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
<PackageReference Include="AWSSDK.SecurityToken" Version="3.7.300.81" />
<PackageReference Include="AWSSDK.SSO" Version="3.7.300.80" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="3.7.301.75" />
<None Include="Assets\**\*" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<PropertyGroup>
<NoWarn>1701;1702;1705;1591</NoWarn>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project>
<Target Name="_AmazonCommonToolsExtractTargetFrameworks">
<ItemGroup>
<_TargetFrameworks Include="$(TargetFramework)" Condition="'$(TargetFramework)' != ''" />
<_TargetFrameworks Include="$(TargetFrameworks)" Condition="'$(TargetFrameworks)' != ''" />
</ItemGroup>
<WriteLinesToFile File="$(_AmazonCommonToolsTargetFrameworksFile)" Lines="@(_TargetFrameworks)" Overwrite="true" />
</Target>
</Project>

77 changes: 74 additions & 3 deletions src/Amazon.Common.DotNetCli.Tools/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,85 @@ public static string DeterminePublishLocation(string workingDirectory, string pr

public static string LookupTargetFrameworkFromProjectFile(string projectLocation)
{

var projectFile = FindProjectFileInDirectory(projectLocation);
if (string.IsNullOrEmpty(projectFile))
{
throw new FileNotFoundException("Could not find a project file in the specified directory.");
}

var xdoc = XDocument.Load(projectFile);
var outputFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var targetsFile = FindTargetsFile();

if (!File.Exists(targetsFile))
{
throw new FileNotFoundException($"Could not find the custom .targets file at {targetsFile}");
}

var arguments = new[]
{
"msbuild",
projectFile,
"/nologo",
"/t:_AmazonCommonToolsExtractTargetFrameworks",
$"/p:_AmazonCommonToolsTargetFrameworksFile={outputFile}",
"/p:Configuration=Debug",
$"\"/p:CustomAfterMicrosoftCommonTargets={targetsFile}\"",
$"\"/p:CustomAfterMicrosoftCommonCrossTargetingTargets={targetsFile}\""
};

var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "dotnet",
Arguments = string.Join(" ", arguments),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};

process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

var element = xdoc.XPathSelectElement("//PropertyGroup/TargetFramework");
return element?.Value;
if (process.ExitCode != 0)
{
throw new Exception($"MSBuild process exited with code {process.ExitCode}. See log for details.");
}

if (File.Exists(outputFile))
{
var targetFrameworks = File.ReadAllLines(outputFile);
File.Delete(outputFile); // Clean up the temporary file

if (targetFrameworks.Length > 0)
{
return targetFrameworks[0]; // Return the first framework if there are multiple
}
}

return null;
}


private static string FindTargetsFile()
{
var assemblyDir = Path.GetDirectoryName(typeof(DotNetCLIWrapper).Assembly.Location);
var searchPaths = new[]
{
Path.Combine(AppContext.BaseDirectory, "Assets"),
Path.Combine(assemblyDir, "Assets"),
AppContext.BaseDirectory,
assemblyDir,
};

return searchPaths.Select(p => Path.Combine(p, "AmazonCommonDotNetCliTools.targets")).FirstOrDefault(File.Exists);
}


/// <summary>
/// Retrieve the `OutputType` property of a given project
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions test/Amazon.Common.DotNetCli.Tools.Test/UtilitiesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class UtilitiesTests
[InlineData("../../../../../testapps/TestFunction", "net6.0")]
[InlineData("../../../../../testapps/ServerlessWithYamlFunction", "net6.0")]
[InlineData("../../../../../testapps/TestBeanstalkWebApp", "netcoreapp3.1")]
[InlineData("../../../../../testapps/TestFunctionBuildProps/TestFunctionBuildProps", "net6.0")]
public void CheckFramework(string projectPath, string expectedFramework)
{
var assembly = this.GetType().GetTypeInfo().Assembly;
Expand Down
5 changes: 5 additions & 0 deletions testapps/TestFunctionBuildProps/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
</Project>
14 changes: 14 additions & 0 deletions testapps/TestFunctionBuildProps/TestFunctionBuildProps/Function.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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 TestFunctionBuildProps;

public class Function
{
public string FunctionHandler(string input, ILambdaContext context)
{
return input.ToUpper();
}
}
49 changes: 49 additions & 0 deletions testapps/TestFunctionBuildProps/TestFunctionBuildProps/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# AWS Lambda Empty Function Project

This starter project consists of:
* Function.cs - class file containing a class with a single function handler method
* aws-lambda-tools-defaults.json - default argument settings for use with Visual Studio and command line deployment tools for AWS

You may also have a test project depending on the options selected.

The generated function handler is a simple method accepting a string argument that returns the uppercase equivalent of the input string. Replace the body of this method, and parameters, to suit your needs.

## Here are some steps to follow from Visual Studio:

To deploy your function to AWS Lambda, right click the project in Solution Explorer and select *Publish to AWS Lambda*.

To view your deployed function open its Function View window by double-clicking the function name shown beneath the AWS Lambda node in the AWS Explorer tree.

To perform testing against your deployed function use the Test Invoke tab in the opened Function View window.

To configure event sources for your deployed function, for example to have your function invoked when an object is created in an Amazon S3 bucket, use the Event Sources tab in the opened Function View window.

To update the runtime configuration of your deployed function use the Configuration tab in the opened Function View window.

To view execution logs of invocations of your function use the Logs tab in the opened Function View window.

## Here are some steps to follow to get started from the command line:

Once you have edited your template and code you can deploy your application using the [Amazon.Lambda.Tools Global Tool](https://github.com/aws/aws-extensions-for-dotnet-cli#aws-lambda-amazonlambdatools) from the command line.

Install Amazon.Lambda.Tools Global Tools if not already installed.
```
dotnet tool install -g Amazon.Lambda.Tools
```

If already installed check if new version is available.
```
dotnet tool update -g Amazon.Lambda.Tools
```

Execute unit tests
```
cd "TestFunctionBuildProps/test/TestFunctionBuildProps.Tests"
dotnet test
```

Deploy function to AWS Lambda
```
cd "TestFunctionBuildProps/src/TestFunctionBuildProps"
dotnet lambda deploy-function
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.4.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.4" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"Information": [
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
"dotnet lambda help",
"All the command line options for the Lambda command can be specified in this file."
],
"profile": "default",
"region": "us-west-2",
"configuration": "Release",
"function-architecture": "x86_64",
"function-runtime": "dotnet8",
"function-memory-size": 512,
"function-timeout": 30,
"function-handler": "TestFunctionBuildProps::TestFunctionBuildProps.Function::FunctionHandler"
}

0 comments on commit f3fe7a3

Please sign in to comment.