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); }
// 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)); } }
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; } }
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; }
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)); } }
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); }
// 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)); }
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); }
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); }
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)); }
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); }
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); }
//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); }
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()); }
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); }
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); }
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())); }
/// <inheritdoc/> public object FromEntry(DynamoDBEntry entry) => Enum.Parse <TEnum>(entry.AsString());
public object FromEntry(DynamoDBEntry entry) { return(entry == null || entry == "" ? new DateTime() : DateTime.Parse(entry.ToString())); }
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)); }
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); }