public object FromEntry(DynamoDBEntry entry)
 {
     if (DynamoDBEntryConversion.V2.TryConvertFromEntry(entry, out long dateTimeNumber))
     {
         string dateTimeString = dateTimeNumber.ToString();
         if (dateTimeString.Length != 8)
         {
             return((DateTime?)null);
         }
         return(new DateTime(int.Parse(dateTimeString.Substring(0, 4)),
                             int.Parse(dateTimeString.Substring(4, 2)),
                             int.Parse(dateTimeString.Substring(6, 2))));
     }
     else
     {
         return((DateTime?)null);
     }
 }
        /// <summary>
        /// Try to convert the DynamoDBEntry to the specified type. If it fails the method returns false.
        /// </summary>
        /// <typeparam name="TOutput"></typeparam>
        /// <param name="entry"></param>
        /// <param name="output"></param>
        /// <returns>True if successfully converted, otherwise false.</returns>
        public bool TryConvertFromEntry <TOutput>(DynamoDBEntry entry, out TOutput output)
        {
            output = default(TOutput);

            var    outputType = typeof(TOutput);
            object converted;

            if (TryConvertFromEntry(outputType, entry, out converted))
            {
                if (converted != null)
                {
                    output = (TOutput)converted;
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 3
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));
            }
        }
Exemplo n.º 4
0
        public async Task <List <UserGroup> > FindByGroupId(string groupId)
        {
            string        indexName     = "GroupId-index";
            string        attributeName = "GroupId";
            DynamoDBEntry value         = groupId;

            try
            {
                var search = Context.FromQueryAsync <UserGroup>(new QueryOperationConfig()
                {
                    IndexName = indexName,
                    Filter    = new QueryFilter(attributeName, QueryOperator.Equal, value)
                });
                return(await search.GetRemainingAsync());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 5
0
        private static void DynamoDbEntryAsString(StringBuilder sb, DynamoDBEntry entry)
        {
            var list = entry as PrimitiveList;

            if (list == null)
            {
                sb.Append(entry == null ? "NULL" : entry.AsString());
                return;
            }

            string s = list.AsListOfPrimitive().Aggregate
                       (
                string.Empty,
                (c, p) => c == string.Empty ? p.AsString() : c + "," + p.AsString()
                       );

            sb.Append("(");
            sb.Append(s);
            sb.Append(")");
        }
// ReSharper disable UnusedParameter.Local
        private CacheDynamoDbEntryWrapper(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
        {
            var primitiveList = new List <Primitive>();

            var en = info.GetEnumerator();

            while (en.MoveNext())
            {
                if (en.Name == "Primitive")
                {
                    this.Entry = ((CachePrimitiveWrapper)en.Value).Primitive;
                    return;
                }

                primitiveList.Add(((CachePrimitiveWrapper)en.Value).Primitive);
            }

            this.Entry = primitiveList;
        }
Exemplo n.º 7
0
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;

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

            if (primitive.Type != DynamoDBEntryType.String)
            {
                throw new InvalidCastException();
            }
            string xml = primitive.AsString();

            using (StringReader reader = new StringReader(xml))
            {
                return(_serializer.Deserialize(reader));
            }
        }
Exemplo n.º 8
0
        internal Key MakeKey(object hashKey, object rangeKey, ItemStorageConfig storageConfig, DynamoDBFlatConfig flatConfig)
        {
            if (storageConfig.HashKeyPropertyNames.Count != 1)
            {
                throw new InvalidOperationException("Must have one hash key defined for the table " + storageConfig.TableName);
            }

            Key key = new Key();

            string          hashKeyPropertyName = storageConfig.HashKeyPropertyNames[0];
            PropertyStorage hashKeyProperty     = storageConfig.GetPropertyStorage(hashKeyPropertyName);

            DynamoDBEntry hashKeyEntry = ValueToDynamoDBEntry(hashKeyProperty, hashKey, flatConfig);

            if (hashKeyEntry == null)
            {
                throw new InvalidOperationException("Unable to convert hash key value for property " + hashKeyPropertyName);
            }
            key[hashKeyProperty.AttributeName] = hashKeyEntry.ConvertToAttributeValue(new DynamoDBEntry.AttributeConversionConfig(flatConfig.Conversion));

            if (storageConfig.RangeKeyPropertyNames.Count > 0)
            {
                if (storageConfig.RangeKeyPropertyNames.Count != 1)
                {
                    throw new InvalidOperationException("Must have one range key defined for the table");
                }

                string          rangeKeyPropertyName = storageConfig.RangeKeyPropertyNames[0];
                PropertyStorage rangeKeyProperty     = storageConfig.GetPropertyStorage(rangeKeyPropertyName);

                DynamoDBEntry rangeKeyEntry = ValueToDynamoDBEntry(rangeKeyProperty, rangeKey, flatConfig);
                if (rangeKeyEntry == null)
                {
                    throw new InvalidOperationException("Unable to convert range key value for property " + rangeKeyPropertyName);
                }
                key[rangeKeyProperty.AttributeName] = rangeKeyEntry.ConvertToAttributeValue(new DynamoDBEntry.AttributeConversionConfig(flatConfig.Conversion));
            }

            ValidateKey(key, storageConfig);
            return(key);
        }
Exemplo n.º 9
0
        // Check if DynamoDBEntry is supported
        private static bool ShouldSave(DynamoDBEntry entry)
        {
            if (entry == null)
            {
                return(false);
            }

            var primitive     = entry as Primitive;
            var primitiveList = entry as PrimitiveList;

            if (primitive != null)
            {
                return(!string.IsNullOrEmpty(primitive.Value));
            }
            if (primitiveList != null)
            {
                return(primitiveList.Entries != null && primitiveList.Entries.Count > 0);
            }

            throw new InvalidOperationException("Unrecognized DynamoDBEntry object");
        }
        private static QueryFilter ComposeQueryFilter(object hashKeyValue, IEnumerable <QueryCondition> conditions, ItemStorageConfig storageConfig, out List <string> indexNames)
        {
            if (hashKeyValue == null)
            {
                throw new ArgumentNullException("hashKeyValue");
            }

            string        hashKeyProperty = storageConfig.HashKeyPropertyNames[0];
            DynamoDBEntry hashKeyEntry    = ValueToDynamoDBEntry(hashKeyProperty, hashKeyValue, storageConfig);

            if (hashKeyEntry == null)
            {
                throw new InvalidOperationException("Unable to convert hash key value for property " + hashKeyProperty);
            }
            string   hashAttributeName = storageConfig.GetPropertyStorage(hashKeyProperty).AttributeName;
            Document hashKey           = new Document();

            hashKey[hashAttributeName] = hashKeyEntry;

            return(ComposeQueryFilterHelper(hashKey, conditions, storageConfig, out indexNames));
        }
        public object FromEntry(DynamoDBEntry entry, Type targetType)
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            object value;

            if (TryFromEntry(entry, targetType, out value))
            {
                return(value);
            }

            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                              "Unable to convert [{0}] of type {1} to {2}", entry, entry.GetType().FullName, targetType.FullName));
        }
Exemplo n.º 12
0
        public object FromEntry(DynamoDBEntry entry)
        {
            var document = entry.AsDocument();

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

            var result = new Dictionary <string, TEntity>();

            document.Keys.ToList().ForEach(key =>
            {
                var item   = document[key].AsDocument();
                var entity = _dbContext.FromDocument <TEntity>(item);

                result.Add(key, entity);
            });

            return(result);
        }
Exemplo n.º 13
0
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;

            if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
            {
                throw new ArgumentOutOfRangeException();
            }

            string entryString = entry.AsString();

            foreach (KudosStatus status in Enum.GetValues <KudosStatus>())
            {
                if (status.ToString() == entryString)
                {
                    return(status);
                }
            }

            return(KudosStatus.Unknown);
        }
Exemplo n.º 14
0
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;

            if (primitive == null || !(primitive.Value is string) || string.IsNullOrEmpty((string)primitive.Value))
            {
                throw new ArgumentOutOfRangeException();
            }

            string[] position = ((string)primitive.Value).Split(',');

            if (position.Length != 2)
            {
                throw new ArgumentOutOfRangeException();
            }

            double lat = Convert.ToDouble(position[0]);
            double lng = Convert.ToDouble(position[1]);

            return(new Position(lat, lng));
        }
Exemplo n.º 15
0
 public static object AsType(this DynamoDBEntry entry, Type type)
 {
     if (type == stringType)
     {
         return(entry.AsString());
     }
     else if (type == intType)
     {
         return(entry.AsInt());
     }
     else if (type == boolType)
     {
         return(entry.AsBoolean());
     }
     else if (type == longType)
     {
         return(entry.AsLong());
     }
     else if (type == dateTimeType)
     {
         return(entry.AsDateTime());
     }
     else if (type == doubleType)
     {
         return(entry.AsDouble());
     }
     else if (type == floatType)
     {
         return(entry.AsSingle());
     }
     else if (type == listOfStringType)
     {
         return(entry.AsListOfString());
     }
     else if (type == listOfByteArrayType)
     {
         return(entry.AsListOfString());
     }
     return(null);
 }
        private Dictionary <CurrencyPair, decimal> ToExchangeRates(List <Document> allItems)
        {
            var exchangeRates = new Dictionary <CurrencyPair, decimal>();

            foreach (Document item in allItems)
            {
                var sourceCurrency     = string.Empty;
                var targetCurrencyJSON = string.Empty;

                foreach (string key in item.Keys)
                {
                    DynamoDBEntry dbEntry = item[key];
                    string        val     = dbEntry.ToString();

                    if (string.Equals(key, "source", StringComparison.InvariantCultureIgnoreCase))
                    {
                        sourceCurrency = val;
                    }
                    if (string.Equals(key, "target", StringComparison.InvariantCultureIgnoreCase))
                    {
                        targetCurrencyJSON = val;
                    }
                }

                var perCurrencyRates = ToModel(sourceCurrency, JsonConvert.DeserializeObject <List <KeyValue> >(targetCurrencyJSON));



                if (perCurrencyRates != null)
                {
                    exchangeRates = Merge <CurrencyPair, decimal>(new List <Dictionary <CurrencyPair, decimal> >()
                    {
                        exchangeRates, perCurrencyRates
                    });
                }
            }

            return(exchangeRates);
        }
Exemplo n.º 17
0
            public object FromEntry(DynamoDBEntry entry)
            {
                if ((entry == null) || (entry is DynamoDBNull))
                {
                    return(null);
                }

                var list       = entry.AsListOfString();
                var dictionary = new Dictionary <string, TimeSpan>();

                foreach (var record in list)
                {
                    var split = record.Split('@');

                    var key   = split[0];
                    var value = TimeSpan.Parse(split[1]);

                    dictionary.Add(key, value);
                }

                return(dictionary);
            }
Exemplo n.º 18
0
        //public async void FindMedicineWithBarcode(long barcode, string table)
        //{
        //    GetItemOperationConfig config = new GetItemOperationConfig()
        //    {
        //        AttributesToGet = new List<string>() { "Barcode" },
        //    };

        //    //  Primitive key = Medicine
        //    Table tablename = Table.LoadTable(DynamoClient, table);
        //    //  tablename.GetItemAsync(Primitive Medicine.MedicineID, Primitive sortKey, GetItemOperationConfig config)
        //    ScanFilter scanFilter = new ScanFilter();
        //    scanFilter.AddCondition("Barcode", ScanOperator.Equal, barcode);
        //    ScanOperationConfig ScanConfig = new ScanOperationConfig()
        //    {
        //        AttributesToGet = new List<string> { "MedicineID", "Barcode" },
        //        Filter = scanFilter
        //    };
        //    Search getMedicine = tablename.Scan(ScanConfig);
        //    List<Document> result = await getMedicine.GetRemainingAsync();
        //    foreach (Document item in result)
        //    {
        //        foreach (string key in item.Keys)
        //        {
        //            DynamoDBEntry dbEntry = item[key];
        //            string val = dbEntry.ToString();
        //            if (key.ToLower() == "Barcode")
        //            {
        //                List<string> barcodes = dbEntry.AsListOfString();
        //                StringBuilder valueBuilder = new StringBuilder();
        //                foreach (string code in barcodes)
        //                {
        //                    valueBuilder.Append(code).Append(", ");
        //                }
        //                val = valueBuilder.ToString();
        //            }
        //            Console.WriteLine(string.Format("Property: {0}, value: {1}", key, val));
        //        }
        //    }
        //}

        public async Task <string> FindPrescriptionForCurrentDate(string date)
        {
            ScanFilter   filter   = new ScanFilter();
            ScanOperator op       = ScanOperator.Equal;
            string       attrName = "StartDate";

            filter.AddCondition(attrName, op, date);

            Table tablename = Table.LoadTable(DynamoClient, "Prescription");

            List <Document> prescriptions = await(tablename.Scan(filter)).GetRemainingAsync();
            int             newID         = prescriptions.Count;
            string          medicineName  = "";
            string          numberOfTime  = "";
            string          returnValue   = "";

            foreach (Document item in prescriptions)
            {
                foreach (string key in item.Keys)
                {
                    if (key == "Barcode")
                    {
                        DynamoDBEntry dbEntry      = item[key];
                        string        val          = dbEntry.ToString();
                        long          barcodeValue = Convert.ToInt64(val);
                        //find medicine name
                        medicineName = await FindMedicineNameByBarcode(barcodeValue);
                    }

                    if (key == "NumberOfTime")
                    {
                        DynamoDBEntry dbEntry = item[key];
                        numberOfTime = dbEntry.ToString();
                    }
                    returnValue = medicineName + " & " + numberOfTime;
                }
            }
            return(returnValue);
        }
Exemplo n.º 19
0
        public async Task <TKey[]> GetAggregateIdsAsync(
            CancellationToken cancellationToken = default)
        {
            var scanFilter = new ScanFilter();
            //scanFilter.AddCondition("aggregateVersion", ScanOperator.Equal, 1);
            Search search = _table.Scan(scanFilter);

            var ids = new HashSet <TKey>();

            do
            {
                List <Document> documents = await search.GetNextSetAsync(cancellationToken).ConfigureAwait(false);

                foreach (Document document in documents)
                {
                    DynamoDBEntry entry = document["aggregateId"];
                    TKey          id    = Defaults.Convert <TKey>(entry);
                    ids.Add(id);
                }
            }while (!search.IsDone);

            return(ids.ToArray());
        }
Exemplo n.º 20
0
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;

            if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
            {
                throw new ArgumentOutOfRangeException();
            }

            string[] data = ((string)(primitive.Value)).Split(new string[] { " x " }, StringSplitOptions.None);
            if (data.Length != 3)
            {
                throw new ArgumentOutOfRangeException();
            }

            AuthenticationInfo complexData = new AuthenticationInfo
            {
                Password    = Convert.ToString(data[0]),
                AuthToken   = Convert.ToString(data[1]),
                TokenExpiry = Convert.ToString(data[2])
            };

            return(complexData);
        }
Exemplo n.º 21
0
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;

            if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
            {
                throw new ArgumentOutOfRangeException();
            }

            string[] data = ((string)(primitive.Value)).Split(new string[] { " x " }, StringSplitOptions.None);
            if (data.Length != 3)
            {
                throw new ArgumentOutOfRangeException();
            }

            Monitor_Video_Source complexData = new Monitor_Video_Source
            {
                DeviceType      = data[0],
                Instance        = Convert.ToInt32(data[1]),
                MonitorLocation = data[2]
            };

            return(complexData);
        }
Exemplo n.º 22
0
    public object FromEntry(DynamoDBEntry entry)
    {
        Primitive primitive = entry as Primitive;

        if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
        {
            throw new ArgumentOutOfRangeException();
        }

        string[] data = ((string)(primitive.Value)).Split(new string[] { " x " }, StringSplitOptions.None);
        if (data.Length != 3)
        {
            throw new ArgumentOutOfRangeException();
        }

        DimensionType complexData = new DimensionType
        {
            Length    = Convert.ToDecimal(data[0]),
            Height    = Convert.ToDecimal(data[1]),
            Thickness = Convert.ToDecimal(data[2])
        };

        return(complexData);
    }
 /// <summary>
 /// Asynchronously gets an audit event from its primary key
 /// </summary>
 /// <typeparam name="T">The audit event type</typeparam>
 /// <param name="hashKey">The primary key Hash portion</param>
 /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
 public async Task <T> GetEventAsync <T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey) where T : AuditEvent
 {
     return(await GetEventAsync <T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive()));
 }
 /// <summary>
 /// Gets an audit event from its primary key
 /// </summary>
 /// <typeparam name="T">The audit event type</typeparam>
 /// <param name="hashKey">The primary key Hash portion</param>
 /// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
 public T GetEvent <T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey) where T : AuditEvent
 {
     return(GetEvent <T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive()));
 }
Exemplo n.º 25
0
 /// <inheritdoc/>
 public object FromEntry(DynamoDBEntry entry)
 => Enum.Parse <TEnum>(entry.AsString());
Exemplo n.º 26
0
 public object FromEntry(DynamoDBEntry entry)
 {
     return(entry == null || entry == "" ? new DateTime() : DateTime.Parse(entry.ToString()));
 }
Exemplo n.º 27
0
 public object FromEntry(DynamoDBEntry entry)
 {
     return(new Guid(entry.AsString()));
 }
        /// <summary>
        /// Try to convert value to DynamoDBEntry. If it fails the method returns false.
        /// </summary>
        /// <typeparam name="TInput"></typeparam>
        /// <param name="value"></param>
        /// <param name="entry"></param>
        /// <returns>True if successfully converted, otherwise false.</returns>
        public bool TryConvertToEntry <TInput>(TInput value, out DynamoDBEntry entry)
        {
            var inputType = typeof(TInput);

            return(TryConvertToEntry(inputType, value, out entry));
        }
        public object FromEntry(DynamoDBEntry entry)
        {
            string dateTimeString = entry.AsString();

            return(DateTime.Parse(dateTimeString));
        }
Exemplo n.º 30
0
        private static bool TryToPrimitiveList(Type type, object value, bool canReturnPrimitive, out DynamoDBEntry output)
        {
            Type elementType;

            if (!EntityUtils.ImplementsInterface(type, typeof(ICollection <>)) ||
                !EntityUtils.IsPrimitive(elementType = type.GetGenericArguments()[0]))
            {
                output = null;
                return(false);
            }

            IEnumerable enumerable = value as IEnumerable;

            Primitive primitive;

            // Strings are collections of chars, don't treat them as collections
            if (enumerable == null || value is string)
            {
                if (canReturnPrimitive &&
                    value.GetType().IsAssignableFrom(elementType) &&
                    TryToPrimitive(elementType, value, out primitive))
                {
                    output = primitive;
                    return(true);
                }

                output = null;
                return(false);
            }

            PrimitiveList     primitiveList = new PrimitiveList();
            DynamoDBEntryType?listType      = null;

            foreach (var item in enumerable)
            {
                if (TryToPrimitive(elementType, item, out primitive))
                {
                    if (listType.HasValue && listType.Value != primitive.Type)
                    {
                        throw new InvalidOperationException("List cannot contain a mix of different types");
                    }
                    listType = primitive.Type;

                    primitiveList.Entries.Add(primitive);
                }
                else
                {
                    output = null;
                    return(false);
                }
            }
            primitiveList.Type = listType.GetValueOrDefault(DynamoDBEntryType.String);

            output = primitiveList;
            return(true);
        }