Пример #1
0
        public static void RunDocumentModelSample(AmazonDynamoDBClient client)
        {
            Console.WriteLine("Loading hints table");
            Table table = Table.LoadTable(client, "packLevels");

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

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

            }
        }
Пример #2
0
        public void FromEntryTestWrongObjectsReturnsEmptyObjects()
        {
            var          list    = CreateObjectList <SomeOtherObject>();
            DynamoDBList dbEntry = new DynamoDBList(
                list.Select(x => Document.FromJson(JsonSerializer.Serialize(x, CreateJsonOptions()))));

            var expected = new List <SomeObject>(new[]
            {
                new SomeObject(),
                new SomeObject(),
                new SomeObject(),
            });

            _sut.FromEntry(dbEntry).Should().BeEquivalentTo(expected);
        }
Пример #3
0
        /// <summary>
        /// If value implements IEnumerable{T}, converts the items to DynamoDBList
        /// This method is called after the PrimitiveList version of TryTo, so this will
        /// never work on a HashSet{T}.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="l"></param>
        /// <returns></returns>
        public override bool TryTo(object value, out DynamoDBList l)
        {
            var inputType = value.GetType();

            if (DataModel.Utils.ImplementsInterface(inputType, enumerableType))
            {
                var elementType = Utils.GetElementType(inputType);
                var entries     = Conversion.ConvertToEntries(elementType, value as IEnumerable);
                l = new DynamoDBList(entries);
                return(true);
            }

            l = null;
            return(false);
        }
Пример #4
0
        private static DynamoDBEntry SerializeField(object value, SerializationMaskType mask)
        {
            if (value == null)
            {
                return(null);
            }

            var type = value.GetType();

            if (IsPrimitive(type))
            {
                return(ValueToPrimitive(value));
            }

            if (type.GetInterfaces().Contains(typeof(IList)))
            {
                var list          = (IList)value;
                var listOfEntries = new DynamoDBList();
                foreach (var item in list)
                {
                    listOfEntries.Add(SerializeField(item, mask));
                }
                return(listOfEntries);
            }

            if (type.GetInterfaces().Contains(typeof(IDictionary)))
            {
                var dict     = (IDictionary)value;
                var dictData = new Document();
                foreach (var key in dict.Keys)
                {
                    dictData[SerializeField(key, mask)] = SerializeField(dict[key], mask);
                }
                return(dictData);
            }

            if (type.IsEnum)
            {
                return(value.ToString());
            }

            if (type.IsClass || type.IsValueType)
            {
                return(Serialize(value, mask));
            }

            throw new Exception(string.Format("Unsupported type {0}", type.Name));
        }
        /// <summary>
        /// Fills an IList with contents of DynamoDBList.
        /// </summary>
        private static object FillListFromDynamoDbList(IList list, DynamoDBList dynamoDbList, Type elementType)
        {
            // There might DynamoDBLists of primitives occur as well. And we're checking the entry type only once for better performance.
            bool?isListOfObjects = null;

            foreach (var entry in dynamoDbList.Entries)
            {
                if (isListOfObjects == null)
                {
                    isListOfObjects = entry is Document;
                }

                list.Add(isListOfObjects.Value ? ((Document)entry).ToObject(elementType) : entry.ToObject(elementType));
            }
            return(list);
        }
        /// <summary>
        /// Converts a DynamoDbList into an array of elements of elementType
        /// </summary>
        private static object FillArrayFromDynamoDbList <T>(DynamoDBList dynamoDbList, Type elementType)
        {
            bool?isListOfObjects = null;

            return(dynamoDbList.Entries
                   .Select(pr =>
            {
                if (isListOfObjects == null)
                {
                    isListOfObjects = pr is Document;
                }

                return isListOfObjects.Value ? ((Document)pr).ToObject(elementType) : pr.ToObject(elementType);
            })
                   .Cast <T>()
                   .ToArray());
        }
        public async Task UpdateReleases(IEnumerable <Release> releases)
        {
            foreach (var release in releases)
            {
                var beverages = new DynamoDBList();
                foreach (var beverage in release.Beverages)
                {
                    beverages.Add(JsonSerializer.Serialize(beverage));
                }

                var document = new Document();
                document["ReleaseDate"]       = release.ReleaseDate.ToString("yyyy-MM-dd");
                document["Group"]             = release.Group;
                document["NumberOfBeverages"] = release.NumberOfBeverages;
                document["Beverages"]         = beverages;

                await _table.PutItemAsync(document);
            }
        }
Пример #8
0
        public override bool TryTo(object value, out DynamoDBList l)
        {
            var items = value as IEnumerable;

            if (items != null)
            {
                l = new DynamoDBList();
                foreach (var item in items)
                {
                    var itemType = item.GetType();
                    var entry    = Conversion.ConvertToEntry(itemType, item);
                    l.Add(entry);
                }
                return(true);
            }

            l = null;
            return(false);
        }
Пример #9
0
        public DynamoDBEntry ToEntry(object value)
        {
            var list       = new DynamoDBList();
            var coffeeList = ((List <Coffee>)value);

            foreach (var coffee in coffeeList)
            {
                list.Add(
                    new Document(new Dictionary <string, DynamoDBEntry> {
                    { ID, coffee.Id },
                    { DESCRIPTION, coffee.Description ?? string.Empty },
                    { IMAGE, coffee?.Image ?? string.Empty },
                    { TITLE, coffee?.Title ?? string.Empty },
                })
                    );
            }

            return(list);
        }
Пример #10
0
        private bool TryFromList(Type targetType, DynamoDBList list, DynamoDBFlatConfig flatConfig, out object output)
        {
            var targetTypeWrapper = TypeFactory.GetTypeInfo(targetType);

            if ((!Utils.ImplementsInterface(targetType, typeof(ICollection <>)) &&
                 !Utils.ImplementsInterface(targetType, typeof(IList))) ||
                !Utils.CanInstantiate(targetType))
            {
                output = null;
                return(false);
            }

            var   elementType       = targetTypeWrapper.GetGenericArguments()[0];
            var   collection        = Utils.Instantiate(targetType);
            IList ilist             = collection as IList;
            bool  useIListInterface = ilist != null;
            var   propertyStorage   = new SimplePropertyStorage(elementType);

            MethodInfo collectionAdd = null;

            if (!useIListInterface)
            {
                collectionAdd = targetTypeWrapper.GetMethod("Add");
            }

            foreach (DynamoDBEntry entry in list.Entries)
            {
                var item = FromDynamoDBEntry(propertyStorage, entry, flatConfig);

                if (useIListInterface)
                {
                    ilist.Add(item);
                }
                else
                {
                    collectionAdd.Invoke(collection, new object[] { item });
                }
            }

            output = collection;
            return(true);
        }
Пример #11
0
        // DynamoDBEntry <--> Object
        private object FromDynamoDBEntry(SimplePropertyStorage propertyStorage, DynamoDBEntry entry, DynamoDBFlatConfig flatConfig)
        {
            var converter = propertyStorage.Converter;

            if (converter != null)
            {
                return(converter.FromEntry(entry));
            }

            var conversion = flatConfig.Conversion;
            var targetType = propertyStorage.MemberType;

            if (conversion.HasConverter(targetType))
            {
                return(conversion.ConvertFromEntry(targetType, entry));
            }
            else
            {
                object   output;
                Document document = entry as Document;
                if (document != null)
                {
                    if (TryFromMap(targetType, document, flatConfig, out output))
                    {
                        return(output);
                    }

                    return(DeserializeFromDocument(document, targetType, flatConfig));
                }

                DynamoDBList list = entry as DynamoDBList;
                if (list != null &&
                    TryFromList(targetType, list, flatConfig, out output))
                {
                    return(output);
                }

                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                  "Unable to convert DynamoDB entry [{0}] of type {1} to property {2} of type {3}",
                                                                  entry, entry.GetType().FullName, propertyStorage.PropertyName, propertyStorage.MemberType.FullName));
            }
        }
Пример #12
0
        private bool TryToList(object value, Type type, DynamoDBFlatConfig flatConfig, out DynamoDBList output)
        {
            var typeWrapper = TypeFactory.GetTypeInfo(type);

            if (!Utils.ImplementsInterface(type, typeof(ICollection <>)))
            {
                output = null;
                return(false);
            }

            IEnumerable enumerable = value as IEnumerable;

            // Strings are collections of chars, don't treat them as collections
            if (enumerable == null || value is string)
            {
                output = null;
                return(false);
            }

            Type elementType = typeWrapper.GetGenericArguments()[0];
            SimplePropertyStorage propertyStorage = new SimplePropertyStorage(elementType);

            output = new DynamoDBList();
            foreach (var item in enumerable)
            {
                DynamoDBEntry entry;
                if (item == null)
                {
                    entry = DynamoDBNull.Null;
                }
                else
                {
                    entry = ToDynamoDBEntry(propertyStorage, item, flatConfig);
                }

                output.Add(entry);
            }
            return(true);
        }
Пример #13
0
        private static void TestBinaryDecoding()
        {
            // Test data
            var data                = "Hello world!";
            var binaryData          = Encoding.UTF8.GetBytes(data);
            var base64Data          = Convert.ToBase64String(binaryData);
            var ms                  = new MemoryStream(binaryData);
            var binaryDataPrimitive = new Primitive(ms);

            var data2                = "Big River";
            var binaryData2          = Encoding.UTF8.GetBytes(data2);
            var base64Data2          = Convert.ToBase64String(binaryData2);
            var ms2                  = new MemoryStream(binaryData2);
            var binaryData2Primitive = new Primitive(binaryData2);

            var binarySet = new PrimitiveList(DynamoDBEntryType.Binary);

            binarySet.Add(binaryDataPrimitive);
            binarySet.Add(binaryData2Primitive);
            var binarySetContents = binarySet.AsListOfByteArray();

            var binaryList = new DynamoDBList();

            binaryList.Add(binaryDataPrimitive);
            binaryList.Add(binaryData2Primitive);
            var binaryListContents = binaryList.AsListOfByteArray();

            var base64Set = new PrimitiveList(DynamoDBEntryType.String);

            base64Set.Add(base64Data);
            base64Set.Add(base64Data2);
            var base64SetContents = new List <string> {
                base64Data, base64Data2
            };

            // Populate document
            var doc = new Document();

            doc["Binary"]       = binaryData;
            doc["BinarySet"]    = binarySet;
            doc["BinaryList"]   = binaryList;
            doc["BinaryString"] = base64Data;

            // Convert document to JSON
            var json       = doc.ToJson();
            var prettyJson = doc.ToJsonPretty();

            CompareJson(json, prettyJson);

            // Back to a document
            var rt = Document.FromJson(json);

            // Test to make sure binary data is strings
            var p = rt["Binary"] as Primitive;

            Assert.IsNotNull(p);
            Assert.AreEqual(DynamoDBEntryType.String, p.Type);

            p = rt["BinaryString"] as Primitive;
            Assert.IsNotNull(p);
            Assert.AreEqual(DynamoDBEntryType.String, p.Type);

            var s = rt["BinarySet"] as DynamoDBList;

            Assert.IsNotNull(s);
            Assert.AreEqual(2, s.Entries.Count);
            for (int i = 0; i < s.Entries.Count; i++)
            {
                var entry = s.Entries[i];
                Assert.IsTrue(entry is Primitive);
                Assert.AreEqual(DynamoDBEntryType.String, (entry as Primitive).Type);
                Assert.AreEqual(base64SetContents[i], entry.AsString());
            }

            var l = rt["BinaryList"] as DynamoDBList;

            Assert.IsNotNull(l);
            Assert.AreEqual(2, l.Entries.Count);
            for (int i = 0; i < l.Entries.Count; i++)
            {
                var entry = l.Entries[i];
                Assert.IsTrue(entry is Primitive);
                Assert.AreEqual(DynamoDBEntryType.String, (entry as Primitive).Type);
                Assert.AreEqual(base64SetContents[i], entry.AsString());
            }

            // Add a base64 set (SS, with base64 items)
            rt["BinarySet2"] = base64Set;

            // Decode all base64-encoded attributes
            rt.DecodeBase64Attributes("Binary", "BinarySet", "BinaryList", "BinarySet2", "BinaryString", "FakeAttribute");

            // Test to make sure attributes are binary
            var dp = rt["Binary"] as Primitive;

            Assert.IsNotNull(dp);
            Assert.AreEqual(DynamoDBEntryType.Binary, dp.Type);
            CollectionAssert.AreEqual(binaryData, dp.AsByteArray());

            dp = rt["BinaryString"] as Primitive;
            Assert.IsNotNull(dp);
            Assert.AreEqual(DynamoDBEntryType.Binary, dp.Type);
            CollectionAssert.AreEqual(binaryData, dp.AsByteArray());

            var dl = rt["BinaryList"] as DynamoDBList;

            Assert.IsNotNull(dl);
            Assert.AreEqual(2, dl.Entries.Count);
            for (int i = 0; i < dl.Entries.Count; i++)
            {
                var entry = dl.Entries[i];
                Assert.IsTrue(entry is Primitive);
                Assert.AreEqual(DynamoDBEntryType.Binary, (entry as Primitive).Type);
                CollectionAssert.AreEqual(entry.AsByteArray(), binarySetContents[i]);
            }

            dl = rt["BinarySet"] as DynamoDBList;
            Assert.IsNotNull(dl);
            Assert.AreEqual(2, dl.Entries.Count);
            for (int i = 0; i < dl.Entries.Count; i++)
            {
                var entry = dl.Entries[i];
                Assert.IsTrue(entry is Primitive);
                Assert.AreEqual(DynamoDBEntryType.Binary, (entry as Primitive).Type);
                CollectionAssert.AreEqual(entry.AsByteArray(), binarySetContents[i]);
            }

            var ds = rt["BinarySet2"] as PrimitiveList;

            Assert.IsNotNull(ds);
            Assert.AreEqual(2, ds.Entries.Count);
            Assert.AreEqual(DynamoDBEntryType.Binary, ds.Type);
            for (int i = 0; i < ds.Entries.Count; i++)
            {
                var entry = ds.Entries[i];
                Assert.IsTrue(entry is Primitive);
                Assert.AreEqual(DynamoDBEntryType.Binary, (entry as Primitive).Type);
                CollectionAssert.AreEqual(entry.AsByteArray(), binarySetContents[i]);
            }

            rt["FakeBinaryData"] = "this is fake";
            AssertExtensions.ExpectException(() => rt.DecodeBase64Attributes("FakeBinaryData"));
        }
Пример #14
0
 public override bool TryFrom(DynamoDBList l, Type targetType, out object result)
 {
     var elementType = DataModel.Utils.GetElementType(targetType);
     var entries = l.Entries;
     return EntriesToCollection(targetType, elementType, entries, out result);
 }
        /// <summary>
        /// Fills an ICollection[T] with contents of DynamoDBList.
        /// </summary>
        private static object FillCollectionFromDynamoDbList <T>(ICollection <T> coll, DynamoDBList dynamoDbList, Type elementType)
        {
            bool?isListOfObjects = null;

            foreach (var entry in dynamoDbList.Entries)
            {
                if (isListOfObjects == null)
                {
                    isListOfObjects = entry is Document;
                }

                var item = isListOfObjects.Value ? ((Document)entry).ToObject(elementType) : entry.ToObject(elementType);
                coll.Add((T)item);
            }
            return(coll);
        }
Пример #16
0
        public override bool TryTo(object value, out DynamoDBList l)
        {
            var items = value as IEnumerable;
            if (items != null)
            {
                l = new DynamoDBList();
                foreach(var item in items)
                {
                    var itemType = item.GetType();
                    var entry = Conversion.ConvertToEntry(itemType, item);
                    l.Add(entry);
                }
                return true;
            }

            l = null;
            return false;
        }
Пример #17
0
        // Returns a DynamoDB entry for the given JSON data
        private static DynamoDBEntry ToEntry(JsonData data, DynamoDBEntryConversion conversion)
        {
            if (data == null)
                return new DynamoDBNull();

            if (data.IsObject)
            {
                var document = new Document();
                foreach (var propertyName in data.PropertyNames)
                {
                    var nestedData = data[propertyName];
                    var entry = ToEntry(nestedData, conversion);
                    document[propertyName] = entry;
                }
                return document;
            }

            if (data.IsArray)
            {
                var list = new DynamoDBList();
                for(int i=0;i<data.Count;i++)
                {
                    var item = data[i];
                    var entry = ToEntry(item, conversion);
                    list.Add(entry);
                }
                return list;
            }

            if (data.IsBoolean)
                return new UnconvertedDynamoDBEntry((bool)data).Convert(conversion);

            if (data.IsDouble)
                return new UnconvertedDynamoDBEntry((double)data).Convert(conversion);

            if (data.IsInt)
                return new UnconvertedDynamoDBEntry((int)data).Convert(conversion);

            if (data.IsLong)
                return new UnconvertedDynamoDBEntry((long)data).Convert(conversion);

            if (data.IsString)
                return new UnconvertedDynamoDBEntry((string)data).Convert(conversion);

            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                "Unable to convert JSON data of type {0} to DynamoDB type.", data.GetJsonType()));
        }
Пример #18
0
        // Attempts to decode a particular DynamoDBEntry.
        // May throw exceptions, in particular if the data is not base64 encoded
        private static bool TryDecodeBase64(DynamoDBEntry entry, out DynamoDBEntry decodedEntry)
        {
            decodedEntry = null;

            // Convert string primitive (S) to binary primitive (B)
            var primitive = entry as Primitive;
            if (primitive != null && primitive.Type == DynamoDBEntryType.String)
            {
                // Decode the contents
                var base64 = primitive.Value as string;
                byte[] bytes;
                if (!TryDecodeBase64(base64, out bytes))
                    return false;

                // Store as binary primitive (B)
                decodedEntry = new Primitive(bytes);
                return true;
            }

            // Convert string set (SS) to binary set (BS)
            var primitiveList = entry as PrimitiveList;
            if (primitiveList != null && primitiveList.Type == DynamoDBEntryType.String)
            {
                var decodedList = new PrimitiveList(DynamoDBEntryType.Binary);
                foreach(var item in primitiveList.Entries)
                {
                    // Attempt to decode
                    DynamoDBEntry decodedItem;
                    if (!TryDecodeBase64(item, out decodedItem))
                        return false;

                    // The decoded item must be a Primitive
                    Primitive decodedPrimitive = decodedItem as Primitive;
                    if (decodedPrimitive == null)
                        return false;

                    decodedList.Add(decodedPrimitive);
                }

                decodedEntry = decodedList;
                return true;
            }

            // In a given list (L), convert every string primitive (S) to binary primitive (B)
            // Non-strings and strings that cannot be converted will be left as-is
            var dynamoDBList = entry as DynamoDBList;
            if (dynamoDBList != null)
            {
                var decodedList = new DynamoDBList();
                foreach(var item in dynamoDBList.Entries)
                {
                    DynamoDBEntry decodedItem;
                    if (!TryDecodeBase64(item, out decodedItem))
                    {
                        // if decoding could not succeed, store same item
                        decodedItem = item;
                    }

                    decodedList.Add(decodedItem);
                }

                decodedEntry = decodedList;
                return true;
            }

            return false;
        }
Пример #19
0
        private void TestHashTable(Table hashTable, DynamoDBEntryConversion conversion)
        {
            // Put an item
            Document doc = new Document();

            doc["Id"]       = 1;
            doc["Product"]  = "CloudSpotter";
            doc["Company"]  = "CloudsAreGrate";
            doc["IsPublic"] = true;
            doc["Price"]    = 1200;
            doc["Tags"]     = new HashSet <string> {
                "Prod", "1.0"
            };
            doc["Aliases"] = new List <string> {
                "CS", "Magic"
            };
            doc["Developers"] = new List <Document>
            {
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Alan" },
                    { "Age", 29 }
                }),
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Franco" },
                    { "Age", 32 }
                })
            };
            doc["Garbage"] = "asdf";
            Assert.AreEqual("asdf", doc["Garbage"].AsString());
            hashTable.PutItem(doc);

            // Get the item by hash key
            Document retrieved = hashTable.GetItem(1);

            Assert.IsFalse(AreValuesEqual(doc, retrieved));
            var convertedDoc = doc.ForceConversion(conversion);

            Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved));

            // Get the item by document
            retrieved = hashTable.GetItem(doc);
            // Verify retrieved document
            Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved, conversion));
            var tagsRetrieved = retrieved["Tags"];

            Assert.IsTrue(tagsRetrieved is PrimitiveList);
            Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count);
            // Test bool storage for different conversions
            var isPublicRetrieved = retrieved["IsPublic"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual("1", isPublicRetrieved.AsPrimitive().Value as string);
            }
            else
            {
                Assert.IsTrue(isPublicRetrieved is DynamoDBBool);
            }
            // Test HashSet<string> storage for different conversions
            var aliasesRetrieved = retrieved["Aliases"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual(2, aliasesRetrieved.AsPrimitiveList().Entries.Count);
            }
            else
            {
                Assert.AreEqual(2, aliasesRetrieved.AsDynamoDBList().Entries.Count);
            }
            List <Document> developers = retrieved["Developers"].AsListOfDocument();

            Assert.AreEqual(2, developers.Count);
            AssertExtensions.ExpectException(() => aliasesRetrieved.AsListOfDocument(), typeof(InvalidCastException));

            // Update the item
            doc["Tags"] = new List <string> {
                "Prod", "1.0", "2.0"
            };
            doc["Developers"] = new DynamoDBList(new List <DynamoDBEntry>
            {
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Alan" },
                    { "Age", 29 }
                })
            });
            // Delete the Garbage attribute
            doc["Garbage"] = null;
            Assert.IsNull(doc["Garbage"].AsString());
            hashTable.UpdateItem(doc);
            retrieved = hashTable.GetItem(1);
            Assert.IsFalse(AreValuesEqual(doc, retrieved, conversion));
            doc.Remove("Garbage");
            Assert.IsTrue(AreValuesEqual(doc, retrieved, conversion));
            developers = retrieved["Developers"].AsListOfDocument();
            Assert.AreEqual(1, developers.Count);

            // Create new, circularly-referencing item
            Document doc2 = doc.ForceConversion(conversion);

            doc2["Id"]       = doc2["Id"].AsInt() + 1;
            doc2["Price"]    = 94;
            doc2["Tags"]     = null;
            doc2["IsPublic"] = false;
            doc2["Parent"]   = doc2;
            AssertExtensions.ExpectException(() => hashTable.UpdateItem(doc2));
            // Remove circular reference and save new item
            doc2.Remove("Parent");
            hashTable.UpdateItem(doc2);

            // Scan the hash-key table
            var items = hashTable.Scan(new ScanFilter()).GetRemaining();

            Assert.AreEqual(2, items.Count);

            // Scan by pages
            var search = hashTable.Scan(new ScanOperationConfig {
                Limit = 1
            });

            items.Clear();
            while (!search.IsDone)
            {
                var set = search.GetNextSet();
                items.AddRange(set);
            }
            Assert.AreEqual(2, items.Count);

            // Query against GlobalIndex
            var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate");

            queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100);
            search = hashTable.Query(new QueryOperationConfig
            {
                IndexName = "GlobalIndex",
                Filter    = queryFilter
            });
            items = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Scan for specific tag
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0");
            search = hashTable.Scan(scanFilter);
            items  = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Delete the item by hash key
            hashTable.DeleteItem(1);
            Assert.IsNull(hashTable.GetItem(1));

            // Delete the item by document
            hashTable.DeleteItem(doc2);
            Assert.IsNull(hashTable.GetItem(doc2));

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);

            // Batch-put items
            var batchWrite = hashTable.CreateBatchWrite();

            batchWrite.AddDocumentToPut(doc);
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();

            // Batch-get items
            var batchGet = hashTable.CreateBatchGet();

            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(2, batchGet.Results.Count);

            // Batch-delete items
            batchWrite = hashTable.CreateBatchWrite();
            batchWrite.AddItemToDelete(doc);
            batchWrite.AddKeyToDelete(2);
            batchWrite.Execute();

            // Batch-get non-existent items
            batchGet = hashTable.CreateBatchGet();
            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(0, batchGet.Results.Count);

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);
        }
 public virtual bool TryTo(object value, out DynamoDBList l)
 {
     l = null;
     return(false);
 }
Пример #21
0
        /// <summary>
        /// If value implements IEnumerable{T}, converts the items to DynamoDBList
        /// This method is called after the PrimitiveList version of TryTo, so this will
        /// never work on a HashSet{T}.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="l"></param>
        /// <returns></returns>
        public override bool TryTo(object value, out DynamoDBList l)
        {
            var inputType = value.GetType();

            if (DataModel.Utils.ImplementsInterface(inputType, enumerableType))
            {
                var elementType = DataModel.Utils.GetElementType(inputType);
                var entries = Conversion.ConvertToEntries(elementType, value as IEnumerable);
                l = new DynamoDBList(entries);
                return true;
            }

            l = null;
            return false;
        }
 public virtual bool TryFrom(DynamoDBList l, Type targetType, out object result)
 {
     result = null;
     return(false);
 }
Пример #23
0
        public static Document ToDocument <T>(T tObject, bool removeNulls = true, bool removeZeros = true)
        {
            var dictionary = tObject.GetType()
                             .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .ToDictionary(prop => prop.Name, prop => prop.GetValue(tObject, null));

            if (removeNulls)
            {
                dictionary = dictionary.Where(x => x.Value != null).ToDictionary(y => y.Key, y => y.Value);
            }

            var document = new Document();

            foreach (var entry in dictionary)
            {
                if (entry.Value == null)
                {
                    continue;
                }

                var type = entry.Value.GetType();

                if (type == typeof(List <Object>))
                {
                    Console.WriteLine("WE HAVE A LIST"); // Look away. Nothing to see here. Please stop reading. Come on.... DO you feel better for reading this? Was it worth your time? Really have nothing better to do?                                                          COME ON. IT's Done. Nothing left. I promise. Not like there is any gold at the end of this comment. Please go on. We both have better things to be doing right now. I could be writting alot of usefull code, but instead we are both stuck reading this comment. Hope your happy now. I am not stopping before you are! Wonder if anyone is still reading. Not like anything usefull is coming later. Wonder how many skipped the first part. Please just go on with your day / night. THIS AINT OVER TO I SAY IT'S OVER!
                }

                if (type == typeof(string))
                {
                    document.Add(entry.Key, (string)entry.Value);
                }
                else if (type == typeof(int) || type == typeof(int?))
                {
                    if (removeZeros)
                    {
                        if ((int)entry.Value != 0)
                        {
                            document.Add(entry.Key, (int)entry.Value);
                        }
                    }
                    else
                    {
                        document.Add(entry.Key, (int)entry.Value);
                    }
                }
                else if (type == typeof(bool) || type == typeof(bool?))
                {
                    document.Add(entry.Key, new DynamoDBBool((bool)entry.Value));
                }
                else if (type == typeof(List <string>))
                {
                    document.Add(entry.Key, (List <string>)entry.Value);
                }
                else if (type == typeof(List <int>))
                {
                    var dynamoDBList = new DynamoDBList(new List <DynamoDBEntry>());

                    foreach (var i in (List <int>)entry.Value)
                    {
                        dynamoDBList.Add(i);
                    }
                    document.Add(entry.Key, dynamoDBList);
                }
                else if (type == typeof(DateTime))
                {
                    document.Add(entry.Key, (DateTime)entry.Value);
                }
                else if (type == typeof(float) || type == typeof(float?))
                {
                    if (removeZeros)
                    {
                        if ((float)entry.Value != 0)
                        {
                            document.Add(entry.Key, (float)entry.Value);
                        }
                    }
                    else
                    {
                        document.Add(entry.Key, (float)entry.Value);
                    }
                }
                else if (type == typeof(double) || type == typeof(double?))
                {
                    if (removeZeros)
                    {
                        if ((double)entry.Value != 0)
                        {
                            document.Add(entry.Key, (double)entry.Value);
                        }
                    }
                    else
                    {
                        document.Add(entry.Key, (double)entry.Value);
                    }
                }
                else if (type == typeof(uint?) || type == typeof(uint?))
                {
                    if (removeZeros)
                    {
                        if ((uint)entry.Value != 0)
                        {
                            document.Add(entry.Key, (uint)entry.Value);
                        }
                    }
                    else
                    {
                        document.Add(entry.Key, (uint)entry.Value);
                    }
                }
                else if (type.BaseType != null && type.BaseType.IsAssignableFrom(typeof(T)))
                {
                    if (type.BaseType == typeof(Object) && type.Name == "List`1") // If is list
                    {
                        var dynamoDbList = new DynamoDBList(new List <Document>());
                        var genericList  = entry.Value as IEnumerable;
                        if (genericList != null)
                        {
                            foreach (var test in genericList)
                            {
                                var dbEntry = test;
                                if (dbEntry != null)
                                {
                                    dynamoDbList.Add(AWSDocumentConverter.ToDocument(dbEntry, removeNulls));
                                }
                            }
                        }

                        document.Add(entry.Key, dynamoDbList);
                    }
                    else if (type.BaseType != null)
                    {
                        var docEntry = entry.Value;
                        if (docEntry != null)
                        {
                            document.Add(entry.Key, AWSDocumentConverter.ToDocument(docEntry, removeNulls));
                        }
                    }
                }
            }
            return(document);
        }