private static async Task <HttpStatusCode> ExecuteDeleteAsync(ITransaction tx, IReliableState dictionary, EntityOperation <JToken, JToken> operation) { // Get type information. Type keyType = dictionary.GetKeyType(); Type valueType = dictionary.GetValueType(); var key = operation.Key.ToObject(keyType); Type dictionaryType = typeof(IReliableDictionary <,>).MakeGenericType(keyType, valueType); // Read the existing value. MethodInfo tryGetMethod = dictionaryType.GetMethod("TryGetValueAsync", new[] { typeof(ITransaction), keyType, typeof(LockMode) }); var tryGetTask = (Task)tryGetMethod.Invoke(dictionary, new[] { tx, key, LockMode.Update }); await tryGetTask.ConfigureAwait(false); var tryGetResult = tryGetTask.GetPropertyValue <object>("Result"); // Only update the value if it exists. if (!tryGetResult.GetPropertyValue <bool>("HasValue")) { throw new QueryException(HttpStatusCode.NotFound, "Key not found."); } // Validate the ETag. var currentValue = tryGetResult.GetPropertyValue <object>("Value"); var currentEtag = CRC64.ToCRC64(JsonConvert.SerializeObject(currentValue)).ToString(); if (currentEtag != operation.Etag) { throw new QueryException(HttpStatusCode.PreconditionFailed, "The value has changed on the server."); } // Delete from reliable dictionary. MethodInfo tryDeleteMethod = dictionaryType.GetMethod("TryRemoveAsync", new[] { typeof(ITransaction), keyType }); await((Task)tryDeleteMethod.Invoke(dictionary, new[] { tx, key })).ConfigureAwait(false); return(HttpStatusCode.OK); }
private static async Task <HttpStatusCode> ExecuteAddAsync(ITransaction tx, IReliableState dictionary, EntityOperation <JToken, JToken> operation) { // Get type information. Type keyType = dictionary.GetKeyType(); Type valueType = dictionary.GetValueType(); var key = operation.Key.ToObject(keyType); var value = operation.Value.ToObject(valueType); Type dictionaryType = typeof(IReliableDictionary <,>).MakeGenericType(keyType, valueType); // Add to reliable dictionary. MethodInfo tryAddMethod = dictionaryType.GetMethod("TryAddAsync", new[] { typeof(ITransaction), keyType, valueType }); bool success = await((Task <bool>)tryAddMethod.Invoke(dictionary, new[] { tx, key, value })).ConfigureAwait(false); if (!success) { throw new QueryException(HttpStatusCode.Conflict, "Key already exists."); } return(HttpStatusCode.OK); }