Esempio n. 1
0
        public static object MapType(object value, EdmType type)
        {
            switch (type.ToString())
            {
            case "Edm.Int32":
                int castedValue;
                int.TryParse(value.ToString(), out castedValue);
                return(castedValue);

            case "Edm.DateTime":
                DateTime castedDate = Convert.ToDateTime(value.ToString());
                return(castedDate);

            case "Edm.DateTimeLong":
                return(value);

                break;

            case "Edm.Boolean":
                Boolean castedBoolean = Convert.ToBoolean(value);
                return(castedBoolean);

            default:    //String
                return(value);
            }
        }
 private static void WriteJsonProperty(JsonWriter writer, string key, object value, EdmType edmType)
 {
     writer.WritePropertyName(key);
     writer.WriteStartObject();
     writer.WritePropertyName(key);
     writer.WriteValue(value);
     writer.WritePropertyName("EdmType");
     writer.WriteValue(edmType.ToString());
     writer.WriteEndObject();
 }
Esempio n. 3
0
        private void ThrowIfInvalidType(string methodName, EdmType expectedType)
        {
            if (this.currentEdmType == expectedType)
            {
                return;
            }

            throw new InvalidOperationException(
                      string.Format(
                          CultureInfo.InvariantCulture,
                          "{0} expects current type to be {1}, actual type is {2}",
                          methodName,
                          expectedType.ToString(),
                          this.currentEdmType.ToString()));
        }
        private void DataTypeTestHelper(object value, EdmType edmType, string formattedValue)
        {
            var dict = new Dictionary<string, object>
            {
                { "Foo", value }
            };

            XElement xml = DataServicesHelper.CreateDataElement(dict);

            var prop = xml.Element(null, "content").Element("m", "properties").Element("d", "Foo");

            Assert.That(prop.Attribute("m", "type").ValueOrDefault(), Is.EqualTo(edmType.ToString()));

            Assert.That(xml.Element(null, "content").Element("m", "properties").Element("d", "Foo").Value, Is.EqualTo(formattedValue));
        }
Esempio n. 5
0
        internal async Task <List <dynamic> > GetByConstructedKeyAsync(EdmType targetEntityMDType, List <EdmProperty> keyProps, object[] keyValues, string specifierTop, Boolean tracking)
        {
            var conditionStr     = new StringBuilder();
            var targetEntityName = targetEntityMDType.Name.ToString();
            var targetEntityType = Type.GetType(targetEntityMDType.ToString());

            for (int index = 0; index < keyProps.Count(); index++)
            {
                if (conditionStr.Length > 0)
                {
                    conditionStr.Append(" AND ");
                }
                conditionStr.Append($"{keyProps[index].Name.ToString()}= @p{index}");
            }
            List <dynamic> result = null;

            if (tracking)
            {
                result = await context.Set(targetEntityType).SqlQuery($"SELECT {specifierTop} * FROM dbo.{targetEntityName} WHERE {conditionStr}", keyValues).ToListAsync();
            }
            else
            {
                result = await context.Set(targetEntityType).SqlQuery($"SELECT {specifierTop} * FROM dbo.{targetEntityName} WHERE {conditionStr}", keyValues).AsNoTracking().ToListAsync();
            }
            if (result != null)
            {
                foreach (var row in result)
                {
                    if (row.GetType() != targetEntityType && row.GetType().BaseType != targetEntityType)
                    {
                        throw new ArgumentException("Wrong entity type retrieved.");
                    }
                }
            }
            return(result);
        }
        internal static void ReadAndUpdateTableEntityWithEdmTypeResolver(ITableEntity entity, Dictionary <string, string> entityAttributes, EntityReadFlags flags, Func <string, string, string, string, EdmType> propertyResolver, OperationContext ctx)
        {
            Dictionary <string, EntityProperty> entityProperties           = (flags & EntityReadFlags.Properties) > 0 ? new Dictionary <string, EntityProperty>() : null;
            Dictionary <string, EdmType>        propertyResolverDictionary = null;

            // Try to add the dictionary to the cache only if it is not a DynamicTableEntity. If DisablePropertyResolverCache is true, then just use reflection and generate dictionaries for each entity.
            if (entity.GetType() != typeof(DynamicTableEntity))
            {
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                if (!TableEntity.DisablePropertyResolverCache)
                {
                    propertyResolverDictionary = TableEntity.PropertyResolverCache.GetOrAdd(entity.GetType(), TableOperationHttpResponseParsers.CreatePropertyResolverDictionary);
                }
                else
                {
                    Logger.LogVerbose(ctx, SR.PropertyResolverCacheDisabled);
                    propertyResolverDictionary = TableOperationHttpResponseParsers.CreatePropertyResolverDictionary(entity.GetType());
                }
#else
                propertyResolverDictionary = TableOperationHttpResponseParsers.CreatePropertyResolverDictionary(entity.GetType());
#endif
            }

            if (flags > 0)
            {
                foreach (KeyValuePair <string, string> prop in entityAttributes)
                {
                    if (prop.Key == TableConstants.PartitionKey)
                    {
                        entity.PartitionKey = (string)prop.Value;
                    }
                    else if (prop.Key == TableConstants.RowKey)
                    {
                        entity.RowKey = (string)prop.Value;
                    }
                    else if (prop.Key == TableConstants.Timestamp)
                    {
                        if ((flags & EntityReadFlags.Timestamp) == 0)
                        {
                            continue;
                        }

                        entity.Timestamp = DateTime.Parse(prop.Value, CultureInfo.InvariantCulture);
                    }
                    else if ((flags & EntityReadFlags.Properties) > 0)
                    {
                        if (propertyResolver != null)
                        {
                            Logger.LogVerbose(ctx, SR.UsingUserProvidedPropertyResolver);
                            try
                            {
                                EdmType type = propertyResolver(entity.PartitionKey, entity.RowKey, prop.Key, prop.Value);
                                Logger.LogVerbose(ctx, SR.AttemptedEdmTypeForTheProperty, prop.Key, type.GetType().ToString());
                                try
                                {
                                    entityProperties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, type.GetType()));
                                }
                                catch (FormatException ex)
                                {
                                    throw new StorageException(string.Format(CultureInfo.InvariantCulture, SR.FailParseProperty, prop.Key, prop.Value, type.ToString()), ex)
                                          {
                                              IsRetryable = false
                                          };
                                }
                            }
                            catch (StorageException)
                            {
                                throw;
                            }
                            catch (Exception ex)
                            {
                                throw new StorageException(SR.PropertyResolverThrewError, ex)
                                      {
                                          IsRetryable = false
                                      };
                            }
                        }
                        else if (entity.GetType() != typeof(DynamicTableEntity))
                        {
                            EdmType edmType;
                            Logger.LogVerbose(ctx, SR.UsingDefaultPropertyResolver);

                            if (propertyResolverDictionary != null)
                            {
                                propertyResolverDictionary.TryGetValue(prop.Key, out edmType);
                                Logger.LogVerbose(ctx, SR.AttemptedEdmTypeForTheProperty, prop.Key, edmType);
                                entityProperties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, edmType));
                            }
                        }
                        else
                        {
                            Logger.LogVerbose(ctx, SR.NoPropertyResolverAvailable);
                            entityProperties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, typeof(string)));
                        }
                    }
                }

                if ((flags & EntityReadFlags.Properties) > 0)
                {
                    entity.ReadEntity(entityProperties, ctx);
                }
            }
        }
        private static void WriteTestHelper(object value, EdmType edmType, string formattedValue)
        {
            var be = BaseTestElement();
            EdmHelper.Write(be, new KeyValuePair<string, object>("Test", value));

            var element = be.Element("d", "Test");

            Assert.That(element, Is.Not.Null);
            Assert.That(element.Attribute("m", "type").Value, Is.EqualTo(edmType.ToString()));
            Assert.That(element.Value, Is.EqualTo(formattedValue));
        }
        internal static void ReadAndUpdateTableEntityWithEdmTypeResolver(ITableEntity entity, Dictionary <string, string> entityAttributes, EntityReadFlags flags, Func <string, string, string, string, EdmType> propertyResolver, OperationContext ctx)
        {
            Dictionary <string, EntityProperty> dictionary  = ((flags & EntityReadFlags.Properties) > (EntityReadFlags)0) ? new Dictionary <string, EntityProperty>() : null;
            Dictionary <string, EdmType>        dictionary2 = null;

            if (entity.GetType() != typeof(DynamicTableEntity))
            {
                if (!TableEntity.DisablePropertyResolverCache)
                {
                    dictionary2 = TableEntity.PropertyResolverCache.GetOrAdd(entity.GetType(), CreatePropertyResolverDictionary);
                }
                else
                {
                    Logger.LogVerbose(ctx, "Property resolver cache is disabled.");
                    dictionary2 = CreatePropertyResolverDictionary(entity.GetType());
                }
            }
            if (flags > (EntityReadFlags)0)
            {
                foreach (KeyValuePair <string, string> entityAttribute in entityAttributes)
                {
                    if (entityAttribute.Key == "PartitionKey")
                    {
                        entity.PartitionKey = entityAttribute.Value;
                    }
                    else if (entityAttribute.Key == "RowKey")
                    {
                        entity.RowKey = entityAttribute.Value;
                    }
                    else if (entityAttribute.Key == "Timestamp")
                    {
                        if ((flags & EntityReadFlags.Timestamp) != 0)
                        {
                            entity.Timestamp = DateTime.Parse(entityAttribute.Value, CultureInfo.InvariantCulture);
                        }
                    }
                    else if ((flags & EntityReadFlags.Properties) > (EntityReadFlags)0)
                    {
                        if (propertyResolver != null)
                        {
                            Logger.LogVerbose(ctx, "Using the property resolver provided via TableRequestOptions to deserialize the entity.");
                            try
                            {
                                EdmType edmType = propertyResolver(entity.PartitionKey, entity.RowKey, entityAttribute.Key, entityAttribute.Value);
                                Logger.LogVerbose(ctx, "Attempting to deserialize '{0}' as type '{1}'", entityAttribute.Key, edmType.GetType().ToString());
                                try
                                {
                                    dictionary.Add(entityAttribute.Key, EntityProperty.CreateEntityPropertyFromObject(entityAttribute.Value, edmType.GetType()));
                                }
                                catch (FormatException innerException)
                                {
                                    throw new StorageException(string.Format(CultureInfo.InvariantCulture, "Failed to parse property '{0}' with value '{1}' as type '{2}'", entityAttribute.Key, entityAttribute.Value, edmType.ToString()), innerException)
                                          {
                                              IsRetryable = false
                                          };
                                }
                            }
                            catch (StorageException)
                            {
                                throw;
                            }
                            catch (Exception innerException2)
                            {
                                throw new StorageException("The custom property resolver delegate threw an exception. Check the inner exception for more details.", innerException2)
                                      {
                                          IsRetryable = false
                                      };
                            }
                        }
                        else if (entity.GetType() != typeof(DynamicTableEntity))
                        {
                            Logger.LogVerbose(ctx, "Using the default property resolver to deserialize the entity.");
                            if (dictionary2 != null)
                            {
                                dictionary2.TryGetValue(entityAttribute.Key, out EdmType value);
                                Logger.LogVerbose(ctx, "Attempting to deserialize '{0}' as type '{1}'", entityAttribute.Key, value);
                                dictionary.Add(entityAttribute.Key, EntityProperty.CreateEntityPropertyFromObject(entityAttribute.Value, value));
                            }
                        }
                        else
                        {
                            Logger.LogVerbose(ctx, "No property resolver available. Deserializing the entity properties as strings.");
                            dictionary.Add(entityAttribute.Key, EntityProperty.CreateEntityPropertyFromObject(entityAttribute.Value, typeof(string)));
                        }
                    }
                }
                if ((flags & EntityReadFlags.Properties) > (EntityReadFlags)0)
                {
                    entity.ReadEntity(dictionary, ctx);
                }
            }
        }