Giter Site home page Giter Site logo

dynamodb-net-core-sample's Introduction

Getting Started With DynamoDB with C# (.NET Core)

This is a very simple .NET Core console app with DynamoDB. It verifies or creates a DynamoDB table, waits for that table to become active, then adds one document to the table and retrieves it.

The item stored in the database is modeled on the audio state item created in the Alexa Audio Player sample.

Nuget Package

AWSSDK Amazon DynamoDB

Search or type Install-Package AWSSDK.DynamoDBv2 into your Package Manager Console

Add the following namespaces

using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;

Set Your AWS Credentials

BasicAWSCredentials(accessKey, secretKey);
var client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);

Verify a Table

var tableResponse = await client.ListTablesAsync();
if (!tableResponse.TableNames.Contains(tableName))
{
    // Create our table if it doesn't exist
}

Create a New Table

await client.CreateTableAsync(new CreateTableRequest
{
    TableName = tableName,
    ProvisionedThroughput = new ProvisionedThroughput
    {
        ReadCapacityUnits = 3,
        WriteCapacityUnits = 1
    },
    KeySchema = new List<KeySchemaElement>
    {
        new KeySchemaElement
        {
            AttributeName = hashKey,
            KeyType = KeyType.HASH
        }
    },
    AttributeDefinitions = new List<AttributeDefinition>
    {
        new AttributeDefinition {
            AttributeName = hashKey,
            AttributeType =ScalarAttributeType.S
        }
    }
});

Wait for New Table to Create / Become Active

bool isTableAvailable = false;
while (!isTableAvailable) {
    Thread.Sleep(5000);
    var tableStatus = await client.DescribeTableAsync(tableName);
    isTableAvailable = tableStatus.Table.TableStatus == "ACTIVE";
}

Set Your Context

var context = new DynamoDBContext(client);

Create an Object and Save It

// Create our audio state object
AlexaAudioState currentState = new AlexaAudioState
{
    UserId = "someAwesomeUser",
    State = new StateMap()
    {
        EnqueuedToken = "awesomeAudioPart2",
        Index = 0,
        Loop = true,
        OffsetInMS = 123456,
        PlaybackFinished = false,
        PlaybackIndexChanged = false,
        playOrder = new List<int> { 0, 1 },
        Shuffle = false,
        State = "PLAY_MODE",
        Token = "awesomeAudioPart1"
    }
};

// Save that object into our DynamoDB
await context.SaveAsync<AlexaAudioState>(currentState);

Retrieve a Document

List<ScanCondition> conditions = new List<ScanCondition>();
conditions.Add(new ScanCondition("UserId", ScanOperator.Equal, currentState.UserId));
var allDocs = await context.ScanAsync<AlexaAudioState>(conditions).GetRemainingAsync();
var savedState = allDocs.FirstOrDefault();

Delete a Table

context.Dispose();
await client.DeleteTableAsync(new DeleteTableRequest() { TableName = tableName });

dynamodb-net-core-sample's People

Contributors

matthiasxc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

dynamodb-net-core-sample's Issues

Question regarding object composition

Is there a reason that you put State in to object StateMap rather than just putting all the properties in to AlexAudioState? Is this required by DynamoDB or is this your design choice?

[DynamoDBTable("AlexaAudioStates")]
    public class AlexaAudioState
    {
        [DynamoDBHashKey]
        public string UserId { get; set; }
        public StateMap State { get; set; }

    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.