Connecting to AWS DynamoDb with .NET CORE


Recently i was trying out this course on Udemy on designing microservices architecture based solutions with .NET core and AWS. It was a good course but like most Udemy courses ( ahem ) it had some holes here and there. One of the things i found most troubling is that it did not explain how to connect to AWS' DynamoDb which they was used as the database for the course project, using .NET core. When i checked the questions section of Udemy it was evident to me that i was not the only guy having this problem. Also the information on the all mighty internet was a bit scattered on this problem so i had to read a lot. There WAS instructions on the AWS documentation but it was...let's say i was too stupid to understand it! 

So therefor , here are the steps i followed to get my solution working , if you are stupid like me i hope you will find this useful :)

Step 1

Create an AWS account , if you don't have one already. Im a poor developer so i only have a humble free tier account. You can get some Dynamo with the free tier so make one if you are new to AWS.

Step 2

Create a small DynamoDb database. Since my article is about the connection part , i will not explain how to do that. But you can follow this great article and get it done easily. 



Step 2

Alright cowboy , now you have a database. Now let's create a user to connect to it. This is important. Because it doesn't matter if you have a horse but don't have a jockey.

First go to your AWS management console home , search for IAM and go there. IAM means Identity and Access Management


Then click on Users



Now here you will a bunch of users. If you do not see any user already, don't worry we can create a new user. Or , you can create a new user anyways for the purpose of connecting to your database. Which might be a better idea so it limits the powers of that user. So we will create a new user ( but you can go with your own existing user if you want , makes no difference in application ).

Then fill the details as shown below and click on Next:Permissions

Important: Make sure to tick the Programmatic access box as shown below. If you do not select this then you will not be able to connect to your AWS services via the SDKs. 

I put the other tick on too because i want my user to check stuff from the console , but it is not mandatory for our exercise.

OK now click on the far right box. This is another important step as we have to give our user permission to access our DynamoDb. You can give this permission later as well but it's easier if you do it now itself so WTF right ? let's do it !

Search for 'dynamo' and give this sucker full access to your precious DynamoDb


Other step which is 'Tags' is not relevant to us for this excercise , so you can skip that and proceed to Create User. BAM ! Life is created and BAM hold your horses now , we have another important step to do before you do anything silly.

Step 3

Before you go any further you need to download this key by clicking the button shown below. You can create new credentials and download later as shown below , but it's easier to download it now.

Now please note that you can connect to your DynamoDb client even without downloading this file , but im going to show you the easiest way to connect so we wil go with this method.

Step 4

Alright now you can use these credentials to connect to your DynamoDb. But we have to a few more things. 

Now, go to your user profile root folder. You can go there easily by hitting Windows + R and typing %USERPROFILE%

Then create a folder there called .aws as shown below.


TIP: Now another tip if you don't know already , windows does not let you create files or folders starting with a period in the explorer , so you have to name your folder like this .aws. with a dot in the end , then it will be accepted. Same goes when you are creating things like .htaccess files.

Ok now :
Create a file there called "credentials", without any extension and put your access key and secrete access key there as shown below. You can get these two keys from the CSV file you downloaded in Step 3.


File Format

[default]
aws_access_key_id=XXXXXXXXXXXXXXXXXXXXXXXXXX
aws_secret_access_key=XXXXXXXXXXXXXXXXXXXXXXXX


Step 5

Ok now that's about all the configurations work we have to do, now let's get to coding ! 

Hope you are familiar with .NET core so i am not going to explain how to create a .NET core application today.I created a .NET Core Web Application to test. Follow the below steps after creating your .NET core project.

  • First install the following 2 Nuget packages
AWSSDK.Extensions.NETCore.Setup
AWSSDK.DynamoDBv2


  • Place the following in your appsetting.json
  "AWS": {
    "Profile": "default",
    "Region": "your-region"
  }

default - this is the name that you put within the square brackets as the first line in your credentials files in Step 4
region - make sure to put your relevant region to which your aws belongs

Here's how my file looks.


  • Now place the following in your Startup.cs -> ConfigureServices method

   // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
            services.AddAWSService<IAmazonDynamoDB>();
            services.AddControllers();
        }


  • Finally , create a controller and put the following code to check your connection. Since this is an example i coded like a savage and put everything in one controller file , but you can comeup with a more civilized solution when doing this for real.
"Adverts" is the name of my table , please replace with your table name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.DynamoDBv2;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Playground1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DynamoController : Controller
    {
        private readonly IConfiguration _configuration;

        public DynamoController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [Route("get-status")]
        public async Task<string> GetStatus()
        {
            var options = _configuration.GetAWSOptions();
            string status;
            using (var client = options.CreateServiceClient<IAmazonDynamoDB>())
            {
                var tableData = await client.DescribeTableAsync("Adverts");
                status = tableData.Table.TableStatus;
            }

            return status;
        }
    }
}

Step 6

aaand thats it ! Now call your brand new method as shown below and see that it returns the table status fetched straight from the DynamoDb service in AWS itself.



And that's it guys ! There you have it , your shiny DynamoDb now talking with your .NET core app without a problem. 

Thanks for reading and cheers !

Comments

Popular posts from this blog

Wasted about an hour of my life on something so trivial

With Values

Angular for Dinosaurs : How i got started after being out of the game