Exemplo n.º 1
0
        public UnitTest1(ITestOutputHelper testOutputHelper)
        {
            _testOutputHelper = testOutputHelper;
            var containerService = new Builder()
                                   .UseContainer()
                                   .WithName("dynamodb-outbox")
                                   .UseImage("amazon/dynamodb-local:1.13.0")
                                   .KeepRunning()
                                   .ReuseIfExists()
                                   .Command("", "-jar", "DynamoDBLocal.jar", "-inMemory", "-sharedDb")
                                   .ExposePort(8000, 8000)
                                   .WaitForPort("8000/tcp", 5000, "127.0.0.1")
                                   .Build();

            _service = containerService.Start();

            var awsCredentials = new BasicAWSCredentials("ignored", "ignored");
            var dynamoDBConfig = new AmazonDynamoDBConfig
            {
                ServiceURL = "http://localhost:8000",
            };

            _client = new AmazonDynamoDBClient(awsCredentials, dynamoDBConfig);

            var streamsConfig = new AmazonDynamoDBStreamsConfig
            {
                ServiceURL = dynamoDBConfig.ServiceURL
            };

            _streamsClient = new AmazonDynamoDBStreamsClient(awsCredentials, streamsConfig);
        }
Exemplo n.º 2
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(creds, config);

            ScanResponse resp = new ScanResponse();

            ScanRequest req = new ScanRequest
            {
                ExclusiveStartKey = resp.LastEvaluatedKey
                ,
                Limit = maxItems
            };

            resp = client.Scan(req);
            CheckError(resp.HttpStatusCode, "200");

            foreach (var obj in resp.Items)
            {
                AddObject(obj);
            }
        }
Exemplo n.º 3
0
        public void SaveDynamoDb()
        {
            try
            {
                var config = new AmazonDynamoDBConfig();
                config.ServiceURL = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
                var client = new AmazonDynamoDBClient(config);

                Table ccdAudit = Table.LoadTable(client, "CcdAudit");

                var Audit = new Document();

                Audit["AuditId"]           = AuditId.ToString();
                Audit["MergeId"]           = MergeId.ToString();
                Audit["DateStamp"]         = DateStamp;
                Audit["MergeRule"]         = MergeRule;
                Audit["RuleVersion"]       = RuleVersion;
                Audit["PreRuleMasterCcd"]  = PreRuleMasterCcd.ToString();
                Audit["PostRuleMasterCcd"] = PostRuleMasterCcd.ToString();
                Audit["RunSeconds"]        = RunSeconds;

                ccdAudit.PutItem(Audit);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 4
0
        public async Task <bool> Exists()
        {
            CredentialProfileOptions options = new CredentialProfileOptions();

            Settings settings = Settings.Load();

            options.AccessKey = settings.DBKey;
            options.SecretKey = settings.DBSecret;

            CredentialProfile profile = new CredentialProfile("Default", options);

            profile.Region = RegionEndpoint.APSoutheast2;

            SharedCredentialsFile sharedFile = new SharedCredentialsFile();

            sharedFile.RegisterProfile(profile);

            AmazonDynamoDBConfig dbConfig = new AmazonDynamoDBConfig();

            this.client = new AmazonDynamoDBClient(dbConfig);

            ListTablesResponse listTablesResponse = await this.client.ListTablesAsync();

            return(listTablesResponse.TableNames.Contains(this.InternalName));
        }
Exemplo n.º 5
0
        public async Task SingleSuccessfulRequestAsync()
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };
            CSMTestUtilities testUtils = new CSMTestUtilities
            {
                Service            = "DynamoDB",
                ApiCall            = "ListTables",
                AttemptCount       = 1,
                Domain             = "dynamodb.us-east-1.amazonaws.com",
                Region             = "us-east-1",
                HttpStatusCode     = 200,
                MaxRetriesExceeded = 0,
                StashCount         = 3
            };
            var task = Task.Run(() => testUtils.UDPListener());
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(config);
            await client.ListTablesAsync(new ListTablesRequest { });

            Thread.Sleep(10);
            testUtils.EndTest();
            task.Wait();
            testUtils.Validate(task.Result);
        }
Exemplo n.º 6
0
        private static IAmazonDynamoDB CreateClient(
            ICredentialsProvider credentialsProvider,
            IDynamoDbOptions <T> options
            )
        {
            AWSCredentials credentials = credentialsProvider.GetCredentials(options.CredentialsProfile);

            if (!string.IsNullOrWhiteSpace(options.Role))
            {
                credentials = credentialsProvider.AssumeRole(
                    credentials,
                    options.Role
                    );
            }

            if (!string.IsNullOrWhiteSpace(options.RegionEndpoint))
            {
                AmazonDynamoDBConfig config = new AmazonDynamoDBConfig {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(options.RegionEndpoint)
                };
                return(new AmazonDynamoDBClient(credentials, config));
            }

            return(new AmazonDynamoDBClient(credentials));
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //services.AddDefaultAWSOptions(
            //    new AWSOptions
            //    {
            //        Region = RegionEndpoint.GetBySystemName("us-east-1")
            //    });

            if (env.IsDevelopment())
            {
                services.AddSingleton <IAmazonDynamoDB>(cc =>
                {
                    var clientConfig = new AmazonDynamoDBConfig {
                        ServiceURL = "http:localhost:8000"
                    };                                                                                 //4569
                    return(new AmazonDynamoDBClient(clientConfig));
                });
            }
            else
            {
                services.AddAWSService <IAmazonDynamoDB>();
            }
            services.AddAWSService <IAmazonDynamoDB>();
            services.AddSingleton <IMovieRankService, MovieRank.Services.ObjectPersistenceModel.MovieRankService>();
            services.AddSingleton <IMovieRankRepository, MovieRankRepository>();
            services.AddSingleton <IMapper, Mapper>();
            //services.AddSingleton<ISetupService, SetupService>();
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(creds, config);

            ListContributorInsightsResponse resp = new ListContributorInsightsResponse();

            do
            {
                ListContributorInsightsRequest req = new ListContributorInsightsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.ListContributorInsights(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.ContributorInsightsSummaries)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services
            .AddSwaggerGen(c =>
            {
                c.UseInlineDefinitionsForEnums();
                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title       = "POC DynamoDB",
                    Version     = "v1",
                    Description = ""
                });
                c.MapType <Guid>(() => new OpenApiSchema {
                    Type = "string", Format = "uuid"
                });
            });

            services.AddScoped(typeof(IBaseRepository <>), typeof(DynamoDbRepository <>));

            services.AddScoped <IProductRepository, ProductRepository>();

            var config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = RegionEndpoint.SAEast1, ServiceURL = Configuration["AWS:ConnectionString"]
            };
            var credentials = new BasicAWSCredentials(Configuration["AWS:AccessKey"], Configuration["AWS:SecretKey"]);

            services.AddSingleton <IAmazonDynamoDB>(new AmazonDynamoDBClient(credentials, config));
        }
Exemplo n.º 10
0
        public static IWishlistRepository Create()
        {
            var ddbConfig = new AmazonDynamoDBConfig();

            ddbConfig.ServiceURL = "http://localhost:8000";
            return(new DynamoDbRepository(new AmazonDynamoDBClient(ddbConfig)));
        }
Exemplo n.º 11
0
        protected Repository(IConfiguration config, string tableName)
        {
            var             dynamoConfig = config.GetSection("DynamoDb");
            var             awsConfig    = config.GetSection("Aws:Dynamo");
            var             runLocal     = Convert.ToBoolean(dynamoConfig["LocalMode"]);
            IAmazonDynamoDB client;

            if (!runLocal)
            {
                var credentials = new BasicAWSCredentials(awsConfig["AWSAccessKey"], awsConfig["AWSSecretKey"]);
                client = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);
            }
            else
            {
                var ddbConfig = new AmazonDynamoDBConfig
                {
                    RegionEndpoint = RegionEndpoint.SAEast1,
                    ServiceURL     = dynamoConfig["LocalServiceUrl"]
                };
                //takes credentials from environment/configfile
                client = new AmazonDynamoDBClient(ddbConfig);
            }
            Context = new DynamoDBContext(client, new DynamoDBContextConfig {
                TableNamePrefix = dynamoConfig["TableNamePrefix"]
            });
            _table = Table.LoadTable(client, tableName);
        }
        public void SingleSuccessfulRequest()
        {
            ThreadPool.QueueUserWorkItem(UDPListener);
            CSMTestUtilities testUtils = new CSMTestUtilities
            {
                Service            = "DynamoDB",
                ApiCall            = "ListTables",
                AttemptCount       = 1,
                Domain             = "dynamodb.us-east-1.amazonaws.com",
                Region             = "us-east-1",
                HttpStatusCode     = 200,
                MaxRetriesExceeded = 0,
                StashCount         = 3
            };
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(config);

            client.ListTables(new ListTablesRequest {
            });
            Thread.Sleep(10);
            testUtils.EndTest();
            testUtils.Validate(stash);
        }
Exemplo n.º 13
0
        public static void ConfigureDynamoDb(this IServiceCollection services, bool isDebug)
        {
            var tableName = Environment.GetEnvironmentVariable("LinkTable");

            AWSConfigsDynamoDB.Context.TypeMappings[typeof(LinkDto)] =
                new Amazon.Util.TypeMapping(typeof(LinkDto), tableName);

            var dbConfig = new AmazonDynamoDBConfig();

            if (isDebug)
            {
                //TODO parametrize
                dbConfig = new AmazonDynamoDBConfig
                {
                    RegionEndpoint = RegionEndpoint.APSoutheast2,
                    ServiceURL     = "http://localhost:8000"
                };
            }

            var client = new AmazonDynamoDBClient(dbConfig);
            var config = new DynamoDBContextConfig {
                Conversion = DynamoDBEntryConversion.V2
            };
            var ddbContext = new DynamoDBContext(client, config);

            services.AddSingleton <IDynamoDBContext>(ddbContext);
        }
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Add dynamo service

            var dynamoDbConfig = Configuration.GetSection("DynamoDB");

            if (dynamoDbConfig.GetValue <bool>("LocalMode"))
            {//Add Local DynamoDB Service if running dev mode - from appsettings.Development.json
                var serviceUrl = dynamoDbConfig.GetValue <string>("LocalUrl");
                services.AddSingleton <IAmazonDynamoDB>(sp =>
                {
                    var clientConfig = new AmazonDynamoDBConfig {
                        ServiceURL = serviceUrl
                    };
                    return(new AmazonDynamoDBClient(clientConfig));
                });
            }
            else
            {
                //Use real DynamoDB
                services.AddAWSService <IAmazonDynamoDB>();
            }

            #endregion Add dynamo service

            #region our dependencies
            services.AddSingleton <IUserWorker, UserWorker>();
            services.AddSingleton <IRandomIDGenerator, RandomIDGenerator>();
            #endregion ourdependencies

            services.AddControllers();
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(creds, config);

            BatchGetItemResponse resp = new BatchGetItemResponse();

            do
            {
                BatchGetItemRequest req = new BatchGetItemRequest
                {
                    RequestItems = resp.UnprocessedKeys
                };

                resp = client.BatchGetItem(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Responses)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.UnprocessedKeys)
                {
                    AddObject(obj);
                }
            }while (resp.UnprocessedKeys.Count > 0);
        }
        public async void CheckHighLevelItemCrud()
        {
            var portUsed = IsPortInUse();

            if (portUsed)
            {
                throw new Exception("You must run local DynamoDB on port " + _port);
            }

            var clientConfig = new AmazonDynamoDBConfig();

            clientConfig.ServiceURL = EndpointUrl;
            var client  = new AmazonDynamoDBClient(clientConfig);
            var context = CreateMockDynamoDbContext(client);

            // Create ProductCatalog table
            _output.WriteLine("Creating ProductCatalog table");
            await CreateTablesLoadData.CreateTablesLoadData.CreateTableProductCatalog(client);

            _output.WriteLine("Adding and deleting a book to/from ProductCatalog table");
            HighLevelItemCRUD.HighLevelItemCrud.TestCrudOperations(context);

            // Delete ProductCatalog table
            _output.WriteLine("Deleting ProductCatalog table");
            await CreateTablesLoadData.CreateTablesLoadData.DeleteTable(client, "ProductCatalog");

            _output.WriteLine("Done");
        }
Exemplo n.º 17
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(creds, config);

            ListTablesResponse resp = new ListTablesResponse();

            do
            {
                ListTablesRequest req = new ListTablesRequest
                {
                    ExclusiveStartTableName = resp.LastEvaluatedTableName
                    ,
                    Limit = maxItems
                };

                resp = client.ListTables(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.TableNames)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.LastEvaluatedTableName));
        }
Exemplo n.º 18
0
        public async void CheckLowLevelItemBinaryExample()
        {
            var portUsed = IsPortInUse();

            if (portUsed)
            {
                throw new Exception("You must run local DynamoDB on port " + _port);
            }

            var clientConfig = new AmazonDynamoDBConfig();

            clientConfig.ServiceURL = _endpointUrl;
            var client = new AmazonDynamoDBClient(clientConfig);

            // Reply table primary key.
            string replyIdPartitionKey  = "Amazon DynamoDB#DynamoDB Thread 1";
            string replyDateTimeSortKey = Convert.ToString(DateTime.UtcNow);

            // Create Reply table.
            _output.WriteLine("Creating Reply table");
            await CreateTablesLoadData.CreateTablesLoadData.CreateTableReply(client);

            _output.WriteLine("Creating item");
            await LowLevelItemBinaryExample.LowLevelItemBinaryExample.CreateItem(client, replyIdPartitionKey, replyDateTimeSortKey);

            _output.WriteLine("retrieving item");
            LowLevelItemBinaryExample.LowLevelItemBinaryExample.RetrieveItem(client, replyIdPartitionKey, replyDateTimeSortKey);

            _output.WriteLine("Deleting item");
            LowLevelItemBinaryExample.LowLevelItemBinaryExample.DeleteItem(client, replyIdPartitionKey, replyDateTimeSortKey);

            // Delete Reply table.
            _output.WriteLine("Deleting Reply table");
            await CreateTablesLoadData.CreateTablesLoadData.DeleteTable(client, "Reply");
        }
Exemplo n.º 19
0
        public async void CheckCreateTablesLoadData()
        {
            var portUsed = IsPortInUse();

            if (portUsed)
            {
                throw new Exception("You must run local DynamoDB on port " + _port);
            }

            var clientConfig = new AmazonDynamoDBConfig();

            clientConfig.ServiceURL = EndpointUrl;
            var client = new AmazonDynamoDBClient(clientConfig);

            // Create, load, and delete a table
            await CreateTablesLoadData.CreateTablesLoadData.CreateTableForum(client);

            _output.WriteLine("Waiting for Forum table to be created");

            //await CreateTablesLoadData.WaitTillTableCreated(client, "Forum", createResult.Result);
            _output.WriteLine("Created Forum table");

            CreateTablesLoadData.CreateTablesLoadData.LoadSampleForums(client);
            _output.WriteLine("Loaded data into Forum table");

            _ = CreateTablesLoadData.CreateTablesLoadData.DeleteTable(client, "Forum");
            _output.WriteLine("Deleted Forum table");
        }
Exemplo n.º 20
0
        public async Task SingleInvalidRequestAsync()
        {
            AmazonDynamoDBConfig config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };
            CSMTestUtilities testUtils = new CSMTestUtilities
            {
                Service             = "DynamoDB",
                ApiCall             = "DeleteTable",
                AttemptCount        = 1,
                Domain              = "dynamodb.us-east-1.amazonaws.com",
                Region              = "us-east-1",
                AWSException        = "ResourceNotFoundException",
                AWSExceptionMessage = "Requested resource not found",
                HttpStatusCode      = 400,
                MaxRetriesExceeded  = 0,
                StashCount          = 3
            };
            var task = Task.Run(() => testUtils.UDPListener());
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(config);
            var exception = await Record.ExceptionAsync(async() => await client.DeleteTableAsync(new DeleteTableRequest
            {
                TableName = "foobar"
            }));

            Assert.NotNull(exception);
            Assert.IsType <ResourceNotFoundException>(exception);
            Thread.Sleep(10);
            testUtils.EndTest();
            task.Wait();
            testUtils.Validate(task.Result);
        }
Exemplo n.º 21
0
 /// <summary>
 /// Create a client for the Amazon DynamoDB Service with the specified configuration
 /// </summary>
 /// <param name="awsAccessKey">The AWS Access Key associated with the account</param>
 /// <param name="awsSecretAccessKey">The AWS Secret Access Key associated with the account</param>
 /// <param name="config">Configuration options for the service like HTTP Proxy, # of connections, etc
 /// </param>
 /// <returns>An Amazon DynamoDB client</returns>
 /// <remarks>
 /// </remarks>
 public static IAmazonDynamoDB CreateAmazonDynamoDBClient(
     string awsAccessKey,
     string awsSecretAccessKey, AmazonDynamoDBConfig config
     )
 {
     return(new AmazonDynamoDBClient(awsAccessKey, awsSecretAccessKey, config));
 }
        public void RunBeforeAnyTests()
        {
            var clientConfig = new AmazonDynamoDBConfig {
                ServiceURL = "http://dynamodb-database:8000"
            };

            DynamoDBClient = new AmazonDynamoDBClient(clientConfig);
            try
            {
                var request = new CreateTableRequest("APIAuthenticatorData",
                                                     new List <KeySchemaElement> {
                    new KeySchemaElement("apiName", KeyType.HASH), new KeySchemaElement("environment", KeyType.RANGE)
                },
                                                     new List <AttributeDefinition> {
                    new AttributeDefinition("apiName", ScalarAttributeType.S), new AttributeDefinition("environment", ScalarAttributeType.S)
                },
                                                     new ProvisionedThroughput(3, 3));

                DynamoDBClient.CreateTableAsync(request).GetAwaiter().GetResult();
            }
            catch (ResourceInUseException)
            {
            }

            DynamoDbContext = new DynamoDBContext(DynamoDBClient);
        }
 public DynamoPersistenceProvider(AWSCredentials credentials, AmazonDynamoDBConfig config, IDynamoDbProvisioner provisioner, string tablePrefix, ILoggerFactory logFactory)
 {
     _logger      = logFactory.CreateLogger <DynamoPersistenceProvider>();
     _client      = new AmazonDynamoDBClient(credentials, config);
     _tablePrefix = tablePrefix;
     _provisioner = provisioner;
 }
Exemplo n.º 24
0
        public void TestLargeRetryCount()
        {
            var          maxRetries      = 1000;
            var          maxMilliseconds = 1;
            ClientConfig config          = new AmazonDynamoDBConfig();

            config.MaxErrorRetry = 100;
            var coreRetryPolicy = new DefaultRetryPolicy(config)
            {
                MaxBackoffInMilliseconds = maxMilliseconds
            };
            var ddbRetryPolicy = new DynamoDBRetryPolicy(config)
            {
                MaxBackoffInMilliseconds = maxMilliseconds
            };

            var context = new Amazon.Runtime.Internal.ExecutionContext(new RequestContext(false, new NullSigner()), null);

            for (int i = 0; i < maxRetries; i++)
            {
                context.RequestContext.Retries = i;
                coreRetryPolicy.WaitBeforeRetry(context);
                ddbRetryPolicy.WaitBeforeRetry(context);
            }
        }
Exemplo n.º 25
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            LogMessage(context, "Starting Execution");

            try
            {
                AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
                clientConfig.RegionEndpoint = RegionEndpoint.USEast1;
                AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);

                var repo     = new Movimientosrepository(client);
                var mapper   = new Mapper();
                var _service = new MovimientosService(repo, mapper);

                var results = await _service.GetAllItems();

                var response = CreateResponse(results);
                LogMessage(context, "Execution Completed");

                return(response);
            }
            catch (Exception e)
            {
                LogMessage(context, "Error: " + e.ToString());

                return(CreateResponse(null));
            }
        }
Exemplo n.º 26
0
            private async Task CreateDynamoTable(string tableName)
            {
                AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig
                {
                    ServiceURL = "http://localhost:8000"
                };
                var client = new AmazonDynamoDBClient(ddbConfig);

                try
                {
                    await client.DeleteTableAsync(tableName);
                }
                catch
                {
                }

                await client.CreateTableAsync(new CreateTableRequest()
                {
                    TableName = tableName,
                    KeySchema = new List <KeySchemaElement>()
                    {
                        new KeySchemaElement("HashKey", KeyType.HASH),
                        new KeySchemaElement("SortKey", KeyType.RANGE)
                    },
                    AttributeDefinitions = new List <AttributeDefinition>()
                    {
                        new AttributeDefinition("HashKey", ScalarAttributeType.S),
                        new AttributeDefinition("SortKey", ScalarAttributeType.N)
                    },
                    ProvisionedThroughput = new ProvisionedThroughput(100, 100)
                });
            }
        public string Get()
        {
            AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
            //    clientConfig.ServiceURL = "http://localhost:8000";
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);
            string tableName            = "users";
            var    request = new CreateTableRequest
            {
                AttributeDefinitions = new List <AttributeDefinition>()
                ,

                TableName = tableName
            };


            var   response   = client.CreateTable(request);
            Table usersTable = Table.LoadTable(client, tableName);

            Document user = new Document();

            user["id"]       = 1;
            user["name"]     = "shahaf";
            user["password"] = "******";
            usersTable.PutItem(user);
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "id", "name", "password"
                },
                ConsistentRead = true
            };
            Document doc = usersTable.GetItem(1, config);

            return(PrintDocument(doc));
        }
        public async void CheckLowLevelScan()
        {
            var portUsed = IsPortInUse();

            if (portUsed)
            {
                throw new Exception("You must run local DynamoDB on port " + _port);
            }

            var clientConfig = new AmazonDynamoDBConfig();

            clientConfig.ServiceURL = _endpointUrl;
            var client = new AmazonDynamoDBClient(clientConfig);

            // Create ProductCatalog table.
            _output.WriteLine("Creating ProductCatalog table.");
            await CreateTablesLoadData.CreateTablesLoadData.CreateTableProductCatalog(client);

            _output.WriteLine("Retrieving products < $0");
            LowLevelScan.LowLevelScan.FindProductsForPriceLessThanZero(client);

            // Delete ProductCatalog table.
            _output.WriteLine("Deleting ProductCatalog table.");
            await CreateTablesLoadData.CreateTablesLoadData.DeleteTable(client, "ProductCatalog");

            _output.WriteLine("Done");
        }
Exemplo n.º 29
0
        public static void ConfigureDynamoDB(this IServiceCollection services)
        {
            bool localMode = false;

            _ = bool.TryParse(Environment.GetEnvironmentVariable("DynamoDb_LocalMode"), out localMode);

            if (localMode)
            {
                var url = Environment.GetEnvironmentVariable("DynamoDb_LocalServiceUrl");
                services.AddSingleton <IAmazonDynamoDB>(sp =>
                {
                    var clientConfig = new AmazonDynamoDBConfig {
                        ServiceURL = url
                    };
                    return(new AmazonDynamoDBClient(clientConfig));
                });
            }
            else
            {
                services.AddAWSService <IAmazonDynamoDB>();
            }

            services.AddScoped <IDynamoDBContext>(sp =>
            {
                var db = sp.GetService <IAmazonDynamoDB>();
                return(new DynamoDBContext(db));
            });
        }
Exemplo n.º 30
0
        public static Table GetTableObject(string tableName)
        {
            // First, set up a DynamoDB client for DynamoDB Local
            AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();

            ddbConfig.ServiceURL = "http://localhost:8000";
            AmazonDynamoDBClient client;

            try
            {
                client = new AmazonDynamoDBClient(ddbConfig);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
                return(null);
            }

            // Now, create a Table object for the specified table
            Table table = null;

            try
            {
                table = Table.LoadTable(client, tableName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
                return(null);
            }
            return(table);
        }
Exemplo n.º 31
0
 public DynamoDbClient()
     : base()
 {
     var config = new AmazonDynamoDBConfig();
     client = new AmazonDynamoDBClient(config);
 }