Implementation for accessing AmazonDynamoDBv2. Amazon DynamoDB Overview

This is the Amazon DynamoDB API Reference. This guide provides descriptions and samples of the Amazon DynamoDB API.

Inheritance: AmazonWebServiceClient, IAmazonDynamoDB
        protected void submitButton_Click(object sender, EventArgs e)
        {
            if (inId.Value != "" && startTime.Text != "" && endTime.Text != "" && name.Text != "" && speakerName.Text != "")
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Session");

                var book = new Document();
                book["eventId"] = inId.Value;
                DateTime sTime = Convert.ToDateTime(startTime.Text);
                //string endNew = test.ToString("dd/MM/yyyy HH:mm tt");
                book["startTime"] = sTime.ToString("dd/MM/yyyy HH:mm tt");
                DateTime eTime = Convert.ToDateTime(endTime.Text);
                book["endTime"] = eTime.ToString("dd/MM/yyyy HH:mm tt");
                book["name"] = name.Text;
                book["speakerName"] = speakerName.Text;

                table.PutItem(book);
                Response.Redirect("Session.aspx");
                string script = "alert(\"Successfully created the Session.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
            else
            {
                string script = "alert(\"Please fill all the data.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
        }
Beispiel #2
1
        public void InstantiateIn(System.Web.UI.Control container)
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            // string tableName = "Attendee";
            var request = new ScanRequest
            {
                TableName = "QuizQuestion",

            };
            var response = client.Scan(request);
            List<QuestionData> questionDataList = new List<QuestionData>();
            foreach (Dictionary<string, AttributeValue> item in response.ScanResult.Items)
            {
                // Process the result.

                QuestionData question = new QuestionData();
                if (item.ContainsKey("options"))
                {
                        foreach (var itemNew in item["options"].M)
                        {
                            Label link = new Label();
                            link.ID = "linkmodel";
                            container.Controls.Add(link);
                            link.Text = itemNew.Value.S;
                            //Label value = questionData.FindControl("options") as Label;
                            ////testM = itemNew.Key.ToString();
                            //value.Text = itemNew.Value.S;
                        }
                }

            }
        }
        public virtual void CreateAccountItem(AmazonDynamoDBClient ddbClient, string tableName, Account account)
        {
            // Create the request
            var putItemRequest = new PutItemRequest
            {
                TableName = tableName,
                Item = new Dictionary<string, AttributeValue>
                {
                    {"Company", new AttributeValue {S = account.Company}},
                    {"Email", new AttributeValue {S = account.Email}}
                }
            };

            // Only add attributes if the coresponding property in the account object is not empty.
            if (!String.IsNullOrEmpty(account.First))
            {
                putItemRequest.Item.Add("First", new AttributeValue {S = account.First});
            }
            if (!String.IsNullOrEmpty(account.Last))
            {
                putItemRequest.Item.Add("Last", new AttributeValue {S = account.Last});
            }
            if (!String.IsNullOrEmpty(account.Age))
            {
                putItemRequest.Item.Add("Age", new AttributeValue {N = account.Age});
            }

            // Submit the request
            ddbClient.PutItem(putItemRequest);
        }
        public virtual void BuildTable(AmazonDynamoDBClient ddbClient, string tableName)
        {
            Console.WriteLine("Creating table.");
            var request = new CreateTableRequest
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>
                {
                    new AttributeDefinition {AttributeName = "Company", AttributeType = "S"},
                    new AttributeDefinition {AttributeName = "Email", AttributeType = "S"}
                },
                KeySchema = new List<KeySchemaElement>
                {
                    new KeySchemaElement {AttributeName = "Company", KeyType = "HASH"},
                    new KeySchemaElement {AttributeName = "Email", KeyType = "RANGE"}
                },
                ProvisionedThroughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits = 10,
                    WriteCapacityUnits = 5
                }
            };

            ddbClient.CreateTable(request);
            // Pause until the table is active
            WaitForStatus(ddbClient, tableName, "ACTIVE");
            Console.WriteLine("Table created and active.");
        }
        public static void RunDocumentModelSample(AmazonDynamoDBClient client)
        {
            Console.WriteLine("Loading hints table");
            Table table = Table.LoadTable(client, "packLevels");

            Console.WriteLine("Creating and saving first item");

            string wordbrain = @"D:\wordbrain.json";
            List<Pack> packs = JsonConvert.DeserializeObject<List<Pack>>(File.ReadAllText(wordbrain)) as List<Pack>;
            int packNum = 0;
            foreach (Pack p in packs)
            {
                packNum++;
                int level = 0;
                foreach (Answers item in p.levels)
                {
                    Document mydoc = new Document();
                    mydoc["puzzleID"] = p.pack + "_" + level;
                    DynamoDBList list = new DynamoDBList();
                    foreach (string str in item.answers)
                        list.Add(str);
                    mydoc.Add("answers", list);
                    table.PutItem(mydoc);
                    ++level;
                }

            }
        }
        protected void submitButton_Click(object sender, EventArgs e)
        {
            if (description.Text != "" && end.Text != "" && inId.Value != "" && Name.Text != "" && oName.Text != "" && start.Text != "" && venue.Text != "")
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Event");

                var book = new Document();
                book["description1"] = description.Text;
                //DateTime date2 = Convert.ToDateTime(end.Text);
                //string endDate = date2.ToString("dd/MM/yyyy");
                book["endDate"] = end.Text;
                book["eventId"] = inId.Value;
                book["eventName"] = Name.Text;
                book["organiserName"] = oName.Text;
                //DateTime date1 = Convert.ToDateTime(start.Text);
                //string startDate = date1.ToString("dd/MM/yyyy");
                book["startDate"] = start.Text;
                book["venue"] = venue.Text;

                table.PutItem(book);
                Response.Redirect("Events.aspx");
                string script = "alert(\"Successfully created the Event.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
            else
            {
                string script = "alert(\"Please fill all the data correctly.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
        }
        protected void submitButton_Click(object sender, EventArgs e)
        {
            if (inId.Value != "" && inEid.Value != "" && PublishTime.Text != "" && txtText.Text != "")
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Announcement");

                var book = new Document();
                book["announcementId"] = inId.Value;
                book["eventId"] = inEid.Value;
                DateTime pTime = Convert.ToDateTime(PublishTime.Text);
                book["publishTime"] = pTime.ToString("dd/MM/yyyy HH:mm tt");
                book["text"] = txtText.Text;

                table.PutItem(book);
                string script = "alert(\"Successfully created the Announcement.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
                Response.Redirect("Announcement.aspx");

            }
            else
            {
                string script = "alert(\"Please fill all the data.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
        }
        private void WaitTillTableCreated(AmazonDynamoDBClient client, string tableName) {
            string status;

            Console.Write("Creating the table: ");
            do {
                System.Threading.Thread.Sleep(50);
                try {
                    var res = client.DescribeTable(new DescribeTableRequest
                    {
                        TableName = tableName
                    });
                    if (res.Table.TableStatus == "ACTIVE") {
                        break;
                    }
                    if (res.Table.TableStatus == "CREATING") {
                        Console.Write(".");
                    }
                    else {
                        Console.Write("[{0}]", res.Table.TableStatus);
                    }

                    status = res.Table.TableStatus;
                }
                catch (ResourceNotFoundException) {
                    Console.Write("?");  // Okay to appear, since the consistency is eventual.
                    status = "EXCEPTION";
                }
            } while (status != "ACTIVE");
            Console.WriteLine(" Done.");
        }
 /// <summary>
 ///     Upload the specified image to S3 and add a reference to the image to DynamoDB. The DynamoDB item representing the
 ///     image
 ///     should contain two attributes:
 ///     Key - The key to the object in S3
 ///     Bucket - The bucket that the object is located in
 ///     Do not set any permissions for the object in S3; keep the restrictive defaults.
 ///     This method will be called if the lab controller code determines that the images used in the lab aren't
 ///     in place or referenced properly in DynamoDB. It will be executed at least once.
 /// </summary>
 /// <param name="dynamoDbClient">The DynamoDB client object.</param>
 /// <param name="tableName">The name of the table to put the items in.</param>
 /// <param name="s3Client">The S3 client object.</param>
 /// <param name="bucketName">The name of the bucket to use for the objects in S3.</param>
 /// <param name="imageKey">The key representing the object in S3.</param>
 /// <param name="filePath">The full path of the image file to upload.</param>
 /// <remarks>
 ///     The purpose of this task is to gain experience with the process of preparing AWS resources for use by your
 ///     application.
 /// </remarks>
 public override void AddImage(AmazonDynamoDBClient dynamoDbClient, string tableName, AmazonS3Client s3Client,
     string bucketName,
     string imageKey, string filePath)
 {
     //TODO: Replace this call to the base class with your own method implementation.
     base.AddImage(dynamoDbClient, tableName, s3Client, bucketName, imageKey, filePath);
 }
Beispiel #10
0
        static void Main(string[] args)
        {
            var awsKey = "my-aws-key";
            var awsSecret = "my-aws-secret";
            var config = new AmazonDynamoDBConfig { ServiceURL = "http://localhost:8000" };

            var client = new AmazonDynamoDBClient(awsKey, awsSecret, config);
            var ctx = new DynamoDBContext(client);

            var userId = "theburningmonk-1";

            // query examples
            QueryByHashKey(userId, client, ctx);
            QueryWithRangeKey(userId, client, ctx);
            QueryWithOrderAndLimit(userId, client, ctx);
            QueryWithNoConsistentRead(userId, client, ctx);
            ThrottlingWithQueryPageSize(userId, client, ctx);
            SelectSpecificAttributes(userId, client, ctx);
            QueryWithNoReturnedConsumedCapacity(userId, client);
            QueryWithLocalSecondaryIndexAllAttributes(userId, client, ctx);
            QueryWithLocalSecondaryIndexProjectedAttributes(userId, client, ctx);
            QueryWithGlobalSecondaryIndexProjectedAttributes(client, ctx);

            // scan examples
            BasicScan(client, ctx);
            ScanWithLimit(client, ctx);
            ThrottlingWithScanPageSize(client, ctx);
            ScanWithScanPageSizeAndSegments(client, ctx);
            ScanWithNoReturnedConsumedCapacity(client);
            SelectSpecificAttributes(client, ctx);

            Console.WriteLine("all done...");

            Console.ReadKey();
        }
Beispiel #11
0
 public AmazonDynamoDBClient ConnectAmazonDynamoDB(string ConnectionString)
 {
     var config = new AmazonDynamoDBConfig();
     config.ServiceURL = ConnectionString;
     var client = new AmazonDynamoDBClient(config);
     return client;
 }
        public DynamoDBConfigurationFactory()
        {
            string accessKey = ConfigurationManager.AppSettings["DynamoDB.AccessKey"];
            string secretKey = ConfigurationManager.AppSettings["DynamoDB.SecretKey"];
            string tableName = ConfigurationManager.AppSettings["DynamoDB.TableName"];

            AmazonDynamoDBClient dynmamoClient = new AmazonDynamoDBClient(accessKey, secretKey, RegionEndpoint.EUWest1);
            _configTable = Table.LoadTable(dynmamoClient, tableName);
        }
Beispiel #13
0
        public static AmazonDynamoDBClient CreateDynamoDBClient()
        {
            var dynamoClient = new AmazonDynamoDBClient("keyId", "key", new AmazonDynamoDBConfig
            {
                ServiceURL = ConfigUtils.GetAppSetting("DynamoDbUrl", "http://localhost:8000"),
            });

            return dynamoClient;
        }
Beispiel #14
0
        /// <summary>
        /// Creates all samples defined in SampleTables map
        /// </summary>
        /// <param name="client"></param>
        public static void CreateSampleTables(AmazonDynamoDBClient client)
        {
            Console.WriteLine("Getting list of tables");
            List<string> currentTables = client.ListTables().TableNames;
            Console.WriteLine("Number of tables: " + currentTables.Count);

            bool tablesAdded = false;
            if (!currentTables.Contains("Businesses"))
            {
                Console.WriteLine("Table Businesses does not exist, creating");
                client.CreateTable(new CreateTableRequest
                {
                    TableName = "Businesses",
                    ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 3, WriteCapacityUnits = 1 },
                    KeySchema = new List<KeySchemaElement>
                    {
                        new KeySchemaElement
                        {
                            AttributeName = "Name",
                            KeyType = KeyType.HASH
                        },
                        new KeySchemaElement
                        {
                            AttributeName = "Id",
                            KeyType = KeyType.RANGE
                        }
                    },
                    AttributeDefinitions = new List<AttributeDefinition>
                    {
                        new AttributeDefinition { AttributeName = "Name", AttributeType = ScalarAttributeType.S },
                        new AttributeDefinition { AttributeName = "Id", AttributeType = ScalarAttributeType.N }
                    }
                });
                tablesAdded = true;
            }

            if (tablesAdded)
            {
                bool allActive;
                do
                {
                    allActive = true;
                    Console.WriteLine("While tables are still being created, sleeping for 5 seconds...");
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    foreach (var tableName in SAMPLE_TABLE_NAMES)
                    {
                        string tableStatus = GetTableStatus(client, tableName);
                        bool isTableActive = string.Equals(tableStatus, "ACTIVE", StringComparison.OrdinalIgnoreCase);
                        if (!isTableActive)
                            allActive = false;
                    }
                } while (!allActive);
            }

            Console.WriteLine("All sample tables created");
        }
Beispiel #15
0
    protected override void Load(ContainerBuilder builder)
    {
        var config = new AmazonDynamoDBConfig();
        config.RegionEndpoint = Amazon.RegionEndpoint.APSoutheast2;
        var client = new AmazonDynamoDBClient(config);

        builder.Register(c => client).As<IAmazonDynamoDB>();

        builder.RegisterType<SessionsRepository>().As<ISessionsRepository>();
    }
 public static IAmazonDynamoDB CreateAmazonDynamoDb()
 {
     var dynamoClient = new AmazonDynamoDBClient(
         ConfigUtils.GetNullableAppSetting("DynamoDbAccessKey") ?? AwsAccessKey,
         ConfigUtils.GetNullableAppSetting("DynamoDbSecretKey") ?? AwsSecretKey,
         new AmazonDynamoDBConfig {
             ServiceURL = ConfigUtils.GetAppSetting("DynamoDbUrl","http://dynamodb.us-east-1.amazonaws.com"),
         });
     return dynamoClient;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamoDbDataWriter"/> class.
        /// </summary>
        /// <param name="endpoint">The AWS DynamoDb service endpoint.</param>
        /// <param name="tableName">Name of the table used for logging.</param>
        public DynamoDbDataWriter(string endpoint, string tableName="")
        {
            if (string.IsNullOrEmpty(endpoint))
            {
                endpoint = DefaultServiceEndpoint;
            }

            DynamoDbClient = new AmazonDynamoDBClient(new AmazonDynamoDBConfig {ServiceURL = endpoint});
            LogTable = Table.LoadTable(DynamoDbClient, tableName);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine();
            Console.WriteLine("Setting up DynamoDB client");

            AmazonDynamoDBClient client = new AmazonDynamoDBClient();

            //CreateTablesWithData(client);
            //DefaultConcurrencyBehavior(client);
            ConditionalWriteSample(client);
        }
        protected void submitButton_Click(object sender, EventArgs e)
        {
            if (flFile.PostedFile != null && inId.Value != "" && SpeakerName.Text != "" && Email.Text != "" && Designation.Text != "" && Biography.Text != "" && Organization.Text != "")
            {
                //string FileName = Path.GetFileName(file.PostedFile.FileName);
                string fileToBackup = flFile.PostedFile.FileName;
                string fileName = flFile.FileName;// test file
                string myBucketName = "isbils"; //your s3 bucket name goes here
                string s3DirectoryName = "";
                // string s3FileName = @"mybackupFile uploaded in 10-1-2016.png";
                string Url = "https://s3.amazonaws.com/" + myBucketName + "/" + fileName;
                string imageNew = Url;
                AmazonUploader myUploader = new AmazonUploader();
                myUploader.sendMyFileToS3(fileToBackup, myBucketName, s3DirectoryName, flFile.PostedFile.InputStream, flFile.PostedFile.FileName);
                // string FileExtension = System.IO.Path.GetExtension(file.FileName);
                string FileExtension = System.IO.Path.GetExtension(flFile.FileName).Replace(".", "").ToLower();
                if (FileExtension == "jpg" || FileExtension == "png")
                {
                    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                    Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Speaker");

                    //var book = new Document();

                    var book = new Document();
                    book["eventId"] = inId.Value;
                    book["speakerName"] = SpeakerName.Text;
                    book["email"] = Email.Text;
                    book["designation"] = Designation.Text;
                    book["biography"] = Biography.Text;
                    book["imageUrl"] = Url;
                    book["organization"] = Organization.Text;

                    table.PutItem(book);
                    Response.Redirect("Speaker.aspx");
                    string script = "alert(\"Successfully created the Speaker.\");";
                    ScriptManager.RegisterStartupScript(this, GetType(),
                                          "ServerControlScript", script, true);
                }
                else
                {
                    string script = "alert(\"Please choose a file with extension 'png' or 'jpg'.\");";
                    ScriptManager.RegisterStartupScript(this, GetType(),
                                          "ServerControlScript", script, true);
                }
            }
            else
            {
                string script = "alert(\"Please fill all the data.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
        }
        static NotesDataContext()
        {
            // creating a DynamoDb client in some region (AmazonDynamoDBClient is thread-safe and can be reused
            var dynamoDbConfig = new AmazonDynamoDBConfig { RegionEndpoint = RegionEndpoint.APSoutheast1 };

            DynamoDbClient = new AmazonDynamoDBClient(dynamoDbConfig);

            // creating a MemcacheD client (it's thread-safe and can be reused)
            CacheClient = new MemcachedClient();

            // creating tables
            CreateTablesIfTheyDoNotExist();
        }
        public override IUserAuthRepository CreateAuthRepo()
        {
            var dynamoClient = new AmazonDynamoDBClient("keyId", "key", new AmazonDynamoDBConfig
            {
                ServiceURL = ConfigUtils.GetAppSetting("DynamoDbUrl", "http://localhost:8000"),
            });
            var db = new PocoDynamo(dynamoClient);

            var dynamoDbRepo = new DynamoDbAuthRepository(db);
            InitTest(dynamoDbRepo);
            dynamoDbRepo.InitSchema();
            return dynamoDbRepo;
        }
Beispiel #22
0
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;

            var dynamoClient = new AmazonDynamoDBClient("keyId", "key", new AmazonDynamoDBConfig {
                ServiceURL = "http://localhost:8000",
            });

            container.Register<IPocoDynamo>(c => new PocoDynamo(dynamoClient));

            var db = container.Resolve<IPocoDynamo>();
            db.RegisterTable<Todo>();
            db.InitSchema();
        }
Beispiel #23
0
        private static void QueryByHashKey(string userId, AmazonDynamoDBClient client, DynamoDBContext context)
        {
            var selectQuery = string.Format("SELECT * FROM GameScores WHERE UserId = \"{0}\"", userId);

            Console.WriteLine("(AmazonDynamoDBClient) Running basic hash key query :\n\t\t{0}", selectQuery);
            var response = client.Query(selectQuery);
            Debug.Assert(response.Items.Count == 5);
            Debug.Assert(response.Items.TrueForAll(i => i["UserId"].S == userId));

            Console.WriteLine("(DynamoDBContext) Running basic hash key query :\n\t\t{0}", selectQuery);
            var gameScores = context.ExecQuery<GameScore>(selectQuery).ToArray();
            Debug.Assert(gameScores.Count() == 5);
            Debug.Assert(gameScores.All(gs => gs.UserId == userId));
        }
Beispiel #24
0
        public Dictionary<string, object> GetPinWithPinID(string owner, double pinDate)
        {
            Dictionary<string, object> retval = new Dictionary<string, object>();
            QueryResponse response;
            var config = new AmazonDynamoDBConfig();
            config.ServiceURL = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
            client = new AmazonDynamoDBClient(config);
            try
            {
                QueryRequest request = new QueryRequest()
                {
                    TableName = "Pin",
                    KeyConditions = new Dictionary<string, Condition>()
                    {
                        {
                            "Owner",
                            new Condition()
                            {
                                ComparisonOperator = ComparisonOperator.EQ,
                                AttributeValueList = new List<AttributeValue> { new AttributeValue { S = owner } }
                            }
                        },
                        {
                            "PinDate",
                            new Condition()
                            {
                                ComparisonOperator = ComparisonOperator.EQ,
                                AttributeValueList = new List<AttributeValue> { new AttributeValue { N = pinDate.ToString() } }
                            }
                        }
                    }

                };
                response = client.Query(request);
                retval.Add("Title", response.Items[0]["Title"].S);
                retval.Add("Owner", response.Items[0]["Owner"].S);
                retval.Add("OwnerName", response.Items[0]["UserName"].S);
                retval.Add("OwnerHeadshot", response.Items[0]["HeadshotURL"].S);
                retval.Add("Latitude", response.Items[0]["Latitude"].S);
                retval.Add("Longitude", response.Items[0]["Longitude"].S);
                retval.Add("PinDate", Convert.ToDouble(response.Items[0]["PinDate"].N));
                retval.Add("Images", response.Items[0]["Images"].SS);
            }
            catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }

            return retval;
        }
        public void SaveNewVideo()
        {
            var client = new AmazonDynamoDBClient();
            var request = new PutItemRequest();
            request.TableName = "Local.Area";
            request.Item = new Dictionary<string, AttributeValue>();

            var value1 = new AttributeValue
            {
               S = "103"

            };

            request.Item.Add("Description", value1);
        }
Beispiel #26
0
        private static void QueryWithRangeKey(string userId, AmazonDynamoDBClient client, DynamoDBContext context)
        {
            var selectQuery = string.Format("SELECT * FROM GameScores WHERE UserId = \"{0}\" AND GameTitle BEGINS WITH \"A\"", userId);

            Console.WriteLine("(AmazonDynamoDBClient) Running query with range key :\n\t\t{0}", selectQuery);
            var response = client.Query(selectQuery);
            Debug.Assert(response.Items.Count == 2);
            Debug.Assert(response.Items.TrueForAll(i => i["UserId"].S == userId));
            Debug.Assert(response.Items.TrueForAll(i => i["GameTitle"].S.StartsWith("A")));

            Console.WriteLine("(DynamoDBContext) Running query with range key :\n\t\t{0}", selectQuery);

            var gameScores = context.ExecQuery<GameScore>(selectQuery).ToArray();
            Debug.Assert(gameScores.Count() == 2);
            Debug.Assert(gameScores.All(gs => gs.UserId == userId));
            Debug.Assert(gameScores.All(gs => gs.GameTitle.StartsWith("A")));
        }
        public void CanReadAndWriteData()
        {
            var client = new AmazonDynamoDBClient(RegionEndpoint.EUWest1);
            const string itemId = "1";
            var provider = new DynamoStore(new DynamoDBContext(client));
            var config = GetDynamoDbConfig();
            var table = new DynamoTable(config, client);

            table.CreateIfNotExist();

            provider.Save(new FakeDynamoItem { Id = itemId }, new DynamoDBOperationConfig());
            var result = provider.Read<FakeDynamoItem>(itemId, new DynamoDBOperationConfig());

            Assert.IsNotNull(result);
            Console.WriteLine(result.Id);
            Assert.AreEqual(result.Id, itemId);
        }
Beispiel #28
0
 public void TestAnonymousCredentialsGetThroughPipeline()
 {
     using (var client = new Amazon.DynamoDBv2.AmazonDynamoDBClient(new AnonymousAWSCredentials()))
     {
         try
         {
             client.ListTables();
         }
         catch (AmazonServiceException e)
         {
             if (e.StatusCode != HttpStatusCode.BadRequest)
             {
                 throw;
             }
         }
     }
 }
        public virtual void AddImage(AmazonDynamoDBClient dynamoDbClient, string tableName, AmazonS3Client s3Client, string bucketName, string imageKey, string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {

                    // Create the upload request
                    var putObjectRequest = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = imageKey,
                        FilePath = filePath
                    };

                    // Upload the object
                    s3Client.PutObject(putObjectRequest);

                    // Create the put item request to submit to DynamoDB
                    var putItemRequest = new PutItemRequest
                    {
                        TableName = tableName,
                        Item = new Dictionary<string, AttributeValue>
                        {
                            {"Key", new AttributeValue {S = imageKey}},
                            {"Bucket", new AttributeValue {S = bucketName}}
                        }
                    };

                    dynamoDbClient.PutItem(putItemRequest);
                    _Default.LogMessageToPage("Added imageKey: {0}", imageKey);
                }
                else
                {
                    _Default.LogMessageToPage("Skipped imageKey: {0}", imageKey);
                }
            }
            catch (Exception ex)
            {
                _Default.LogMessageToPage("AddImage Error: {0}", ex.Message);
            }
        }
        private static void ConditionalWriteSample(AmazonDynamoDBClient client)
        {
            Table table = Table.LoadTable(client, "Actors");
            Document d = table.GetItem("Christian Bale");

            int version = d["Version"].AsInt();
            double height = d["Height"].AsDouble();

            Console.WriteLine("Retrieved Item Version #" + version.ToString());

            var request = new UpdateItemRequest
            {
                Key = new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Christian Bale" } } },
                ExpressionAttributeNames = new Dictionary<string, string>()
                {
                    {"#H", "Height"},
                    {"#V", "Version"}
                },
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
                {
                    {":ht", new AttributeValue{N=(height+.01).ToString()}},
                    {":incr", new AttributeValue{N="1"}},
                    {":v", new AttributeValue{N=version.ToString()}}
                },
                UpdateExpression = "SET #V = #V + :incr, #H = :ht",
                ConditionExpression = "#V = :v",
                TableName = "Actors"
            };

            try
            {
                Console.ReadKey();
                var response = client.UpdateItem(request);
                Console.WriteLine("Updated succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Update failed. " + ex.Message);
            }

            Console.ReadKey();
        }
    protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
    {
      var records = events.Select(x => new LogDocument(x, x.RenderMessage(_formatProvider)));

      try
      {
        using (var client = new AmazonDynamoDBClient(AmazonDynamoDbConfig))
        {
          using (var context = new DynamoDBContext(client))
          {
            var batchWrite = context.CreateBatchWrite<LogDocument>(OperationConfig);
            batchWrite.AddPutItems(records);
            await batchWrite.ExecuteAsync();
          }
        }
      }
      catch (Exception exception)
      {
        SelfLog.WriteLine("Unable to write events to DynamoDB Sink for {0}: {1}", _tableName, exception);
      }
    }
        // Test exception parsing with selected services
        public void TestExceptions()
        {
            var fakeData = "obviously-super-duper-fake-data";

            using (var client = new Amazon.Lightsail.AmazonLightsailClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.Lightsail.Model.NotFoundException>(() =>
                {
                    client.GetInstance(new Amazon.Lightsail.Model.GetInstanceRequest
                    {
                        InstanceName = fakeData
                    });
                });
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var client = new Amazon.ElasticTranscoder.AmazonElasticTranscoderClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.ElasticTranscoder.Model.ValidationException>(() =>
                {
                    client.DeletePipeline(new Amazon.ElasticTranscoder.Model.DeletePipelineRequest
                    {
                        Id = fakeData
                    });
                });
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var ddb = new Amazon.DynamoDBv2.AmazonDynamoDBClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.DynamoDBv2.Model.ResourceNotFoundException>(() => ddb.DescribeTable("fakey-mcfake-table"));
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var client = new Amazon.Pinpoint.AmazonPinpointClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.Pinpoint.Model.NotFoundException>(() =>
                {
                    client.DeleteCampaign(new Amazon.Pinpoint.Model.DeleteCampaignRequest
                    {
                        ApplicationId = fakeData,
                        CampaignId    = fakeData
                    });
                });
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var client = new Amazon.Batch.AmazonBatchClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.Batch.Model.ClientException>(() =>
                {
                    client.UpdateComputeEnvironment(new Amazon.Batch.Model.UpdateComputeEnvironmentRequest
                    {
                        ComputeEnvironment = fakeData
                    });
                });
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var client = new Amazon.Glacier.AmazonGlacierClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.Glacier.Model.ResourceNotFoundException>(() =>
                {
                    client.InitiateMultipartUpload(new Amazon.Glacier.Model.InitiateMultipartUploadRequest
                    {
                        AccountId          = "-",
                        ArchiveDescription = fakeData,
                        VaultName          = fakeData,
                        PartSize           = 123
                    });
                });
                Assert.AreEqual(ErrorType.Unknown, ex.ErrorType);
            }

            using (var client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient())
            {
                var ex = AssertExtensions.ExpectException <Amazon.IdentityManagement.Model.NoSuchEntityException>(() =>
                {
                    client.AttachGroupPolicy(new Amazon.IdentityManagement.Model.AttachGroupPolicyRequest
                    {
                        PolicyArn = fakeData,
                        GroupName = fakeData
                    });
                });
                Assert.AreEqual(ErrorType.Sender, ex.ErrorType);
            }
        }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(collection =>
            {
                collection.Remove(new ServiceDescriptor(typeof(IDynamoDBContext),
                                                        a => a.GetService(typeof(IDynamoDBContext)), ServiceLifetime.Scoped));

                AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig
                {
                    RegionEndpoint = RegionEndpoint.EUCentral1,
                    UseHttp        = true,
                    ServiceURL     = DynamoDbServiceUrl
                };

                var dynamoDbClient = new AmazonDynamoDBClient("123", "123", clientConfig);

                collection.AddScoped <IDynamoDBContext, DynamoDBContext>(opt =>
                {
                    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                    client = dynamoDbClient;
                    var dynamoDbContext = new DynamoDBContext(client);
                    return(dynamoDbContext);
                });

                collection.Remove(new ServiceDescriptor(typeof(IAmazonDynamoDB),
                                                        a => a.GetService(typeof(IAmazonDynamoDB)), ServiceLifetime.Scoped));

                collection.AddAWSService <IAmazonDynamoDB>(options: new AWSOptions
                {
                    Region      = RegionEndpoint.EUCentral1,
                    Credentials = new BasicAWSCredentials("123", "123"),
                }, ServiceLifetime.Scoped);

                collection.Remove(new ServiceDescriptor(typeof(IAmazonSQS), a => a.GetService(typeof(IAmazonSQS)),
                                                        ServiceLifetime.Scoped));

                AmazonSQSConfig sqsConfig = new AmazonSQSConfig
                {
                    RegionEndpoint = RegionEndpoint.EUCentral1,
                    UseHttp        = true,
                    ServiceURL     = SqsServiceUrl,
                };

                var sqsClient = new AmazonSQSClient("123", "123", sqsConfig);

                collection.AddScoped <IAmazonSQS, AmazonSQSClient>(opt =>
                {
                    AmazonSQSConfig localSqsConfig = new AmazonSQSConfig
                    {
                        RegionEndpoint = RegionEndpoint.EUCentral1,
                        UseHttp        = true,
                        ServiceURL     = SqsServiceUrl,
                    };

                    var localSqsClient = new AmazonSQSClient("123", "123", localSqsConfig);

                    return(localSqsClient);
                });

                collection.RemoveAll(typeof(IHostedService));
                DynamoDbSeeder.CreateTable(dynamoDbClient);
                DynamoDbSeeder.Seed(dynamoDbClient);
                SqsSeeder.CreateQueue(sqsClient);
            });
            base.ConfigureWebHost(builder);
        }