The Table class is the starting object when using the Document API. It is used to Get documents from the DynamnoDB table and write documents back to the DynamoDB table.
Exemplo n.º 1
0
        public void loadData()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.USEast2);
            Table  table    = Table.LoadTable(client, "Users");
            string email    = TxtUserEmail.Text;
            string password = TxtPassword.Password;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("Fields can't be empty!", "Alert", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            else
            {
                Document doc         = table.GetItem(email);
                string   emailInput  = doc.Values.ElementAt(1);
                string   userPasword = doc.Values.ElementAt(0);
                string   result      = emailInput;
                string   pass        = userPasword;
                if (email == result & password == pass)
                {
                    bookShelf = new BookShelf();
                    this.bookShelf.UserEmail = emailInput;

                    HomePage homePage = new HomePage(this.bookShelf);
                    homePage.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Incorrect Email or Password entered!");
                }
            }
        }
Exemplo n.º 2
0
        public static List <Document> GetAllDocumentsWithFilter(string tableName, string columnName, string filterValue)
        {
            try
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient(MyAWSConfigs.DynamodbRegion);

                Table table = Table.LoadTable(client, tableName);

                ScanFilter scanFilter = new ScanFilter();
                scanFilter.AddCondition(columnName, ScanOperator.Equal, filterValue);

                Search          search = table.Scan(scanFilter);
                List <Document> docs   = new List <Document>();
                do
                {
                    docs.AddRange(search.GetNextSet().ToList <Document>());
                } while (!search.IsDone);

                var temp = docs.ToList <Document>();

                client.Dispose();

                return(temp);
            }
            catch (AmazonDynamoDBException e)
            {
                Console.WriteLine("AmazonDynamoDBException: " + e);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
            }

            return(null);
        }
        private void BtnConfirmDelete_Click(object sender, RoutedEventArgs e)
        {
            var tableName = "Cameras";
            //load DynamoDB table
            var table = Table.LoadTable(client, tableName);
            var item  = table.GetItem(DeleteCamId);

            try
            {
                if (item != null)
                {
                    table.DeleteItem(item);
                    MessageBox.Show("Successfully Deleted!");
                }
                else
                {
                    MessageBox.Show("There is no such a Camera!");
                }
                MainView        mainv = new MainView();
                CamerasPageView cams  = new CamerasPageView();
                mainv.MenuPage.Content = cams;
                mainv.Show();
            }
            catch (AmazonDynamoDBException ex)
            {
                MessageBox.Show("Message : Server Error", ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message : Unknown Error", ex.Message);
            }
        }
Exemplo n.º 4
0
 internal static void LoadTableAsync(IAmazonDynamoDB ddbClient, string tableName, Table.DynamoDBConsumer consumer, DynamoDBEntryConversion conversion, AmazonDynamoDBCallback<Table> callback, AsyncOptions asyncOptions = null)
 {
     asyncOptions = asyncOptions??new AsyncOptions();
     DynamoDBAsyncExecutor.ExecuteAsync<Table>(
     ()=>{
         return LoadTable(ddbClient,tableName,consumer,conversion);
     },asyncOptions,callback);
 }
        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);
        }
        /// <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);
        }
        /// <summary>
        /// Gets a resource of a given type and with the provided id from a given table
        /// </summary>
        /// <param name="table"></param>
        /// <param name="typeName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task <dynamic> Get(DynamoDbTable table, string typeName, string id)
        {
            var hashKey  = new Primitive($"{typeName}");
            var rangeKey = new Primitive(id);

            Logger.Debug("Getting item with hash key {0} and range key {1} from table {2}...", hashKey, rangeKey, table.TableName);

            var result = await table.GetItemAsync(hashKey, rangeKey);

            return(result != null?DynamoDbDocumentHelper.ToObject(result) : null);
        }
Exemplo n.º 8
0
 private Table(AmazonDynamoDB ddbClient, string tableName, Table.DynamoDBConsumer consumer)
 {
     DDBClient = ddbClient;
     TableConsumer = consumer;
     TableName = tableName;
     Keys = new Dictionary<string, KeyDescription>();
     HashKeys = new List<string>();
     RangeKeys = new List<string>();
     LocalSecondaryIndexes = new Dictionary<string, LocalSecondaryIndexDescription>();
     LocalSecondaryIndexNames = new List<string>();
     Attributes = new List<AttributeDefinition>();
 }
Exemplo n.º 9
0
        private void AddCamera(string camid, string loc, string qlty)
        {
            try
            {
                string tableName = "Cameras";

                var table  = Table.LoadTable(client, tableName);
                var search = table.Scan(new Amazon.DynamoDBv2.DocumentModel.Expression());

                if (search.Count != 0)
                {
                    var item = table.GetItem(camid);

                    if (item == null)
                    {
                        //Console.WriteLine("search  = ", search);
                        //Console.WriteLine("search.count  = ", search.Count);


                        this.Close();
                        MessageBox.Show("New Camera Was Successfully Added!");
                    }
                    else
                    {
                        CreateCameraTable(tableName);
                        MessageBox.Show("Camera ID is already exist! (Please try a different one)");
                    }

                    Document camObj = new Document();
                    camObj["camId"]    = camid;
                    camObj["location"] = loc;
                    camObj["quality"]  = qlty;
                    table.PutItem(camObj);
                }
                else
                {
                    MessageBox.Show("Table scan doesn't gives results");
                }

                MainView        mainv = new MainView();
                CamerasPageView cams  = new CamerasPageView();
                mainv.MenuPage.Content = cams;
                mainv.Show();
            }
            catch (AmazonDynamoDBException ex)
            {
                MessageBox.Show("Message : Server Error", ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message : Unknown Error", ex.Message);
            }
        }
        /// <summary>
        /// Tries to make up a query request from the list of conditions using table keys and local secondary indexes
        /// </summary>
        internal static bool TryGetQueryFilterForTable(this TranslationResult translationResult, Table tableDefinition, out QueryFilter resultFilter, out string indexName)
        {
            resultFilter = null;
            indexName = null;

            Primitive hashKeyValue;
            if (!translationResult.Conditions.TryGetValueForKey(tableDefinition.HashKeys[0], out hashKeyValue))
            {
                return false;
            }
            if (hashKeyValue == null)
            {
                throw new NotSupportedException("Hash key value should not be null");
            }

            resultFilter = new QueryFilter(tableDefinition.HashKeys[0], QueryOperator.Equal, hashKeyValue);

            // Copying the list of conditions. without HashKey condition, which is already matched.
            var conditions = translationResult.Conditions.ExcludeField(tableDefinition.HashKeys[0]);

            if (conditions.Count <= 0)
            {
                return true;
            }

            // first trying to search by range key
            if
            (
                (tableDefinition.RangeKeys.Count == 1)
                &&
                (TryMatchFieldWithCondition(tableDefinition.RangeKeys[0], resultFilter, conditions))
            )
            {
                return TryPutRemainingConditionsToQueryFilter(resultFilter, conditions);
            }

            // now trying to use local secondary indexes
            foreach (var index in tableDefinition.LocalSecondaryIndexes.Values)
            {
                // a local secondary index should always have range key
                string indexedField = index.KeySchema.Single(kse => kse.KeyType == "RANGE").AttributeName;

                if (TryMatchFieldWithCondition(indexedField, resultFilter, conditions))
                {
                    indexName = index.IndexName;
                    return TryPutRemainingConditionsToQueryFilter(resultFilter, conditions);
                }
            }

            return false;
        }
Exemplo n.º 11
0
        protected void LoadData(object obj)
        {
            //load DynamoDB table
            var table = Table.LoadTable(client, "Cameras");
            //scan the table for get all details
            var search = table.Scan(new Amazon.DynamoDBv2.DocumentModel.Expression());

            // create DynamoDB document with scanned data
            var documentList = new List <Document>();

            do
            {
                documentList.AddRange(search.GetNextSet());
            } while (!search.IsDone);

            // create a Collection
            //Camera is the name of the model in <Camera>, it is in Models Folder(Camera.cs)
            var cameras = new ObservableCollection <Camera>();

            // getting DynamoDB Document data to Collection
            foreach (var doc in documentList)
            {
                var camera = new Camera();
                foreach (var attribute in doc.GetAttributeNames())
                {
                    var value = doc[attribute];
                    if (attribute == "camId")
                    {
                        camera.camId = value.AsPrimitive().Value.ToString();
                        //Console.WriteLine(camera.camId);
                    }
                    else if (attribute == "location")
                    {
                        camera.location = value.AsPrimitive().Value.ToString();
                        //Console.WriteLine(camera.location);
                    }
                    else if (attribute == "quality")
                    {
                        camera.quality = value.AsPrimitive().Value.ToString();
                        //Console.WriteLine("quality",camera.quality);
                    }
                }

                //Add camera data to collection
                cameras.Add(camera);
                //give itemsource to datagrid in the frontend, DataGrid's name is CamerasDataGrid
                CamerasDataGrid.ItemsSource = cameras;
            }
        }
Exemplo n.º 12
0
 void LoadTableListener ()
 {
     resultText.text = "\n***LoadTable***";
     Table.LoadTableAsync(_client,"ProductCatalog",(loadTableResult)=>{
         if(loadTableResult.Exception != null)
         {
             resultText.text += "\n failed to load product catalog table";
         }
         else
         {
             productCatalogTable = loadTableResult.Result;
             LoadSampleProducts();
         }
     });
     Table.LoadTableAsync(_client,"Thread",(loadTableResult)=>{
         if(loadTableResult.Exception != null)
         {
             resultText.text += "\n failed to load thread table";
         }
         else
         {
             threadTable = loadTableResult.Result;
             LoadSampleThreads();
         }
     });
     Table.LoadTableAsync(_client,"Reply",(loadTableResult)=>{
         if(loadTableResult.Exception != null)
         {
             resultText.text += "\n failed to load reply table";
         }
         else
         {
             replyTable = loadTableResult.Result;
             LoadSampleReplies();
         }
     });
     Table.LoadTableAsync(_client,"Forum",(loadTableResult)=>{
         if(loadTableResult.Exception != null)
         {
             resultText.text += "\n failed to load reply table";
         }
         else
         {
             forumTable = loadTableResult.Result;
             LoadSampleForums();
         }
     });
 }
Exemplo n.º 13
0
        private Product GetItem(int id)
        {
            AmazonDynamoDBClient client = dynamoDBClient.Value;

            Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Product");

            Document record = table.GetItem(id.ToString());

            Product p = new Product();

            p.Id       = id;
            p.Name     = record["Name"];
            p.Price    = record["Price"].AsDecimal();
            p.Category = record["Category"];
            return(p);
        }
        internal TableDefinitionWrapperBase(Table tableDefinition, Type tableEntityType, object hashKeyValue, ITableCache cacheImplementation, bool consistentRead)
        {
            this.TableDefinition = tableDefinition;
            this.TableEntityType = tableEntityType;
            this._consistentRead = consistentRead;

            // if a predefined HashKey value was specified
            if (hashKeyValue != null)
            {
                this._hashKeyType = hashKeyValue.GetType();
                this.HashKeyValue = hashKeyValue.ToPrimitive(this._hashKeyType);
            }

            this.Cache = cacheImplementation;
            this.Cache.Initialize(tableDefinition.TableName, this.TableEntityType, this.HashKeyValue);
        }
Exemplo n.º 15
0
        public bool userExists()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.USEast2);
            Table    table = Table.LoadTable(client, "Users");
            string   email = TxtUserEmail.Text;
            Document doc   = table.GetItem(email);

            if (doc == null)
            {
                userExist = false;
            }
            else
            {
                userExist = true;
            }
            return(userExist);
        }
Exemplo n.º 16
0
        internal static IEntityKeyGetter CreateInstance(Table tableDefinition, Type entityType, Type hashKeyType, Primitive predefinedHashKeyValue)
        {
            if (predefinedHashKeyValue != null)
            {
                if (tableDefinition.RangeKeys.Count <= 0)
                {
                    throw new InvalidOperationException("When specifying constant hash key values, the table must always have a range key");
                }

                var rangePropInfo = entityType.GetProperty(tableDefinition.RangeKeys[0], BindingFlags.Instance | BindingFlags.Public);
                if (rangePropInfo == null)
                {
                    throw new InvalidOperationException(string.Format("Entity type {0} doesn't contain range key property {1}", entityType.Name, tableDefinition.RangeKeys[0]));
                }

                return new ConstantHashRangeEntityKeyGetter(tableDefinition.HashKeys[0], hashKeyType, predefinedHashKeyValue, rangePropInfo);
            }
            if (tableDefinition.RangeKeys.Count > 0)
            {
                var hashPropInfo = entityType.GetProperty(tableDefinition.HashKeys[0], BindingFlags.Instance | BindingFlags.Public);
                var rangePropInfo = entityType.GetProperty(tableDefinition.RangeKeys[0], BindingFlags.Instance | BindingFlags.Public);
                
                if (hashPropInfo == null)
                {
                    throw new InvalidOperationException(string.Format("Entity type {0} doesn't contain hash key property {1}", entityType.Name, tableDefinition.HashKeys[0]));
                }
                if (rangePropInfo == null)
                {
                    throw new InvalidOperationException(string.Format("Entity type {0} doesn't contain range key property {1}", entityType.Name, tableDefinition.RangeKeys[0]));
                }

                return new HashRangeEntityKeyGetter(hashPropInfo, rangePropInfo);
            }
            else
            {
                var hashPropInfo = entityType.GetProperty(tableDefinition.HashKeys[0], BindingFlags.Instance | BindingFlags.Public);

                if (hashPropInfo == null)
                {
                    throw new InvalidOperationException(string.Format("Entity type {0} doesn't contain hash key property {1}", entityType.Name, tableDefinition.HashKeys[0]));
                }

                return new HashEntityKeyGetter(hashPropInfo);
            }
        }
        /// <summary>
        /// Tries to extract entity key from the list of conditions
        /// </summary>
        internal static EntityKey TryGetEntityKeyForTable(this TranslationResult translationResult, Table tableDefinition)
        {
            Primitive hashKeyValue;
            if (!translationResult.Conditions.TryGetValueForKey(tableDefinition.HashKeys[0], out hashKeyValue))
            {
                return null;
            }

            if (hashKeyValue == null)
            {
                throw new InvalidOperationException("Hash key value should not be null");
            }

            // if there's a range key in the table
            if (tableDefinition.RangeKeys.Any())
            {
                Primitive rangeKeyValue;
                if(!translationResult.Conditions.TryGetValueForKey(tableDefinition.RangeKeys[0], out rangeKeyValue))
                {
                    return null;
                }

                //TODO: check, that hash and range keys really cannot be null
                if (rangeKeyValue == null)
                {
                    throw new NotSupportedException("Range key value should not be null");
                }

                // if any other conditions except hash and range key specified
                if (translationResult.Conditions.Count > 2)
                {
                    throw new NotSupportedException("When requesting a single entity by it's hash key and range key, no need to specify additional conditions");
                }

                return new EntityKey(hashKeyValue, rangeKeyValue);
            }

            // if any other conditions except hash key specified
            if (translationResult.Conditions.Count > 1)
            {
                throw new NotSupportedException("When requesting a single entity by it's hash key, no need to specify additional conditions");
            }

            return new EntityKey(hashKeyValue);
        }
 internal TableDefinitionWrapper(Table tableDefinition, Type tableEntityType, object hashKeyValue, ITableCache cacheImplementation, bool consistentRead)
     : base(tableDefinition, tableEntityType, hashKeyValue, cacheImplementation, consistentRead)
 {
     if (this.HashKeyValue == null)
     {
         this.ToDocumentConversionFunctor = DynamoDbConversionUtils.ToDocumentConverter(this.TableEntityType);
     }
     else
     {
         var converter = DynamoDbConversionUtils.ToDocumentConverter(this.TableEntityType);
         // adding a step for filling in the predefined HashKey value
         this.ToDocumentConversionFunctor = entity =>
             {
                 var doc = converter(entity);
                 doc[this.TableDefinition.HashKeys[0]] = this.HashKeyValue;
                 return doc;
             };
     }
 }
Exemplo n.º 19
0
 //update item query
 public static void UpdateItem(Document item, string tableName)
 {
     try
     {
         AmazonDynamoDBClient client;
         using (client = new AmazonDynamoDBClient(MyAWSConfigs.DynamodbRegion))
         {
             var table = Table.LoadTable(client, tableName);
             table.UpdateItem(item);
         }
     }
     catch (AmazonDynamoDBException e)
     {
         Console.WriteLine("AmazonDynamoDBException: " + e);
     }
     catch (Exception e)
     {
         Console.WriteLine("Error: " + e);
     }
 }
Exemplo n.º 20
0
        private void UpdateCamera(string cid, string loc, string qlty)
        {
            var tableName = "Cameras";
            //load DynamoDB table
            var table = Table.LoadTable(client, tableName);
            var item  = table.GetItem(cid);

            try
            {
                //Console.WriteLine(item["aPassword"]);

                if (item != null)
                {
                    Document camObj = new Document();
                    camObj["camId"]    = cid;
                    camObj["location"] = loc;
                    camObj["quality"]  = qlty;
                    table.PutItem(camObj);
                    MessageBox.Show("Successfully Updated!");
                }
                else
                {
                    MessageBox.Show("There is no such a Camera!");
                }

                MainView        mainv = new MainView();
                CamerasPageView cams  = new CamerasPageView();
                mainv.MenuPage.Content = cams;
                mainv.Show();
            }
            catch (AmazonDynamoDBException ex)
            {
                MessageBox.Show("Message : Server Error", ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message : Unknown Error", ex.Message);
            }
        }
Exemplo n.º 21
0
        private void searchTravelPackageButton_Click(object sender, RoutedEventArgs e)
        {
            SecondWindow f2 = new SecondWindow();

            f2.destinationLabel.Content = "Destination: " + destinationSelectionBox.SelectionBoxItem;
            f2.budgetLabel.Content      = "Budget: $" + budgetTextBox.Text;
            f2.Show();
            Close();



            Table table  = Table.LoadTable(client, "Travels");
            var   travel = new Document();

            int    bgt = int.Parse(budgetTextBox.Text);
            String des = (string)destinationSelectionBox.SelectionBoxItem;

            travel["Budget"]      = bgt;
            travel["Destination"] = des;

            table.PutItem(travel);
        }
Exemplo n.º 22
0
        public static Document GetItem(String itemId, string tableName)
        {
            try
            {
                AmazonDynamoDBClient client;
                using (client = new AmazonDynamoDBClient(MyAWSConfigs.DynamodbRegion))
                {
                    var      table = Table.LoadTable(client, tableName);
                    Document item  = table.GetItem(itemId);

                    return(item);
                }
            }
            catch (AmazonDynamoDBException e)
            {
                Console.WriteLine("AmazonDynamoDBException: " + e);
                return(new Document());
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
                return(new Document());
            }
        }
Exemplo n.º 23
0
        // Test if the given attribute is a key on the table or a key on the given index
        private static bool IsKeyAttribute(Table table, string indexName, string attributeName)
        {
            GlobalSecondaryIndexDescription gsi;
            LocalSecondaryIndexDescription lsi;

            // if no index, check only table keys
            if (string.IsNullOrEmpty(indexName))
                return table.Keys.ContainsKey(attributeName);
            // for an index, check if attribute is part of KeySchema for GSI or LSI
            else if (table.GlobalSecondaryIndexes.TryGetValue(indexName, out gsi) && gsi != null)
                return gsi.KeySchema.Any(AttributeIsKey(attributeName));
            else if (table.LocalSecondaryIndexes.TryGetValue(indexName, out lsi) && lsi != null)
                return lsi.KeySchema.Any(AttributeIsKey(attributeName));
            else
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                    "Unable to locate index [{0}] on table [{1}]", indexName, table.TableName));
        }
Exemplo n.º 24
0
        private static void SplitQueryFilter(Filter filter, Table targetTable, string indexName, out Dictionary<string, Condition> keyConditions, out Dictionary<string, Condition> filterConditions)
        {
            QueryFilter queryFilter = filter as QueryFilter;
            if (queryFilter == null) throw new InvalidOperationException("Filter is not of type QueryFilter");

            keyConditions = new Dictionary<string, Condition>();
            filterConditions = new Dictionary<string, Condition>();

            var conditions = filter.ToConditions(targetTable.Conversion);
            foreach (var kvp in conditions)
            {
                string attributeName = kvp.Key;
                Condition condition = kvp.Value;

                // depending on whether the attribute is key, place either in keyConditions or filterConditions
                if (IsKeyAttribute(targetTable, indexName, attributeName))
                    keyConditions[attributeName] = condition;
                else
                    filterConditions[attributeName] = condition;
            }
        }
Exemplo n.º 25
0
        private void GiveRedersToRefernces(List <String> refList, String readerId)
        {
            try
            {
                Console.WriteLine(readerId);
                foreach (String chkd_ref in refList)
                {
                    string tableName = MyAWSConfigs.RefPersonsDBTableName;
                    Table  table     = Table.LoadTable(client, tableName);

                    Console.WriteLine("\n*** Executing UpdateMultipleAttributes() ***");
                    Console.WriteLine("\nUpdating multiple attributes....");
                    string partitionKey = chkd_ref;

                    Document doc = new Document();
                    doc["id"] = partitionKey;
                    // List of attribute updates.
                    // The following replaces the existing authors list.

                    Item item = table.GetItem(chkd_ref);
                    Console.WriteLine(item["id"]);
                    //Console.WriteLine(item["readerList"]);
                    List <string> readersList = new List <string>();
                    if (item["readerList"] != null)
                    {
                        readersList = item["readerList"].AsListOfString();
                        var match = readersList.FirstOrDefault(stringToCheck => stringToCheck.Contains(readerId));
                        if (match != null)
                        {
                            readersList.Add(readerId);
                            foreach (string i in readersList)
                            {
                                Console.WriteLine("reader !match >>>>>> " + i);
                            }
                            doc["readerList"] = readersList;
                            // Optional parameters.
                            UpdateItemOperationConfig config = new UpdateItemOperationConfig
                            {
                                // Get updated item in response.
                                ReturnValues = ReturnValues.AllNewAttributes
                            };
                            Document updatedadmin = table.UpdateItem(doc, config);
                            Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                            //MessageBox.Show("Successfully Updated! not null");
                        }
                        else
                        {
                            readersList.Add(readerId);
                            foreach (string i in readersList)
                            {
                                Console.WriteLine("reader match >>>>>> " + i);
                            }
                            doc["readerList"] = readersList;
                            // Optional parameters.
                            UpdateItemOperationConfig config = new UpdateItemOperationConfig
                            {
                                // Get updated item in response.
                                ReturnValues = ReturnValues.AllNewAttributes
                            };
                            Document updatedadmin = table.UpdateItem(doc, config);
                            Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                            //MessageBox.Show("Successfully Updated! not null");
                        }
                    }
                    else
                    {
                        foreach (string i in readersList)
                        {
                            Console.WriteLine("reader null >>>>>> " + i);
                        }

                        doc["readerList"] = readersList;
                        // Optional parameters.
                        UpdateItemOperationConfig config = new UpdateItemOperationConfig
                        {
                            // Get updated item in response.
                            ReturnValues = ReturnValues.AllNewAttributes
                        };
                        Document updatedadmin = table.UpdateItem(doc, config);
                        Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                        MessageBox.Show("Successfully Updated! null");
                    }
                }
            }
            catch (AmazonDynamoDBException ex)
            {
                MessageBox.Show("Message : Server Error", ex.Message);
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Message : Unknown Error- Updating Refs", ex.Message);
            }
            finally
            {
            }
        }
Exemplo n.º 26
0
        private async void ButtonSubmit_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("this is submit button");
            String name = txtName.Text;

            //MessageBox.Show(name);

            try
            {
                bool isNameEmpty        = string.IsNullOrEmpty(txtName.Text);
                bool isPhoneEmpty       = string.IsNullOrEmpty(txtPhone.Text);
                bool isDescriptionEmpty = string.IsNullOrEmpty(txtDescription.Text);
                bool isFilePathEmpty    = string.IsNullOrEmpty(uploadFilePath);
                bool isFileIdEmpty      = string.IsNullOrEmpty(txtId.Text);

                if (!isNameEmpty && !isDescriptionEmpty && !isPhoneEmpty)
                {
                    string tableName = MyAWSConfigs.ReaderDBtableName;
                    Table  table     = Table.LoadTable(client, tableName);

                    ProgressDialogController controller = await this.ShowProgressAsync("Please wait...", "");

                    controller.SetIndeterminate();
                    controller.SetCancelable(false);


                    string partitionKey = txtId.Text;
                    Console.WriteLine("oooooooooooooooooooooooooooooooo" + partitionKey);

                    var item = new Document();

                    Document doc = new Document();
                    doc["id"]          = partitionKey;
                    doc["name"]        = txtName.Text;
                    doc["phone"]       = txtPhone.Text;
                    doc["description"] = txtDescription.Text;
                    ///////////////////////////////////////////////////       //#ToDo : Add readerList
                    //item["readerList"] = readerList;

                    UpdateItemOperationConfig config = new UpdateItemOperationConfig
                    {
                        // Get updated item in response.
                        ReturnValues = ReturnValues.AllNewAttributes
                    };

                    if (uploadFilePath != null)
                    {
                        string[] temp = uploadFilePath.Split('.');
                        string   BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory;
                        string   filePath          = BaseDirectoryPath + $"Resources\\Images\\{partitionKey}";
                        item = table.GetItem(partitionKey);
                        string oldImage = item["aPropic"];
                        Console.WriteLine("><><><><><><><><><><>" + oldImage);

                        //Delete old profile pic in local
                        string oldFilePath = BaseDirectoryPath + $"Resources\\Images\\{oldImage}";
                        DeleteOldPic(oldFilePath);

                        //Delete old profile pic in s3Bucket
                        controller.SetMessage("Deleting File");
                        await Task.Run(() => S3Bucket.DeleteFile(oldImage, MyAWSConfigs.RefImagesBucketName));


                        controller.SetMessage("Uploading file");
                        await Task.Run(() => Models.S3Bucket.UploadFile(uploadFilePath, partitionKey, Models.MyAWSConfigs.RefImagesBucketName));
                    }

                    controller.SetMessage("Adding database record");
                    await Task.Run(() => table.UpdateItem(doc, config));

                    Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                    //MessageBox.Show("Successfully Updated!");

                    await controller.CloseAsync();

                    await this.ShowMessageAsync("Success", "Person Updated !", MessageDialogStyle.Affirmative);
                }
                else
                {
                    await this.ShowMessageAsync("Error", "Please check all fields", MessageDialogStyle.Affirmative);
                }
            }
            catch
            {
                await this.ShowMessageAsync("Error", "Task not completed", MessageDialogStyle.Affirmative);
            }
        }
 public DynamoDBOfflineClientSettings(Table configTable)
     : base(configTable)
 {
 }
        /// <summary>
        /// Prepares parameters for a scan operation from the list of conditions
        /// </summary>
        internal static ScanFilter GetScanFilterForTable(this TranslationResult translationResult, Table tableDefinition)
        {
            // the last thing to do is to make a full scan
            var scanFilter = new ScanFilter();

            //TODO: check for BETWEEN operator
            foreach (var condition in translationResult.Conditions.Flatten())
            {
                if 
                (
                    (condition.Item2.Values.Length == 1)
                    &&
                    (condition.Item2.Values[0] == null)
                )
                {
                    switch (condition.Item2.Operator)
                    {
                    case ScanOperator.Equal:
                        scanFilter.AddCondition(condition.Item1, ScanOperator.IsNull );
                    break;
                    case ScanOperator.NotEqual:
                        scanFilter.AddCondition(condition.Item1, ScanOperator.IsNotNull);
                    break;
                    default:
                        throw new InvalidOperationException(string.Format("You cannot use {0} operator with null value", condition.Item2.Operator));
                    }
                }
                else
                {
                    scanFilter.AddCondition(condition.Item1, condition.Item2.Operator, condition.Item2.Values);
                }
            }

            return scanFilter;
        }
Exemplo n.º 29
0
 /// <summary>
 /// Constructs a DocumentBatchGet instance for a specific table.
 /// </summary>
 /// <param name="targetTable">Table to get items from.</param>
 public DocumentBatchGet(Table targetTable)
 {
     TargetTable = targetTable;
     Keys = new List<Key>();
 }
 public DynamoDBS3PublisherSettings(Table configTable)
     : base(configTable)
 {
 }
Exemplo n.º 31
0
        private Table(IAmazonDynamoDB ddbClient, string tableName, Table.DynamoDBConsumer consumer, DynamoDBEntryConversion conversion)
        {
#if (WIN_RT || WINDOWS_PHONE || AWSSDK_UNITY)
            DDBClient = ddbClient as AmazonDynamoDBClient;
#else
            DDBClient = ddbClient;
#endif
            TableInfoCache = SdkCache.GetCache<string, TableDescription>(ddbClient, TableInfoCacheIdentifier, StringComparer.Ordinal);
            LoggerInstance = Logger.GetLogger(typeof(SdkCache));

            TableConsumer = consumer;
            TableName = tableName;
            Conversion = conversion;
            ClearTableData();
        }
        /// <summary>
        /// Tries to make up a batch get operation for translation result
        /// </summary>
        internal static DocumentBatchGet GetBatchGetOperationForTable(this TranslationResult translationResult, Table tableDefinition)
        {
            var conditions = translationResult.Conditions;

            // if there's a range key in the table
            if (tableDefinition.RangeKeys.Any())
            {
                // HashKey should be exactly specified
                Primitive hashKeyValue;
                if (!conditions.TryGetValueForKey(tableDefinition.HashKeys[0], out hashKeyValue))
                {
                    return null;
                }
                if (hashKeyValue == null)
                {
                    throw new NotSupportedException("Hash key value should not be null");
                }

                return GetBatchGetOperationForSearchConditions(tableDefinition, conditions.ExcludeField(tableDefinition.HashKeys[0]), tableDefinition.RangeKeys.First(), hashKeyValue);
            }
            else
            {
                return GetBatchGetOperationForSearchConditions(tableDefinition, conditions, tableDefinition.HashKeys.First(), null);
            }
        }
Exemplo n.º 33
0
 internal Table Copy(Table.DynamoDBConsumer newConsumer)
 {
     return new Table(this.DDBClient, this.TableName, newConsumer, this.Conversion)
     {
         keyNames = this.keyNames,
         Keys = this.Keys,
         RangeKeys = this.RangeKeys,
         HashKeys = this.HashKeys,
         Conversion = this.Conversion                
     };
 }
Exemplo n.º 34
0
 private static async Task InsertData(Table table, string id, string body)
 {
     await table.PutItemAsync(new Document(new Dictionary<string, DynamoDBEntry>
     {
         ["Id"] = new Primitive(id),
         ["Body"] = new Primitive(body)
     }));
 }
Exemplo n.º 35
0
        private Table(IAmazonDynamoDB ddbClient, string tableName, Table.DynamoDBConsumer consumer, DynamoDBEntryConversion conversion)
        {
#if (WIN_RT || WINDOWS_PHONE)
            DDBClient = ddbClient as AmazonDynamoDBClient;
#else
            DDBClient = ddbClient;
#endif

            TableConsumer = consumer;
            TableName = tableName;
            Keys = new Dictionary<string, KeyDescription>();
            HashKeys = new List<string>();
            RangeKeys = new List<string>();
            LocalSecondaryIndexes = new Dictionary<string, LocalSecondaryIndexDescription>();
            LocalSecondaryIndexNames = new List<string>();
            GlobalSecondaryIndexes = new Dictionary<string, GlobalSecondaryIndexDescription>();
            GlobalSecondaryIndexNames = new List<string>();
            Attributes = new List<AttributeDefinition>();
            Conversion = conversion;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Gets the DynamoDB table
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        private async Task <DynamoDbTable> TableWithName(string tableName)
        {
            var hashKeyName  = TableConfigProvider.GetTableHashKeyName(tableName);
            var rangeKeyName = TableConfigProvider.GetTableRangeKeyName(tableName);

            Logger.Debug("Checking if table '{0}' exists in DynamoDB...", tableName);

            try
            {
                if (!DynamoDbTable.TryLoadTable(DynamoDb, tableName, out var table))
                {
                    // if we failed to load the table, this is basically a retry that will throw an exception.
                    // The expectation is that this will expose whatever error caused the TryLoadTable method
                    // to return false, but if for some reason it happens to succed on retry, that also works.
                    if (!TableConfigProvider.CreateIfNotExists)
                    {
                        return(DynamoDbTable.LoadTable(DynamoDb, tableName));
                    }
                    //throw new Exception($"Table {tableName} does not exist in DynamoDB.");

                    Logger.Info("Table '{0}' does not exist in DynamoDB. Creating it now...", tableName);

                    var createResp =
                        await DynamoDb.CreateTableAsync(tableName,
                                                        new List <KeySchemaElement>
                    {
                        new KeySchemaElement
                        {
                            AttributeName = hashKeyName,
                            KeyType       = KeyType.HASH
                        },
                        new KeySchemaElement
                        {
                            AttributeName = rangeKeyName,
                            KeyType       = KeyType.RANGE
                        }
                    },
                                                        new List <AttributeDefinition>
                    {
                        new AttributeDefinition
                        {
                            AttributeName = hashKeyName,
                            AttributeType = ScalarAttributeType.S
                        },
                        new AttributeDefinition
                        {
                            AttributeName = rangeKeyName,
                            AttributeType = ScalarAttributeType.S
                        }
                    },
                                                        new ProvisionedThroughput(1, 1));

                    if (createResp.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"Failed to create table '{tableName}' in DynamoDB. Response code is {createResp.HttpStatusCode}.");
                    }

                    Logger.Info("Successfully created DynamoDB table '{0}'.", tableName);

                    table = DynamoDbTable.LoadTable(DynamoDb, tableName);
                }

                return(table);
            }
            catch (Exception exception)
            {
                Logger.Error($"An error occurred loading the DynamoDB table for type {tableName}.", exception);
                throw;
            }
        }
Exemplo n.º 37
0
 /// <summary>
 /// Converts filter to a map of conditions
 /// </summary>
 /// <param name="table">Table to use for converting .NET values to DynamoDB values.</param>
 /// <returns>Map from attribute name to condition</returns>
 public Dictionary <string, Condition> ToConditions(Table table)
 {
     return(ToConditions(table.Conversion, table.StoreAsEpoch));
 }
Exemplo n.º 38
0
        private async Task<string> ReadData(Table table, string id)
        {
            Document doc = await table.GetItemAsync(new Primitive(id));

            var body = doc["Body"];
            return body;
        }
Exemplo n.º 39
0
 internal Table Copy(Table.DynamoDBConsumer newConsumer)
 {
     return new Table(this.DDBClient, this.TableName, newConsumer, this.Conversion)
     {
         KeyNames = this.KeyNames,
         Keys = this.Keys,
         RangeKeys = this.RangeKeys,
         HashKeys = this.HashKeys,
         Conversion = this.Conversion,
         Attributes = this.Attributes,
         GlobalSecondaryIndexes = this.GlobalSecondaryIndexes,
         GlobalSecondaryIndexNames = this.GlobalSecondaryIndexNames,
         LocalSecondaryIndexes = this.LocalSecondaryIndexes,
         LocalSecondaryIndexNames = this.LocalSecondaryIndexNames,
         ContainsCachedData = this.ContainsCachedData
     };
 }
        /// <summary>
        /// Tries to make up a batch get operation from SearchConditions
        /// </summary>
        private static DocumentBatchGet GetBatchGetOperationForSearchConditions(Table tableDefinition, SearchConditions conditions, string keyFieldName, Primitive hashKeyValue)
        {
            // there should be only one IN operator for key field
            if
            (!(
                (conditions.Count == 1)
                &&
                (conditions.Keys.First() == keyFieldName)
            ))
            {
                return null;
            }

            var conditionList = conditions.Values.First();
            if
            (!(
                (conditionList.Count == 1)
                &&
                (conditionList.First().Operator == ScanOperator.In)
            ))
            {
                return null;
            }

            var result = tableDefinition.CreateBatchGet();
            foreach (var value in conditionList.First().Values)
            {
                if (hashKeyValue == null)
                {
                    result.AddKey((Primitive)value);
                }
                else
                {
                    result.AddKey(hashKeyValue, (Primitive)value);
                }
            }
            return result;
        }
Exemplo n.º 41
0
        public async Task AddNewItem(string tableName, JArray item)
        {
            var      tableRepo = new TableRepo(new AmazonDynamoDBClient());
            Document tableAttr = await tableRepo.GetTableAttr(tableName);

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

            if (tableAttr != null)
            {
                var c = tableAttr["attr"].AsDocument().GetAttributeNames();
                foreach (var c1 in c)
                {
                    attribute.Add(c1);
                    var t = tableAttr["attr"].AsDocument()[c1].AsDocument()["type"];
                    var k = tableAttr["attr"].AsDocument()[c1].AsDocument()["key"];
                    type.Add(t);
                    key.Add(k);
                }
            }
            List <Models.Attribute> attr = new List <Models.Attribute> {
            };

            for (int i = 0; i < attribute.Count; i++)
            {
                attr.Add(new Models.Attribute {
                    attrName = attribute[i], type = type[i], key = key[i]
                });
            }
            Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(dynamoDB, tableName);
            var  itm  = new Document();
            bool flag = false;

            foreach (var value in item)
            {
                if (attribute.Contains(value["key"].ToString()) is true)
                {
                    switch (type[attribute.IndexOf(value["key"].ToString())])
                    {
                    case "N":
                        itm[value["key"].ToString()] = (float)value["value"];
                        break;

                    case "B":
                        byte[]       byteArray = Encoding.ASCII.GetBytes(value["value"].ToString());
                        MemoryStream stream    = new MemoryStream(byteArray);
                        itm[value["key"].ToString()] = stream;
                        break;

                    default:
                        itm[value["key"].ToString()] = value["value"].ToString();
                        break;
                    }
                }
                else
                {
                    flag = true;
                    attribute.Add(value["key"].ToString());
                    if (IsNumeric(value["value"].ToString()) is true)
                    {
                        itm[value["key"].ToString()] = (float)value["value"];
                        type.Add("N");
                        attr.Add(new Models.Attribute {
                            attrName = value["key"].ToString(), type = "N", key = "n"
                        });
                    }
                    else
                    {
                        itm[value["key"].ToString()] = value["value"].ToString();
                        type.Add("S");
                        attr.Add(new Models.Attribute {
                            attrName = value["key"].ToString(), type = "S", key = "n"
                        });
                    }
                }
            }
            await table.PutItemAsync(itm);

            if (flag is true)
            {
                var ar  = JArray.FromObject(attr);
                var obj = new JObject {
                    new JProperty("attr", ar)
                };
                await tableRepo.UpdateAttributeAndType(tableName, obj);
            }
        }
 public DynamoDBApiSettings(Table configTable)
     : base(configTable)
 {
 }
        private void SetupTable()
        {
            try
            {
                this._table = Table.LoadTable(this._ddbClient, this._tableName, DynamoDBEntryConversion.V1);
            }
            catch (ResourceNotFoundException) { }

            if (this._table == null)
            {
                if (this._createIfNotExist)
                    this._table = CreateTable();
                else
                    throw new AmazonDynamoDBException(string.Format("Table {0} was not found to be used to store session state and autocreate is turned off.", this._tableName));
            }
            else
            {
                ValidateTable();
            }
        }
 public DynamoDBFeedSettings(Table configTable)
     : base(configTable)
 {
 }
Exemplo n.º 45
0
 /// <summary>
 /// Creates a Table object with the specified name, using the
 /// passed-in client to load the table definition.
 /// 
 /// This method will return false if the table does not exist.
 /// </summary>
 /// <param name="ddbClient">Client to use to access DynamoDB.</param>
 /// <param name="tableName">Name of the table.</param>
 /// <param name="conversion">Conversion to use for converting .NET values to DynamoDB values.</param>
 /// <param name="table">Loaded table.</param>
 /// <returns>
 /// True if table was successfully loaded; otherwise false.
 /// </returns>
 public static bool TryLoadTable(IAmazonDynamoDB ddbClient, string tableName, DynamoDBEntryConversion conversion, out Table table)
 {
     try
     {
         table = LoadTable(ddbClient, tableName, conversion);
         return true;
     }
     catch
     {
         table = null;
         return false;
     }
 }
Exemplo n.º 46
0
 /// <summary>
 /// Creates a Table object with the specified name, using the
 /// passed-in client to load the table definition.
 /// The returned table will use the conversion specified by
 /// AWSConfigs.DynamoDBConfig.ConversionSchema
 ///
 /// This method will return false if the table does not exist.
 /// </summary>
 /// <param name="ddbClient">Client to use to access DynamoDB.</param>
 /// <param name="tableName">Name of the table.</param>
 /// <param name="table">Loaded table.</param>
 /// <returns>
 /// True if table was successfully loaded; otherwise false.
 /// </returns>
 public static bool TryLoadTable(IAmazonDynamoDB ddbClient, string tableName, out Table table)
 {
     return TryLoadTable(ddbClient, tableName, DynamoDBEntryConversion.CurrentConversion, out table);
 }
Exemplo n.º 47
-1
 internal static Table LoadTable(IAmazonDynamoDB ddbClient, string tableName, Table.DynamoDBConsumer consumer, DynamoDBEntryConversion conversion)
 {
     Table table = new Table(ddbClient, tableName, consumer, conversion);
     table.LoadTableInfo();
     return table;
 }