AWS Cloud9 is no longer available to new customers. Existing customers of
AWS Cloud9 can continue to use the service as normal.
Learn more
.NET tutorial for AWS Cloud9
This tutorial enables you to run some .NET code in an AWS Cloud9 development environment.
Following this tutorial and creating this sample might result in charges to your AWS account. These include possible
charges for services such as Amazon EC2 and Amazon S3. For more information, see Amazon EC2 Pricing
Topics
Prerequisites
Before you use this sample, make sure that your setup meets the following requirements:
-
You must have an existing AWS Cloud9 EC2 development environment. This sample assumes that you already have an EC2 environment that's connected to an Amazon EC2 instance that runs Amazon Linux or Ubuntu Server. If you have a different type of environment or operating system, you might need to adapt this sample's instructions to set up related tools. For more information, see Creating an environment in AWS Cloud9.
-
You have the AWS Cloud9 IDE for the existing environment already open. When you open an environment, AWS Cloud9 opens the IDE for that environment in your web browser. For more information, see Opening an environment in AWS Cloud9.
Step 1: Install required tools
In this step, you install the .NET SDK into your environment, which is required to run this sample.
-
Confirm whether the latest version of the .NET SDK is already installed in your environment. To do this, in a terminal session in the AWS Cloud9 IDE, run the .NET Core command line interface (CLI) with the
--versionoption.dotnet --versionIf the .NET Command Line Tools version is displayed, and the version is 2.0 or greater, skip ahead to Step 3: Create a .NET console application project. If the version is less than 2.0, or if an error such as
bash: dotnet: command not foundis displayed, continue on to install the .NET SDK. -
For Amazon Linux, in a terminal session in the AWS Cloud9 IDE, run the following commands to help ensure the latest security updates and bug fixes are installed, and to install a
libunwindpackage that the .NET SDK needs. (To start a new terminal session, on the menu bar, choose Window, New Terminal.)sudo yum -y update sudo yum -y install libunwindFor Ubuntu Server, in a terminal session in the AWS Cloud9 IDE, run the following command to help ensure the latest security updates and bug fixes are installed. (To start a new terminal session, on the menu bar, choose Window, New Terminal.)
sudo apt -y update -
Download the .NET SDK installer script into your environment by running the following command.
wget https://dot.net/v1/dotnet-install.sh -
Make the installer script executable by the current user by running the following command.
sudo chmod u=rx dotnet-install.sh -
Run the installer script, which downloads and installs the .NET SDK, by running the following command.
./dotnet-install.sh -c Current -
Add the .NET SDK to your
PATH. To do this, in the shell profile for the environment (for example, the.bashrcfile), add the$HOME/.dotnetsubdirectory to thePATHvariable for the environment, as follows.-
Open the
.bashrcfile for editing by using thevicommand.vi ~/.bashrc -
For Amazon Linux, using the down arrow or
jkey, move to the line that starts withexport PATH.For Ubuntu Server, move to the last line of the file by typing
G. -
Using the right arrow or
$key, move to the end of that line. -
Switch to insert mode by pressing the
ikey. (-- INSERT ---will appear at the end of the display.) -
For Amazon Linux, add the
$HOME/.dotnetsubdirectory to thePATHvariable by typing:$HOME/.dotnet. Be sure to include the colon character (:). The line should now look similar to the following.export PATH=$PATH:$HOME/.local/bin:$HOME/bin:$HOME/.dotnetFor Ubuntu Server, press the right arrow key and then press
Entertwice, followed by typing the following line by itself at the end of the file.export PATH=$HOME/.dotnet:$PATH -
Save the file. To do this, press the
Esckey (-- INSERT ---will disappear from the end of the display), type:wq(to write to and then quit the file), and then pressEnter.
-
-
Load the .NET SDK by sourcing the
.bashrcfile.. ~/.bashrc -
Confirm the .NET SDK is loaded by running .NET CLI with the
--helpoption.dotnet --helpIf successful, the .NET SDK version number is displayed, with additional usage information.
-
If you no longer want to keep the .NET SDK installer script in your environment, you can delete it as follows.
rm dotnet-install.sh
Step 2 (Optional): Install the .NET CLI extension for Lambda functions
Although not required for this tutorial, you can deploy AWS Lambda functions and
AWS Serverless Application Model applications using the .NET CLI if you also install the
Amazon.Lambda.Tools package.
-
To install the package, run the following command:
dotnet tool install -g Amazon.Lambda.Tools -
Now set the
PATHandDOTNET_ROOTenvironment variable to point to the installed Lambda tool. In the.bashrcfile, find theexport PATHsection and edit it so that it appears similar to the following (see Step 1 for details on editing this file):export PATH=$PATH:$HOME/.local/bin:$HOME/bin:$HOME/.dotnet:$HOME/.dotnet/tools export DOTNET_ROOT=$HOME/.dotnet
Step 3: Create a .NET console application project
In this step, you use .NET to create a project named hello. This project
contains all of the files that .NET needs to run a simple application from the terminal in
the IDE. The application's code is written in C#.
Create a .NET console application project. To do this, run the .NET CLI with the
new
command, specifying the console application project template type and the
programming language to use (in this sample, C#).
The -n option indicates that the project is outputted to a new directory,
hello. We then navigate to that directory.
dotnet new console -lang C# -n hellocd hello
The preceding command adds a subdirectory named obj with several
files, and some additional standalone files, to the hello directory.
You should note the following two key files:
-
The
hello/hello.csprojfile contains information about the console application project. -
The
hello/Program.csfile contains the application's code to run.
Step 4: Add code
In this step, you add some code to the application.
From the Environment window in the AWS Cloud9 IDE, open the
hello/Program.cs file.
In the editor, replace the file's current contents with the following code, and then
save the Program.cs file.
using System; namespace hello { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Please provide 2 numbers"); return; } Console.WriteLine("Hello, World!"); Console.WriteLine("The sum of 2 and 3 is 5."); int sum = Int32.Parse(args[0]) + Int32.Parse(args[1]); Console.WriteLine("The sum of {0} and {1} is {2}.", args[0], args[1], sum); } } }
Step 5: Build and run the code
In this step, you build the project and its dependencies into a set of binary files, including a runnable application file. Then you run the application.
-
In the IDE, create a builder for .NET as follows.
-
On the menu bar, choose Run, Build System, New Build System.
-
On the My Builder.build tab, replace the tab's contents with the following code.
{ "cmd" : ["dotnet", "build"], "info" : "Building..." } -
Choose File, Save As.
-
For Filename, type
.NET.build. -
For Folder, type
/.c9/builders. -
Choose Save.
-
-
With the contents of the
Program.csfile displayed in the editor, choose Run, Build System, .NET. Then choose Run, Build.This builder adds a subdirectory named
binand adds a subdirectory namedDebugto thehello/objsubdirectory. Note the following three key files.-
The
hello/bin/Debug/netcoreapp3.1/hello.dllfile is the runnable application file. -
The
hello/bin/Debug/netcoreapp3.1/hello.deps.jsonfile lists the application's dependencies. -
The
hello/bin/Debug/netcoreapp3.1/hello.runtimeconfig.jsonfile specifies the shared runtime and its version for the application.
Note
The folder name,
netcoreapp3.1, reflects the version of the .NET SDK used in this example. You may see a different number in the folder name depending on the version you've installed. -
-
Create a runner for .NET as follows.
-
On the menu bar, choose Run, Run With, New Runner.
-
On the My Runner.run tab, replace the tab's contents with the following code.
{ "cmd" : ["dotnet", "run", "$args"], "working_dir": "$file_path", "info" : "Running..." } -
Choose File, Save As.
-
For Filename, type
.NET.run. -
For Folder, type
/.c9/runners. -
Choose Save.
-
-
Run the application with two integers to add (for example,
5and9) as follows.-
With the contents of the
Program.csfile displayed in the editor, choose Run, Run Configurations, New Run Configuration. -
In the [New] - Idle tab, choose Runner: Auto, and then choose .NET.
-
In the Command box, type
hello 5 9. -
Choose Run.
By default, this runner instructs .NET to run the
hello.dllfile in thehello/bin/Debug/netcoreapp3.1directory.Compare your output to the following.
Hello, World! The sum of 2 and 3 is 5. The sum of 5 and 9 is 14.
-
Step 6: Create and set up a .NET console application project that uses the AWS SDK for .NET
You can enhance this sample to use the AWS SDK for .NET to create an Amazon S3 bucket, list your available buckets, and then delete the bucket you just created.
In this new project, you add a reference to the AWS SDK for .NET. The AWS SDK for .NET provides a convenient way to interact with AWS services such as Amazon S3, from your .NET code. You then set up AWS credentials management in your environment. The AWS SDK for .NET needs these credentials to interact with AWS services.
To create the project
-
Create a .NET console application project. To do this, run the .NET CLI with the
newcommand, specifying the console application project template type and the programming language to use.The
-noption indicates that the project is outputted to a new directory,s3. We then navigate to that directory.dotnet new console -lang C# -n s3cd s3 -
Add a project reference to the Amazon S3 package in the AWS SDK for .NET. To do this, run the .NET CLI with the
add packagecommand, specifying the name of the Amazon S3 package in NuGet. (NuGet defines how packages for .NET are created, hosted, and consumed, and provides the tools for each of those roles.)dotnet add package AWSSDK.S3When you add a project reference to the Amazon S3 package, NuGet also adds a project reference to the rest of the AWS SDK for .NET.
Note
For the names and versions of other AWS related packages in NuGet, see NuGet packages tagged with aws-sdk
on the NuGet website.
To set up AWS credentials management
Each time you use the AWS SDK for .NET to call an AWS service, you must provide a set of AWS credentials with the call. These credentials determine whether the AWS SDK for .NET has the appropriate permissions to make that call. If the credentials don't cover the appropriate permissions, the call will fail.
To store your credentials within the environment, follow the instructions in Calling AWS services from an environment in AWS Cloud9, and then return to this topic.
For additional information, see Configuring AWS Credentials in the AWS SDK for .NET Developer Guide.
Step 7: Add AWS SDK code
In this step, you add code to interact with Amazon S3 to create a bucket, delete the bucket you just created, and then list your available buckets.
From the Environment window in the AWS Cloud9 IDE, open the
s3/Program.cs file. In the editor, replace the file's current
contents with the following code, and then save the Program.cs
file.
using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System; using System.Threading.Tasks; namespace s3 { class Program { async static Task Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: <the bucket name> <the AWS Region to use>"); Console.WriteLine("Example: my-test-bucket us-east-2"); return; } if (args[1] != "us-east-2") { Console.WriteLine("Cannot continue. The only supported AWS Region ID is " + "'us-east-2'."); return; } var bucketRegion = RegionEndpoint.USEast2; // Note: You could add more valid AWS Regions above as needed. using (var s3Client = new AmazonS3Client(bucketRegion)) { var bucketName = args[0]; // Create the bucket. try { if (await AmazonS3Util.DoesS3BucketExistV2Async(s3Client, bucketName)) { Console.WriteLine("Cannot continue. Cannot create bucket. \n" + "A bucket named '{0}' already exists.", bucketName); return; } else { Console.WriteLine("\nCreating the bucket named '{0}'...", bucketName); await s3Client.PutBucketAsync(bucketName); } } catch (AmazonS3Exception e) { Console.WriteLine("Cannot continue. {0}", e.Message); } catch (Exception e) { Console.WriteLine("Cannot continue. {0}", e.Message); } // Confirm that the bucket was created. if (await AmazonS3Util.DoesS3BucketExistV2Async(s3Client, bucketName)) { Console.WriteLine("Created the bucket named '{0}'.", bucketName); } else { Console.WriteLine("Did not create the bucket named '{0}'.", bucketName); } // Delete the bucket. Console.WriteLine("\nDeleting the bucket named '{0}'...", bucketName); await s3Client.DeleteBucketAsync(bucketName); // Confirm that the bucket was deleted. if (await AmazonS3Util.DoesS3BucketExistV2Async(s3Client, bucketName)) { Console.WriteLine("Did not delete the bucket named '{0}'.", bucketName); } else { Console.WriteLine("Deleted the bucket named '{0}'.", bucketName); }; // List current buckets. Console.WriteLine("\nMy buckets now are:"); var response = await s3Client.ListBucketsAsync(); foreach (var bucket in response.Buckets) { Console.WriteLine(bucket.BucketName); } } } } }
Step 8: Build and run the AWS SDK code
In this step, you build the project and its dependencies into a set of binary files, including a runnable application file. Then you run the application.
-
Build the project. To do this, with the contents of the
s3/Program.csfile displayed in the editor, on the menu bar, choose Run, Build. -
Run the application with the name of the Amazon S3 bucket to create and the ID of the AWS Region to create the bucket in (for example,
my-test-bucketandus-east-2) as follows.-
With the contents of the
s3/Program.csfile still displayed in the editor, choose Run, Run Configurations, New Run Configuration. -
In the [New] - Idle tab, choose Runner: Auto, and then choose .NET.
-
In the Command box, type the name of the application, the name of the Amazon S3 bucket to create, and the ID of the AWS Region to create the bucket in (for example,
s3 my-test-bucket us-east-2). -
Choose Run.
By default, this runner instructs .NET to run the
s3.dllfile in thes3/bin/Debug/netcoreapp3.1directory.Compare your results to the following output.
Creating a new bucket named 'my-test-bucket'... Created the bucket named 'my-test-bucket'. Deleting the bucket named 'my-test-bucket'... Deleted the bucket named 'my-test-bucket'. My buckets now are:
-
Step 9: Clean up
To prevent ongoing charges to your AWS account after you're done using this sample, you should delete the environment. For instructions, see Deleting an environment in AWS Cloud9.