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));
        }
Ejemplo n.º 2
0
        /*
         * public void putItemWithPublicKey(string clientIDPK, DBItemWithPublicKey securityKey, string TableName)
         * {
         *  try
         *  {
         *      Table table = Table.LoadTable(client, TableName);
         *
         *      var clientItem = new Document();
         *      clientItem["client_id"] = clientIDPK;
         *      clientItem["client_name"] = securityKey.ClientName;
         *      clientItem["client_public_key"] = securityKey.ClientPublicKey;
         *
         *      table.PutItemAsync(clientItem).GetAwaiter().GetResult();
         *      context.Logger.LogLine("DynamoDBHelper::PutItem() -- PutOperation succeeded");
         *  }
         *  catch (Exception ex)
         *  {
         *      context.Logger.LogLine("DynamoDBHelper::PutItem() -- " + ex.StackTrace);
         *  }
         * }
         */

        public Document getItem(string clientIDPK, string TableName)
        {
            context.Logger.LogLine("DynamoDBHelper::GetItem()=> TableName = " + TableName);
            context.Logger.LogLine("DynamoDBHelper::GetItem()=> ClientID = " + clientIDPK);
            Document clientItem = null;

            try
            {
                Table table = Table.LoadTable(client, TableName);


                // Configuration object that specifies optional parameters.
                GetItemOperationConfig config = new GetItemOperationConfig()
                {
                    AttributesToGet = new List <string>()
                    {
                        "CMKARN", "Encrypted256BitKey", "KMSEncryptedDataKey", "Normal256BitKey", "IV", "ClientSecretOTP", "SNSTopicARN", "OTPValidityInSeconds", "OTPGeneratedLinuxTime"
                    },
                };
                // Pass in the configuration to the GetItem method.
                // 1. Table that has only a partition key as primary key.
                clientItem = table.GetItemAsync(clientIDPK, config).GetAwaiter().GetResult();
                context.Logger.LogLine("DynamoDBHelper::GetItem() -- GetOperation succeeded");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine("DynamoDBHelper::GetItem() -- " + ex.StackTrace);
            }
            return(clientItem);
        }
Ejemplo n.º 3
0
        public JObject RetrieveChatById(int id)
        {
            Table chatTable = Table.LoadTable(client, tableName);
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "username", "text", "expiration_date"
                },
                ConsistentRead = true
            };
            Document document = chatTable.GetItem(id, config);

            if (document != null)
            {
                var jsonObject = ParseDocument(document);

                // calculate timeout with expiration date
                var returnJson = new JObject();
                returnJson.Add("username", (string)jsonObject.SelectToken("username"));
                returnJson.Add("text", (string)jsonObject.SelectToken("text"));
                var expiration = (int)jsonObject.SelectToken("expiration_date");
                var expDate    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expiration);
                returnJson.Add("expiration_date", expDate);

                return(returnJson);
            }

            return(null);
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        public Option <JObject> Load(string keyId, DateTimeOffset created)
        {
            using (MetricsUtil.MetricsInstance.Measure.Timer.Time(LoadTimerOptions))
            {
                try
                {
                    GetItemOperationConfig config = new GetItemOperationConfig
                    {
                        AttributesToGet = new List <string> {
                            AttributeKeyRecord
                        },
                        ConsistentRead = true, // Always use strong consistency
                    };
                    Document result = table.GetItemAsync(
                        keyId,
                        created.ToUnixTimeSeconds(),
                        config).Result;
                    if (result != null)
                    {
                        // TODO Optimize Document to JObject conversion. Helper method could enumerate over Document KeyPairs
                        // and convert DynamoDBEntry values based on type inspection
                        return(Option <JObject> .Some(JObject.Parse(result[AttributeKeyRecord].AsDocument().ToJson())));
                    }
                }
                catch (AggregateException ae)
                {
                    Logger.LogError(ae, "Metastore error");
                }

                return(Option <JObject> .None);
            }
        }
Ejemplo n.º 5
0
        public async Task <Document> GetItem(string tableName, string hashKey, string rangeKey)
        {
            var      tableRepo = new TableRepo(new AmazonDynamoDBClient());
            Document tableAttr = await tableRepo.GetTableAttr(tableName);

            List <string> attribute = new List <string> {
            };

            if (tableAttr != null)
            {
                var c = tableAttr["attr"].AsDocument().GetAttributeNames();
                foreach (var c1 in c)
                {
                    attribute.Add(c1);
                }
            }

            Table table = Table.LoadTable(dynamoDB, tableName);
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = attribute,
                ConsistentRead  = true
            };

            if (rangeKey != null)
            {
                return(await table.GetItemAsync(hashKey, rangeKey, config));
            }
            return(await table.GetItemAsync(hashKey, config));
        }
        public async Task <Author> GetAuthor(string id)
        {
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "id", "name"
                },
            };

            Document getResult = null;

            Author author = new Author();

            try
            {
                getResult = await authorsTable.GetItemAsync(id, config);

                author.id   = getResult["id"];
                author.name = getResult["name"];
            }
            catch (Exception ex)
            {
                Console.WriteLine("Can't Get Author. Message: " + ex.Message);
            }

            return(author);
        }
        public void OnPostSearch2()
        {
            AWSCredentials stsCredentails = _securityClient.GetTenantCredentials();

            IAmazonDynamoDB db        = new AmazonDynamoDBClient(stsCredentails, Amazon.RegionEndpoint.APSoutheast2);
            string          tableName = "Animals";
            Table           animalTbl = Table.LoadTable(db, tableName);

            GetItemOperationConfig config = new GetItemOperationConfig();

            config.AttributesToGet = new List <string>();
            config.AttributesToGet.Add("AnimalId");
            config.AttributesToGet.Add("Name");
            config.AttributesToGet.Add("Age");
            // config.AttributesToGet.Add("Breed");
            config.AttributesToGet.Add("Image");

            var singleItem = animalTbl.GetItemAsync(AnimalId, config).Result;

            AnimalSet = new List <AnimalInfo>();
            if (singleItem != null)
            {
                AnimalInfo info = new AnimalInfo();
                info.AnimalId = singleItem.ContainsKey("AnimalId")? (string)singleItem["AnimalId"]:String.Empty;
                info.Name     = singleItem.ContainsKey("Name") ? (string)singleItem["Name"] : String.Empty;
                info.Age      = singleItem.ContainsKey("Age") ? int.Parse(singleItem["Age"]) : 0;
                info.Breed    = singleItem.ContainsKey("Breed") ? (string)singleItem["Breed"] : String.Empty;
                info.Image    = singleItem.ContainsKey("Image") ? (string)singleItem["Image"] : String.Empty;
                AnimalSet.Add(info);
            }
        }
Ejemplo n.º 8
0
        public Document getItem(string PrimaryKeyID, string TableName)
        {
            context.Logger.LogLine("DynamoDBHelper::GetItem()=> TableName = " + TableName);
            context.Logger.LogLine("DynamoDBHelper::GetItem()=> PKID =  " + PrimaryKeyID);
            Document clientItem = null;

            try
            {
                Table table = Table.LoadTable(client, TableName);

                // Configuration object that specifies optional parameters.
                GetItemOperationConfig config = new GetItemOperationConfig()
                {
                    AttributesToGet = new List <string>()
                    {
                        "Name"
                    }
                };
                // Pass in the configuration to the GetItem method.
                // 1. Table that has only a partition key as primary key.
                clientItem = table.GetItemAsync(PrimaryKeyID, config).GetAwaiter().GetResult();
                context.Logger.LogLine("DynamoDBHelper::GetItem() -- GetOperation succeeded");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine("DynamoDBHelper::GetItem() -- " + ex.StackTrace);
            }
            return(clientItem);
        }
        //get the Bank Name of a given account based on a table name and an account id
        public static String getBankName(String tablename = "ATM", String myAccountId = "0002")
        {
            //Creation of a new Client
            AmazonDynamoDBClient dbc = new AmazonDynamoDBClient();

            //Load into a table called ATM thx to a DB client
            Table LoadProduct = Table.LoadTable(dbc, tablename);

            AutoClosingMessageBox.Show("\n*** Finding bank's name ***", "Data retrieval", 1000, Parent: Form.ActiveForm);

            // We define the Attributes to fetch (here Balance)
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "BankName"
                },
                ConsistentRead = true
            };

            //from the table, get the item described in the config
            Document document = LoadProduct.GetItem(myAccountId, config);

            return(strPrintDocument(document));
            //Checker(document);
        }
Ejemplo n.º 10
0
    private void RetrieveBook()
    {
        this.displayMessage += ("\n*** Executing RetrieveBook() ***");
        // Optional configuration.
        GetItemOperationConfig config = new GetItemOperationConfig
        {
            AttributesToGet = new List <string> {
                "Id", "ISBN", "Title", "Authors", "Price"
            },
            ConsistentRead = true
        };

        productCatalog.GetItemAsync(sampleBookId, config,
                                    (AmazonDynamoResult <Document> result) =>
        {
            if (result.Exception != null)
            {
                this.displayMessage += "\nRetrieveBook ; " + result.Exception.Message;
                Debug.LogException(result.Exception);
                return;
            }
            Document document    = result.Response;
            this.displayMessage += ("\nRetrieveBook: Printing book retrieved...");
            PrintDocument(document);
        }, null);
    }
        private Boolean usernameValid(String username)
        {
            // Define GetItem operation
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "username"
                },
                ConsistentRead = true
            };

            // Attempt to retrieve user from DynamoDB
            try
            {
                Document doc = usersTbl.GetItem(username, config); // Get item from table

                // Username not taken
                if (doc == null)
                {
                    return(true);
                }
            }
            catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }

            return(false);
        }
Ejemplo n.º 12
0
        private async Task <String> GetSignatureFromDynamoAsync(String domain, String sigSuffix)
        {
            Console.WriteLine("GetSignatureFromDynamoAsync : Checking for known email signature for : " + domain + " " + sigSuffix);
            try
            {
                AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(primaryRegion);
                Table table = Table.LoadTable(dynamoDBClient, "EmailSignatures");
                GetItemOperationConfig config = new GetItemOperationConfig
                {
                    AttributesToGet = new List <String> {
                        "signature" + sigSuffix
                    },
                    ConsistentRead = true
                };
                Document document = await table.GetItemAsync(domain, config);

                Console.WriteLine("SUCCESS : GetSignatureFromDynamoAsync : " + document["signature" + sigSuffix].AsPrimitive().Value.ToString());
                return(document["signature" + sigSuffix].AsPrimitive().Value.ToString());
            }
            catch (Exception error)
            {
                Console.WriteLine("ERROR : GetSignatureFromDynamoAsync : " + error.Message);
                Console.WriteLine(error.StackTrace);
                return("");
            }
        }
Ejemplo n.º 13
0
        public async Task <IDictionary <string, string> > RetrieveReport(string hashKey, string rangeKey)
        {
            Table reportsTable = Table.LoadTable(dynamoDBClient, tableName);

            //string hashKey = "111";
            //string rangeKey = "2";
            Console.WriteLine("hashKey is " + hashKey);
            Console.WriteLine("rangeKey is " + rangeKey);

            Console.WriteLine("Executing RetrieveItem()");
            // Optional configuration.
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "userid", "id", "title"
                },
                ConsistentRead = true
            };
            Document document = await reportsTable.GetItemAsync(hashKey, rangeKey, config);

            IDictionary <string, string> result = new Dictionary <string, string>();

            result["id"]    = document["id"].AsString();
            result["title"] = document["title"].AsString();
            Console.WriteLine("Found id which is " + result["id"] + " and title is " + result["title"]);
            return(result);
        }
Ejemplo n.º 14
0
        public Document getLogServerDetails(string Environment, string TableName)
        {
            context.Logger.LogLine("DynamoDBHelper::GetLogServerDetails()=> TableName = " + TableName);
            Document clientItem = null;

            try
            {
                Table table = Table.LoadTable(client, TableName);


                // Configuration object that specifies optional parameters.
                GetItemOperationConfig config = new GetItemOperationConfig()
                {
                    AttributesToGet = new List <string>()
                    {
                        "Database", "Environment", "Password", "Port", "Server", "Uid"
                    },
                };
                // Pass in the configuration to the GetItem method.
                // 1. Table that has only a partition key as primary key.
                clientItem = table.GetItemAsync(Environment, config).GetAwaiter().GetResult();
                context.Logger.LogLine("DynamoDBHelper::getLogServerDetails() -- GetOperation succeeded");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine("DynamoDBHelper::getLogServerDetails() -- " + ex.StackTrace);
            }
            return(clientItem);
        }
Ejemplo n.º 15
0
        public async Task <Document> GetItemAsync(DynamoDbTablesEnum dynamoDbTable,
                                                  Primitive primaryKey,
                                                  GetItemOperationConfig config)
        {
            Table table = this.LoadTable(dynamoDbTable);

            return(await table.GetItemAsync(primaryKey, config));
        }
        public async Task <DocumentDetails> GetRecordByTimeStamp(string id)
        {
            var config = new GetItemOperationConfig {
                ConsistentRead = true
            };
            var document = await _documentsTable.GetItemAsync(id, config);

            return(ParseRecord(document));
        }
Ejemplo n.º 17
0
        public Document Get(string id, bool consistentRead = true, List <string> attributesToGet = null)
        {
            GetItemOperationConfig config = new GetItemOperationConfig();

            if (attributesToGet != null)
            {
                config.AttributesToGet = attributesToGet;
            }
            config.ConsistentRead = consistentRead;

            return(dynamoDBTable.GetItem(id));
        }
        private async Task <Document> GetAsync(Primitive id, Primitive sortKey = null, bool consistentRead = true, List <string> attributesToGet = null)
        {
            GetItemOperationConfig config = new GetItemOperationConfig();

            if (attributesToGet != null)
            {
                config.AttributesToGet = attributesToGet;
            }
            config.ConsistentRead = consistentRead;

            return(await dynamoDBTable.GetItemAsync(id, config));
        }
Ejemplo n.º 19
0
 public void TestDynamoDB(string accessKeyId, string secretAccessKey)
 {
     var dbClient = new AmazonDynamoDBClient(accessKeyId, secretAccessKey, RegionEndpoint.USWest2);
     GetItemOperationConfig config = new GetItemOperationConfig
     {
         AttributesToGet = new List <string> {
             "Name"
         },
         ConsistentRead = true
     };
     var table = Table.LoadTable(dbClient, "DotNetTest");
     var item  = table.GetItemAsync("John", config).Result;
 }
Ejemplo n.º 20
0
        public async Task <RekognizedImage> GetImage(string hash)
        {
            using (var client = new AmazonDynamoDBClient(GetCredentials(), Region))
            {
                var table  = Table.LoadTable(client, "Image");
                var config = new GetItemOperationConfig
                {
                    AttributesToGet = new List <string>
                    {
                        "Hash",
                        "Width",
                        "Height",
                        "FaceHeight",
                        "FaceWidth",
                        "FaceLeft",
                        "FaceTop"
                    },
                    ConsistentRead = true
                };

                var document = await table.GetItemAsync(hash, config);

                if (document == null)
                {
                    return(null);
                }

                return(new RekognizedImage
                {
                    Hash = document["Hash"],
                    Width = document["Width"].AsInt(),
                    Height = document["Height"].AsInt(),
                    Faces = new List <Face>
                    {
                        new Face
                        {
                            FaceInfo = new FaceInfo
                            {
                                BoundingBox = new BoundingBox
                                {
                                    Width = document["FaceWidth"].AsInt(),
                                    Height = document["FaceHeight"].AsInt(),
                                    Left = document["FaceLeft"].AsInt(),
                                    Top = document["FaceTop"].AsInt(),
                                }
                            }
                        }
                    }
                });
            }
        }
Ejemplo n.º 21
0
        public async Task <Athlete> GetAthlete(int id)
        {
            var config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    Id, Name, AccessToken, RefreshToken, ExpiresAt, SlackUserId, SignupDateTimeUtc, ReminderCount, LastReminderDateTimeUtc, LatestActivityId
                },
                ConsistentRead = true
            };

            var document = await _athletesTable.GetItemAsync(id, config);

            return(document?.ToAthlete());
        }
Ejemplo n.º 22
0
        public async Task <Circle> GetCircle(Guid circleId)
        {
            var config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "Id", "UserId", "Name"
                },
                ConsistentRead = true
            };

            var document = await _circlesTable.GetItemAsync(circleId.ToString(), config);

            return(document.ToCircle());
        }
Ejemplo n.º 23
0
        public async Task <Document> GetTableAttr(string tableName)
        {
            Table table = Table.LoadTable(dynamoDB, "Table");
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "attr"
                },
                ConsistentRead = true
            };
            Document doc = await table.GetItemAsync(tableName, config);

            return(doc);
        }
        public async Task <User> GetUserByIdAsync(string userId)
        {
            var partitionKey = new Primitive(userId);
            var config       = new GetItemOperationConfig()
            {
                AttributesToGet = new List <string>()
                {
                    "Id", "FirstName"
                },
            };

            var userDocument = await UserTable.GetItemAsync(partitionKey, config);

            return(userDocument == null ? null : ConvertDocumentToUser(userDocument));
        }
        private static void RetrieveBook(Table productCatalog)
        {
            Console.WriteLine("\n*** Executing RetrieveBook() ***");
            // Optional configuration.
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "Id", "ISBN", "Title", "Authors", "Price"
                },
                ConsistentRead = true
            };
            Document document = productCatalog.GetItem(sampleBookId, config);

            Console.WriteLine("RetrieveBook: Printing book retrieved...");
            PrintDocument(document);
        }
        public static async void RetrieveBook(AmazonDynamoDBClient client, Table productCatalog)
        {
            Console.WriteLine("\n*** Executing RetrieveBook() ***");
            // Optional configuration.
            GetItemOperationConfig config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "Id", "ISBN", "Title", "Authors", "Price"
                },
                ConsistentRead = true
            };
            Document document = await productCatalog.GetItemAsync(SampleBookId, config);

            Console.WriteLine("RetrieveBook: Printing book retrieved...");
            PrintDocument(client, document);
        }
Ejemplo n.º 27
0
        private async Task <(DateTimeOffset, DateTimeOffset)> GetAuditDatesAsync(TodoTaskId taskId)
        {
            var getConfig = new GetItemOperationConfig {
                ConsistentRead = true
            };
            var          primaryKey       = taskId.Tag + "_" + taskId.Value;
            const string headSortKeyValue = "HEAD";

            var document = await _storageTable.GetItemAsync(primaryKey, headSortKeyValue, getConfig,
                                                            CancellationToken.None);

            var createdAt1  = DateTimeOffset.FromUnixTimeMilliseconds((long)document["CreatedAt"]);
            var modifiedAt1 = DateTimeOffset.FromUnixTimeMilliseconds((long)document["UpdatedAt"]);

            return(createdAt1, modifiedAt1);
        }
        private async Task <object> TryExecuteGetAsync(TranslationResult translationResult, Type entityType)
        {
            var entityKey = translationResult.TryGetEntityKeyForTable(this.TableDefinition);

            if (entityKey == null)
            {
                return(null);
            }

            Document resultDoc = null;

            // first trying to get entity from cache, but only if it's not a projection
            if (ReferenceEquals(this.TableEntityType, entityType))
            {
                resultDoc = this.Cache.GetSingleEntity(entityKey);
            }

            if (resultDoc != null)
            {
                this.Log("Get from cache: {0}", translationResult);
            }
            else
            {
                var config = new GetItemOperationConfig
                {
                    AttributesToGet = translationResult.AttributesToGet,
                    ConsistentRead  = this._consistentRead
                };
                translationResult.CustomizationHooks.ConfigureGetOperationCallback?.Invoke(config);

                // if the entity is not found in cache - then getting it from DynamoDb
                resultDoc = await this.TableDefinition.GetItemAsync
                            (
                    this.EntityKeyGetter.GetKeyDictionary(entityKey),
                    config
                            )
                            .ConfigureAwait(false); // This is important, as this method can be called synchronously from outside. Without this line it will hang in ASP.Net.

                // putting the entity to cache as well
                this.Cache.PutSingleLoadedEntity(entityKey, resultDoc);

                this.Log("Get from DynamoDb: {0}", translationResult);
            }

            // creating an enumerator for a single value or an empty enumerator
            return(this.CreateSingleDocReader(resultDoc, entityType, translationResult.ProjectionFunc));
        }
Ejemplo n.º 29
0
        private T LoadHelper <T>(Key key, DynamoDBFlatConfig flatConfig, ItemStorageConfig storageConfig, bool isAsync)
        {
            GetItemOperationConfig getConfig = new GetItemOperationConfig
            {
                ConsistentRead  = flatConfig.ConsistentRead.Value,
                AttributesToGet = storageConfig.AttributesToGet
            };

            Table       table   = GetTargetTable(storageConfig, flatConfig);
            ItemStorage storage = new ItemStorage(storageConfig);

            storage.Document = table.GetItemHelper(key, getConfig, isAsync);

            T instance = DocumentToObject <T>(storage, flatConfig);

            return(instance);
        }
Ejemplo n.º 30
0
        public static void RetrieveBook(this DynamoDBContext context, int sampleBookId)
        {
            Console.WriteLine("\n*** Executing RetrieveBook() ***");
            // Optional configuration.
            var config = new GetItemOperationConfig
            {
                AttributesToGet = new List <string> {
                    "Id", "Title"
                },
                ConsistentRead = true
            };

            var book = context.Load <Book>(sampleBookId, config);

            Console.WriteLine("RetrieveBook: Printing book retrieved...");
            PrintDocument(book);
        }