public static void VerifyEdmTypesEquivalent(LegacyMetadata.EdmType legacyEdmType, EdmType edmType)
        {
            Assert.Equal(legacyEdmType.FullName, edmType.FullName);

            Assert.True(
                (legacyEdmType.BaseType == null && edmType.BaseType == null) ||
                legacyEdmType.BaseType.FullName == edmType.BaseType.FullName);
            Assert.Equal(legacyEdmType.BuiltInTypeKind.ToString(), edmType.BuiltInTypeKind.ToString());
            Assert.Equal(
                ((LegacyMetadata.DataSpace)typeof(LegacyMetadata.EdmType)
                                               .GetProperty("DataSpace", BindingFlags.Instance | BindingFlags.NonPublic)
                                               .GetValue(legacyEdmType)).ToString(),
                ((DataSpace)typeof(EdmType)
                                .GetProperty("DataSpace", BindingFlags.Instance | BindingFlags.NonPublic)
                                .GetValue(edmType)).ToString());

            if (edmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveTypeKind)
            {
                var prmitiveEdmType = (PrimitiveType)edmType;
                var legacyPrmitiveEdmType = (LegacyMetadata.PrimitiveType)legacyEdmType;

                // EF5 geospatial types should be converted to EF6 spatial types
                var expectedClrEquivalentType =
                    legacyPrmitiveEdmType.ClrEquivalentType == typeof(LegacySpatial.DbGeography)
                        ? typeof(DbGeography)
                        : legacyPrmitiveEdmType.ClrEquivalentType == typeof(LegacySpatial.DbGeometry)
                              ? typeof(DbGeometry)
                              : legacyPrmitiveEdmType.ClrEquivalentType;

                Assert.Equal(expectedClrEquivalentType, prmitiveEdmType.ClrEquivalentType);
                Assert.Equal(legacyPrmitiveEdmType.GetEdmPrimitiveType().FullName, prmitiveEdmType.GetEdmPrimitiveType().FullName);
            }
        }
Ejemplo n.º 2
0
        protected override PrepareMappingRes PrepareMapping(string typeFullName, EdmType edmItem)
        {
            // find existing parent storageEntitySet
            // thp derived types does not have storageEntitySet
            EntitySet storageEntitySet;
            EdmType baseEdmType = edmItem;
            while (!EntityContainer.TryGetEntitySetByName(baseEdmType.Name, false, out storageEntitySet))
            {
                if (baseEdmType.BaseType == null)
                {
                    break;
                }
                baseEdmType = baseEdmType.BaseType;
            }

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

            var isRoot = baseEdmType == edmItem;
            if (!isRoot)
            {
                var parent = _entityMaps.Values.FirstOrDefault(x => x.EdmType == baseEdmType);
                // parent table has not been mapped yet
                if (parent == null)
                {
                    throw new ParentNotMappedYetException();
                }
            }

            string tableName = GetTableName(storageEntitySet);

            return new PrepareMappingRes { TableName = tableName, StorageEntitySet = storageEntitySet, IsRoot = isRoot, BaseEdmType = baseEdmType };
        }
        /// <summary>
        ///     Returns all the FacetDescriptions for a particular type
        /// </summary>
        /// <param name="type"> the type to return FacetDescriptions for. </param>
        /// <returns> The FacetDescriptions for the type given. </returns>
        public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType type)
        {
            Debug.Assert(type is PrimitiveType, "EdmProviderManifest.GetFacetDescriptions(): Argument is not a PrimitiveType");

            InitializeFacetDescriptions();

            // Some types may not have facets, so just try to get them, if there aren't any, just return an empty list
            ReadOnlyCollection<FacetDescription> collection = null;
            if (_facetDescriptions.TryGetValue(type as PrimitiveType, out collection))
            {
                return collection;
            }
            return Helper.EmptyFacetDescriptionEnumerable;
        }
        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));
        }
 /// <summary>
 /// Gets a function providing a transformation from the specified <paramref name="type"/> to the hashed value represented as <see cref="ulong"/>.
 /// </summary>
 public static Func<object, ulong> GetHashingTransformer(EdmType type)
 {
     switch (type)
     {
         case EdmType.String:
             return TransformString;
         case EdmType.Binary:
             return TransformBytes;
         case EdmType.DateTime:
             return TransformDateTime;
         case EdmType.Double:
             return TransformDouble;
         case EdmType.Guid:
             return TransformGuid;
         case EdmType.Int32:
             return TransformInt;
         case EdmType.Int64:
             return TransformLong;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the EntityProperty class given the
 /// EdmType of the property (the value must be set by a public
 /// constructor).
 /// </summary>
 private EntityProperty(EdmType propertyType)
 {
     this.PropertyType = propertyType;
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Is the given type an Enity Type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal static bool IsEntityType(EdmType type)
 {
     return(BuiltInTypeKind.EntityType == type.BuiltInTypeKind);
 }
        public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType edmType)
        {
            Debug.Assert(edmType != null, "edmType != null");
            Debug.Assert(edmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType, "Primitive type expected.");
            Debug.Assert(
                (DataSpace)typeof(EdmType)
                               .GetProperty("DataSpace", BindingFlags.Instance | BindingFlags.NonPublic)
                               .GetValue(edmType) == DataSpace.SSpace,
                "Expected SSpace type.");

            try
            {
                var legacyStoreType = _legacyStoreTypes.Single(t => t.FullName == edmType.FullName);

                return new ReadOnlyCollection<FacetDescription>(
                    _wrappedProviderManifest
                        .GetFacetDescriptions(legacyStoreType)
                        .Select(
                            legacyFacetDescription =>
                            (FacetDescription)FacetDescriptionConstructor.Invoke(
                                BindingFlags.CreateInstance,
                                null,
                                new[]
                                    {
                                        legacyFacetDescription.FacetName,
                                        FromLegacyPrimitiveType((LegacyMetadata.PrimitiveType)legacyFacetDescription.FacetType),
                                        legacyFacetDescription.MinValue,
                                        legacyFacetDescription.MaxValue,
                                        legacyFacetDescription.DefaultValue == TypeUsageHelper.LegacyVariableValue
                                            ? TypeUsageHelper.VariableValue
                                            : legacyFacetDescription.DefaultValue,
                                        legacyFacetDescription.IsConstant,
                                        legacyStoreType.FullName
                                    },
                                CultureInfo.InvariantCulture))
                        .ToList());
            }
            catch (SystemData.ProviderIncompatibleException exception)
            {
                throw new ProviderIncompatibleException(exception.Message, exception.InnerException);
            }
        }
Ejemplo n.º 9
0
 private void AddDbQueryKeys()
 {
     EdmType.AddKeys(EdmType.StructuralProperties());
 }
 protected override void Visit(EdmType edmType)
 {
     base.Visit(edmType);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Generates a property filter condition string for the <see cref="EdmType"/> value, formatted as the specified <see cref="EdmType"/>.
        /// </summary>
        /// <param name="propertyName">A string containing the name of the property to compare.</param>
        /// <param name="operation">A string containing the comparison operator to use.</param>
        /// <param name="givenValue">A string containing the value to compare with the property.</param>
        /// <param name="edmType">The <see cref="EdmType"/> to format the value as.</param>
        /// <returns>A string containing the formatted filter condition.</returns>
        private static string GenerateFilterCondition(string propertyName, string operation, string givenValue, EdmType edmType)
        {
            string valueOperand = null;

            if (edmType == EdmType.Boolean || edmType == EdmType.Double || edmType == EdmType.Int32)
            {
                valueOperand = givenValue;
            }
            else if (edmType == EdmType.Int64)
            {
                valueOperand = string.Format("{0}L", givenValue);
            }
            else if (edmType == EdmType.DateTime)
            {
                valueOperand = string.Format("datetime'{0}'", givenValue);
            }
            else if (edmType == EdmType.Guid)
            {
                valueOperand = string.Format("guid'{0}'", givenValue);
            }
            else if (edmType == EdmType.Binary)
            {
                valueOperand = string.Format("X'{0}'", givenValue);
            }
            else
            {
                valueOperand = string.Format("'{0}'", givenValue);
            }

            return string.Format("{0} {1} {2}", propertyName, operation, valueOperand);
        }
        private static T ReadAndResolveWithEdmTypeResolver <T>(Dictionary <string, string> entityAttributes, Func <string, string, DateTimeOffset, IDictionary <string, EntityProperty>, string, T> resolver, Func <string, string, string, string, EdmType> propertyResolver, string etag, Type type, OperationContext ctx, bool disablePropertyResolverCache)
        {
            string         pk = null;
            string         rk = null;
            DateTimeOffset ts = new DateTimeOffset();
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>();
            Dictionary <string, EdmType>        propertyResolverDictionary = null;

            if (type != null)
            {
#if WINDOWS_DESKTOP && !WINDOWS_PHONE
                if (!disablePropertyResolverCache)
                {
                    propertyResolverDictionary = TableEntity.PropertyResolverCache.GetOrAdd(type, TableOperationHttpResponseParsers.CreatePropertyResolverDictionary);
                }
                else
                {
                    propertyResolverDictionary = TableOperationHttpResponseParsers.CreatePropertyResolverDictionary(type);
                }
#else
                propertyResolverDictionary = TableOperationHttpResponseParsers.CreatePropertyResolverDictionary(type);
#endif
            }

            foreach (KeyValuePair <string, string> prop in entityAttributes)
            {
                if (prop.Key == TableConstants.PartitionKey)
                {
                    pk = (string)prop.Value;
                }
                else if (prop.Key == TableConstants.RowKey)
                {
                    rk = (string)prop.Value;
                }
                else if (prop.Key == TableConstants.Timestamp)
                {
                    ts = DateTimeOffset.Parse(prop.Value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
                    if (etag == null)
                    {
                        etag = GetETagFromTimestamp(prop.Value);
                    }
                }
                else
                {
                    if (propertyResolver != null)
                    {
                        Logger.LogVerbose(ctx, SR.UsingUserProvidedPropertyResolver);
                        try
                        {
                            EdmType edmType = propertyResolver(pk, rk, prop.Key, prop.Value);
                            Logger.LogVerbose(ctx, SR.AttemptedEdmTypeForTheProperty, prop.Key, edmType);
                            try
                            {
                                properties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, edmType));
                            }
                            catch (FormatException ex)
                            {
                                throw new StorageException(string.Format(CultureInfo.InvariantCulture, SR.FailParseProperty, prop.Key, prop.Value, edmType), ex)
                                      {
                                          IsRetryable = false
                                      };
                            }
                        }
                        catch (StorageException)
                        {
                            throw;
                        }
                        catch (Exception ex)
                        {
                            throw new StorageException(SR.PropertyResolverThrewError, ex)
                                  {
                                      IsRetryable = false
                                  };
                        }
                    }
                    else if (type != null)
                    {
                        Logger.LogVerbose(ctx, SR.UsingDefaultPropertyResolver);
                        EdmType edmType;
                        if (propertyResolverDictionary != null)
                        {
                            propertyResolverDictionary.TryGetValue(prop.Key, out edmType);
                            Logger.LogVerbose(ctx, SR.AttemptedEdmTypeForTheProperty, prop.Key, edmType);
                            properties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, edmType));
                        }
                    }
                    else
                    {
                        Logger.LogVerbose(ctx, SR.NoPropertyResolverAvailable);
                        properties.Add(prop.Key, EntityProperty.CreateEntityPropertyFromObject(prop.Value, typeof(string)));
                    }
                }
            }

            return(resolver(pk, rk, ts, properties, etag));
        }
Ejemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="typeFullName"></param>
        /// <param name="edmItem"></param>
        public EntityMap MapEntity(string typeFullName, EdmType edmItem)
        {
            var identity = edmItem.FullName;

            if (!TphData.ContainsKey(identity))
            {
                return(null);
            }

            var temp = PrepareMapping(typeFullName, edmItem);

            if (temp == null)
            {
                return(null);
            }
            var storageEntitySet = temp.StorageEntitySet;
            var tableName        = temp.TableName;
            var isRoot           = temp.IsRoot;
            var baseEdmType      = temp.BaseEdmType;

            string schema = (string)storageEntitySet.MetadataProperties["Schema"].Value;

            var entityMap = RegEntity(typeFullName, tableName, schema);

            entityMap.IsRoot        = isRoot;
            entityMap.EdmType       = edmItem;
            entityMap.ParentEdmType = entityMap.IsRoot ? null : baseEdmType;

            _pks[tableName] = storageEntitySet.ElementType.KeyMembers.Select(x => x.Name).ToArray();

            entityMap.IsTph = TphData[identity].Discriminators.Count > 0;

            string prefix = null;
            int    i      = 0;

            var propertiesToMap = GetPropertiesToMap(entityMap, storageEntitySet.ElementType.Properties);

            foreach (var edmProperty in propertiesToMap)
            {
                MapProperty(entityMap, edmProperty, ref i, ref prefix);
            }

            // create navigation properties
            foreach (var navigationProperty in TphData[identity].NavProperties)
            {
                var associationType = navigationProperty.RelationshipType as AssociationType;
                if (associationType == null || associationType.ReferentialConstraints.Count == 0)
                {
                    continue;
                }

                var to = associationType.ReferentialConstraints[0].ToProperties[0];

                var propertyMap = entityMap.Properties.Cast <PropertyMap>()
                                  .FirstOrDefault(x => x.EdmMember == to);

                if (propertyMap != null)
                {
                    propertyMap.NavigationPropertyName = navigationProperty.Name;

                    if (entityMap.Prop(navigationProperty.Name) == null)
                    {
                        var navigationPropertyMap = entityMap.MapProperty(navigationProperty.Name, propertyMap.ColumnName);
                        navigationPropertyMap.IsNavigationProperty   = true;
                        navigationPropertyMap.ForeignKeyPropertyName = propertyMap.PropertyName;
                        navigationPropertyMap.ForeignKey             = propertyMap;

                        propertyMap.NavigationProperty = navigationPropertyMap;
                    }
                }
            }

            // create discriminators
            foreach (var discriminator in TphData[identity].Discriminators)
            {
                var propertyMap = entityMap.MapDiscriminator(discriminator.Key, discriminator.Value);
                entityMap.AddDiscriminator(propertyMap);
            }

            return(entityMap);
        }
Ejemplo n.º 14
0
 // requires: workspace
 // Determines CSpace EntityType associated with the type argument T
 internal static bool TryDetermineCSpaceModelType <T>(MetadataWorkspace workspace, out EdmType modelEdmType)
 {
     return(TryDetermineCSpaceModelType(typeof(T), workspace, out modelEdmType));
 }
Ejemplo n.º 15
0
        private static bool TryMatchType(EntityProperty rhs, EdmType edmType, out object matchedValue, out string error)
        {
            error = null;
            switch (edmType)
            {
            case EdmType.String:
                if (rhs.PropertyType == EdmType.String)
                {
                    matchedValue = rhs.StringValue;
                    return(true);
                }
                break;

            case EdmType.Binary:
                if (rhs.PropertyType == EdmType.Binary)
                {
                    matchedValue = rhs.BinaryValue;
                    return(true);
                }
                break;

            case EdmType.Boolean:
                if (rhs.PropertyType == EdmType.Boolean)
                {
                    matchedValue = rhs.BooleanValue;
                    return(true);
                }
                break;

            case EdmType.DateTime:
                if (rhs.PropertyType == EdmType.DateTime)
                {
                    matchedValue = rhs.DateTime;
                    return(true);
                }
                break;

            case EdmType.Double:
                if (rhs.PropertyType == EdmType.Double)
                {
                    matchedValue = rhs.DoubleValue;
                    return(true);
                }

                if (rhs.PropertyType == EdmType.Int32)
                {
                    matchedValue = (double?)rhs.Int32Value;
                    return(true);
                }

                if (rhs.PropertyType == EdmType.Int64)
                {
                    matchedValue = (double?)rhs.Int64Value;
                    return(true);
                }
                break;

            case EdmType.Guid:
                if (rhs.PropertyType == EdmType.Guid)
                {
                    matchedValue = rhs.GuidValue;
                    return(true);
                }
                break;

            case EdmType.Int32:
                if (rhs.PropertyType == EdmType.Int32)
                {
                    matchedValue = rhs.Int32Value;
                    return(true);
                }
                break;

            case EdmType.Int64:
                if (rhs.PropertyType == EdmType.Int64)
                {
                    matchedValue = rhs.Int64Value;
                    return(true);
                }
                if (rhs.PropertyType == EdmType.Int32)
                {
                    matchedValue = (long?)rhs.Int32Value;
                    return(true);
                }
                break;

            default:
                error        = "Unknown type conversion.";
                matchedValue = null;
                return(false);
            }

            error        = $"Cannot convert {rhs.PropertyType} to {edmType}";
            matchedValue = null;
            return(false);
        }
Ejemplo n.º 16
0
 protected abstract PrepareMappingRes PrepareMapping(string typeFullName, EdmType edmitem);
Ejemplo n.º 17
0
        internal void RemoveIsOfType(EdmType type)
        {
            DebugCheck.NotNull(type);

            m_isOfEntityTypes.Remove(type.FullName);
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Add a Type to the list of Is-Of types that this mapping is valid for
        /// </summary>
        internal void AddIsOfType(EdmType type)
        {
            DebugCheck.NotNull(type);

            m_isOfEntityTypes.Add(type.FullName, type);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Add a Type to the list of types that this mapping is valid for
        /// </summary>
        public void AddType(EdmType type)
        {
            Check.NotNull(type, "type");

            m_entityTypes.Add(type.FullName, type);
        }
Ejemplo n.º 20
0
        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));
        }
Ejemplo n.º 21
0
        internal static bool TryDetermineCSpaceModelType(Type type, MetadataWorkspace workspace, out EdmType modelEdmType)
        {
            Debug.Assert(null != workspace);
            Type nonNullabelType = TypeSystem.GetNonNullableType(type);

            // make sure the workspace knows about T
            workspace.ImplicitLoadAssemblyForType(nonNullabelType, System.Reflection.Assembly.GetCallingAssembly());
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
            EdmType objectEdmType;

            if (objectItemCollection.TryGetItem <EdmType>(nonNullabelType.FullName, out objectEdmType))
            {
                Map map;
                if (workspace.TryGetMap(objectEdmType, DataSpace.OCSpace, out map))
                {
                    ObjectTypeMapping objectMapping = (ObjectTypeMapping)map;
                    modelEdmType = objectMapping.EdmType;
                    return(true);
                }
            }
            modelEdmType = null;
            return(false);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Initialises a new instance of the <see cref="ConstantNode" /> class.
 /// </summary>
 /// <param name="edmType">The <see cref="EdmType"/> of the value.</param>
 /// <param name="literalText">The literal text.</param>
 protected ConstantNode(EdmType edmType, string literalText)
 {
     EdmType     = edmType;
     LiteralText = literalText;
 }
Ejemplo n.º 23
0
        // effects: Returns true if member's type has a discrete domain (i.e. is bolean type)
        // Note: enums don't have discrete domains as we allow domain of the underlying type.
        internal static bool HasDiscreteDomain(EdmType edmType)
        {
            var primitiveType = edmType as PrimitiveType;

            return(primitiveType != null && primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Boolean);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Is the given type a primitive type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal static bool IsPrimitiveType(EdmType type)
 {
     return(BuiltInTypeKind.PrimitiveType == type.BuiltInTypeKind);
 }
Ejemplo n.º 25
0
 // effects: Returns this type and its sub types - for refs, gets the
 // type and subtypes of the entity type
 internal static IEnumerable <EdmType> GetTypeAndSubtypesOf(EdmType type, MetadataWorkspace workspace, bool includeAbstractTypes)
 {
     return(GetTypeAndSubtypesOf(type, workspace.GetItemCollection(DataSpace.CSpace), includeAbstractTypes));
 }
        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);
                }
            }
        }
Ejemplo n.º 27
0
 // Metadata 'Visitor' methods
 protected virtual EdmType VisitType(EdmType type)
 {
     return(type);
 }
Ejemplo n.º 28
0
 internal void ValidateAndSetTypeUsage(EdmType edmType)
 {
     _typeUsageBuilder.ValidateAndSetTypeUsage(edmType, false);
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the EntityProperty class given the
 /// EdmType of the property (the value must be set by a public
 /// constructor).
 /// </summary>
 private EntityProperty(EdmType propertyType)
 {
     this.PropertyType = propertyType;
 }
 /// <summary>
 /// Returns the list of facet descriptions for the specified Entity Data Model (EDM) type.
 /// </summary>
 /// <param name="edmType">An <see cref="T:System:Data.Metadata.Edm.EdmType"/> for which the facet descriptions are to be retrieved.</param>
 /// <returns>
 /// A collection of type <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1"/> that contains the list of facet descriptions for the specified Entity Data Model (EDM) type.
 /// </returns>
 public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType edmType)
 {
     return this.wrappedProviderManifest.GetFacetDescriptions(edmType);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Is the given type a collection type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal static bool IsCollectionType(EdmType type)
 {
     return(type.BuiltInTypeKind == BuiltInTypeKind.CollectionType);
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Is the given type a row type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal static bool IsRowType(EdmType type)
 {
     return(BuiltInTypeKind.RowType == type.BuiltInTypeKind);
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Get the edm type, if the type is not a edm type throw a exception.
 /// </summary>
 private Type GetType(EdmType edmType)
 {
     switch (edmType)
     {
         case EdmType.Binary :
             return typeof(byte[]);
         case EdmType.Boolean :
             return typeof(bool);
         case EdmType.DateTime :
             return typeof(DateTime);
         case EdmType.Double :
             return typeof(double);
         case EdmType.Guid :
             return typeof(Guid);
         case EdmType.Int32 :
             return typeof(int);
         case EdmType.Int64 :
             return typeof(long);
         case EdmType.String :
             return typeof(string);
         default: throw new TypeLoadException(string.Format("not supported edmType:{0}" ,edmType));
     }
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Gets the C# type equivalent of an entity data model (Edm) type.
 /// </summary>
 /// <param name="type">The Edm type.</param>
 /// <returns>The C# type.</returns>
 private static string GetType(EdmType type)
 {
     switch (type)
     {
         case EdmType.Binary:
             return "byte[]";
         case EdmType.Boolean:
             return "bool?";
         case EdmType.DateTime:
             return "DateTime?";
         case EdmType.Double:
             return "double?";
         case EdmType.Guid:
             return "Guid?";
         case EdmType.Int32:
             return "int?";
         case EdmType.Int64:
             return "long?";
         case EdmType.String:
             return "string";
         default:
             throw new NotSupportedException(string.Format(Exceptions.TypeNotSupported, type));
     }
 }
Ejemplo n.º 35
0
 protected abstract PrepareMappingRes PrepareMapping(string typeFullName, EdmType edmitem);
Ejemplo n.º 36
0
 /// <summary>
 /// Ensures that the given type matches the type of this entity
 /// property; throws an exception if the types do not match.
 /// </summary>
 private void EnforceType(EdmType requestedType)
 {
     if (this.PropertyType != requestedType)
     {
         throw new InvalidOperationException(string.Format(
             "Cannot return {0} type for a {1} typed property.",
             requestedType,
             this.PropertyType));
     }
 }
        /// <summary>
        /// Generates a property filter condition string for the <see cref="EdmType"/> value, formatted as the specified <see cref="EdmType"/>.
        /// </summary>
        /// <param name="propertyName">A string containing the name of the property to compare.</param>
        /// <param name="operation">A string containing the comparison operator to use.</param>
        /// <param name="givenValue">A string containing the value to compare with the property.</param>
        /// <param name="edmType">The <see cref="EdmType"/> to format the value as.</param>
        /// <returns>A string containing the formatted filter condition.</returns>
        private static string GenerateFilterCondition(string propertyName, string operation, string givenValue, EdmType edmType)
        {
            string valueOperand = null;

            if (edmType == EdmType.Boolean || edmType == EdmType.Double || edmType == EdmType.Int32)
            {
                valueOperand = givenValue;
            }
            else if (edmType == EdmType.Int64)
            {
                valueOperand = string.Format(CultureInfo.InvariantCulture, "{0}L", givenValue);
            }
            else if (edmType == EdmType.DateTime)
            {
                valueOperand = string.Format(CultureInfo.InvariantCulture, "datetime'{0}'", givenValue);
            }
            else if (edmType == EdmType.Guid)
            {
                valueOperand = string.Format(CultureInfo.InvariantCulture, "guid'{0}'", givenValue);
            }
            else if (edmType == EdmType.Binary)
            {
                valueOperand = string.Format(CultureInfo.InvariantCulture, "X'{0}'", givenValue);
            }
            else
            {
                // OData readers expect single quote to be escaped in a param value.
                valueOperand = string.Format(CultureInfo.InvariantCulture, "'{0}'", givenValue.Replace("'", "''"));
            }

            return string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", propertyName, operation, valueOperand);
        }
        /// <summary>
        /// Generates a property filter condition string for the <see cref="EdmType"/> value, formatted as the specified <see cref="EdmType"/>.
        /// </summary>
        /// <param name="propertyName">A string containing the name of the property to compare.</param>
        /// <param name="operation">A string containing the comparison operator to use.</param>
        /// <param name="value">A string containing the value to compare with the property.</param>
        /// <param name="edmType">The <see cref="EdmType"/> to format the value as.</param>
        /// <returns>A string containing the formatted filter condition.</returns>
        private static string GenerateFilterCondition(string propertyName, string operation, string value, EdmType edmType)
        {
            string valueOperand = null;

            if (edmType == EdmType.Boolean || edmType == EdmType.Double || edmType == EdmType.Int32 ||
                edmType == EdmType.Int64)
            {
                valueOperand = value;
            }
            else if (edmType == EdmType.DateTime)
            {
                valueOperand = string.Format("datetime'{0}'", value);
            }
            else if (edmType == EdmType.Guid)
            {
                valueOperand = string.Format("guid'{0}'", value);
            }
            else if (edmType == EdmType.Binary)
            {
                valueOperand = string.Format("X'{0}'", value);
            }
            else
            {
                valueOperand = string.Format("'{0}'", value);
            }

            return(string.Format("{0} {1} {2}", propertyName, operation, valueOperand));
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Gets a ConstantNode which represents a type in the entity data model.
 /// </summary>
 /// <param name="literalText">The literal text.</param>
 /// <param name="edmType">The type in the entity data model.</param>
 /// <returns>A ConstantNode representing a duration value.</returns>
 internal static ConstantNode <EdmType> EdmTypeNode(string literalText, EdmType edmType) => new ConstantNode <EdmType>(edmType, literalText, edmType);
Ejemplo n.º 40
0
 /// <summary>
 /// Gets the CLR type for given EDM type.
 /// </summary>
 /// <param name="edmType">Type of the EDM.</param>
 /// <returns></returns>
 private static Type UnderlyingClrType(EdmType edmType) {
     var primitiveType = edmType as PrimitiveType;
     if (primitiveType != null)
         return primitiveType.ClrEquivalentType;
     return typeof(object);
 }
 private void EnsureConfigurationIsFullyMapped(
     MemberPath currentPath,
     BoolExpression currentWhereClause,
     HashSet <FragmentQuery> outputUsedViews,
     ErrorLog errorLog)
 {
     foreach (Constant domainValue in this.GetDomain(currentPath))
     {
         if (domainValue != Constant.Undefined)
         {
             BoolExpression       memberCondition = this.CreateMemberCondition(currentPath, domainValue);
             BoolExpression       and             = BoolExpression.CreateAnd(currentWhereClause, memberCondition);
             Tile <FragmentQuery> rewriting;
             if (!this.FindRewritingAndUsedViews((IEnumerable <MemberPath>) this._keyAttributes, and, outputUsedViews, out rewriting))
             {
                 if (!ErrorPatternMatcher.FindMappingErrors(this._context, this._domainMap, this._errorLog))
                 {
                     StringBuilder  builder   = new StringBuilder();
                     string         str       = StringUtil.FormatInvariant("{0}", (object)this._extentPath);
                     BoolExpression condition = rewriting.Query.Condition;
                     condition.ExpensiveSimplify();
                     if (condition.RepresentsAllTypeConditions)
                     {
                         string viewGenExtent = Strings.ViewGen_Extent;
                         builder.AppendLine(Strings.ViewGen_Cannot_Recover_Types((object)viewGenExtent, (object)str));
                     }
                     else
                     {
                         string viewGenEntities = Strings.ViewGen_Entities;
                         builder.AppendLine(Strings.ViewGen_Cannot_Disambiguate_MultiConstant((object)viewGenEntities, (object)str));
                     }
                     RewritingValidator.EntityConfigurationToUserString(condition, builder);
                     ErrorLog.Record record = new ErrorLog.Record(ViewGenErrorCode.AmbiguousMultiConstants, builder.ToString(), (IEnumerable <LeftCellWrapper>) this._context.AllWrappersForExtent, string.Empty);
                     errorLog.AddEntry(record);
                 }
             }
             else
             {
                 TypeConstant typeConstant = domainValue as TypeConstant;
                 if (typeConstant != null)
                 {
                     EdmType                  edmType = typeConstant.EdmType;
                     List <MemberPath>        list    = QueryRewriter.GetNonConditionalScalarMembers(edmType, currentPath, this._domainMap).Union <MemberPath>(QueryRewriter.GetNonConditionalComplexMembers(edmType, currentPath, this._domainMap)).ToList <MemberPath>();
                     IEnumerable <MemberPath> notCoveredAttributes;
                     if (list.Count > 0 && !this.FindRewritingAndUsedViews((IEnumerable <MemberPath>)list, and, outputUsedViews, out rewriting, out notCoveredAttributes))
                     {
                         List <MemberPath> memberPathList = new List <MemberPath>(list.Where <MemberPath>((Func <MemberPath, bool>)(a => !a.IsPartOfKey)));
                         this.AddUnrecoverableAttributesError(notCoveredAttributes, memberCondition, errorLog);
                     }
                     else
                     {
                         foreach (MemberPath conditionalComplexMember in QueryRewriter.GetConditionalComplexMembers(edmType, currentPath, this._domainMap))
                         {
                             this.EnsureConfigurationIsFullyMapped(conditionalComplexMember, and, outputUsedViews, errorLog);
                         }
                         foreach (MemberPath conditionalScalarMember in QueryRewriter.GetConditionalScalarMembers(edmType, currentPath, this._domainMap))
                         {
                             this.EnsureConfigurationIsFullyMapped(conditionalScalarMember, and, outputUsedViews, errorLog);
                         }
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="typeFullName"></param>
        /// <param name="edmItem"></param>
        public EntityMap MapEntity(string typeFullName, EdmType edmItem)
        {
            var identity = edmItem.FullName;
            if (!TphData.ContainsKey(identity))
            {
                return null;
            }

            var temp = PrepareMapping(typeFullName, edmItem);
            if (temp == null)
            {
                return null;
            }
            var storageEntitySet = temp.StorageEntitySet;
            var tableName = temp.TableName;
            var isRoot = temp.IsRoot;
            var baseEdmType = temp.BaseEdmType;

            string schema = (string)storageEntitySet.MetadataProperties["Schema"].Value;

            var entityMap = RegEntity(typeFullName, tableName, schema);
            entityMap.IsRoot = isRoot;
            entityMap.EdmType = edmItem;
            entityMap.ParentEdmType = entityMap.IsRoot ? null : baseEdmType;

            _pks[tableName] = storageEntitySet.ElementType.KeyMembers.Select(x => x.Name).ToArray();

            entityMap.IsTph = TphData[identity].Discriminators.Count > 0;

            string prefix = null;
            int i = 0;

            var propertiesToMap = GetPropertiesToMap(entityMap, storageEntitySet.ElementType.Properties);
            foreach (var edmProperty in propertiesToMap)
            {
                MapProperty(entityMap, edmProperty, ref i, ref prefix);
            }

            // create navigation properties
            foreach (var navigationProperty in TphData[identity].NavProperties)
            {
                var associationType = navigationProperty.RelationshipType as AssociationType;
                if (associationType == null || associationType.ReferentialConstraints.Count == 0)
                {
                    continue;
                }

                var to = associationType.ReferentialConstraints[0].ToProperties[0];

                var propertyMap = entityMap.Properties.Cast<PropertyMap>()
                    .FirstOrDefault(x => x.EdmMember == to);

                if (propertyMap != null)
                {
                    propertyMap.NavigationPropertyName = navigationProperty.Name;

                    if (entityMap.Prop(navigationProperty.Name) == null)
                    {
                        var navigationPropertyMap = entityMap.MapProperty(navigationProperty.Name, propertyMap.ColumnName);
                        navigationPropertyMap.IsNavigationProperty = true;
                        navigationPropertyMap.ForeignKeyPropertyName = propertyMap.PropertyName;
                        navigationPropertyMap.ForeignKey = propertyMap;

                        propertyMap.NavigationProperty = navigationPropertyMap;
                    }
                }
            }

            // create discriminators
            foreach (var discriminator in TphData[identity].Discriminators)
            {
                var propertyMap = entityMap.MapDiscriminator(discriminator.Key, discriminator.Value);
                entityMap.AddDiscriminator(propertyMap);
            }

            return entityMap;
        }
Ejemplo n.º 43
0
 internal static IEnumerable <ComplexType> ToHierarchy(this ComplexType edmType)
 {
     return(EdmType.SafeTraverseHierarchy(edmType));
 }
 /// <summary>
 /// Initialises a new instance of the <see cref="ConstantNode" /> class.
 /// </summary>
 /// <param name="edmType">The <see cref="EdmType"/> of the value.</param>
 /// <param name="literalText">The literal text.</param>
 /// <param name="value">The value.</param>
 private ConstantNode(EdmType edmType, string literalText, object value)
 {
     this.EdmType = edmType;
     this.LiteralText = literalText;
     this.Value = value;
 }
Ejemplo n.º 45
0
 internal static bool Equals(EdmType x, EdmType y)
 {
     return(x.Identity.Equals(y.Identity));
 }
Ejemplo n.º 46
0
        private MappingBase GetOCMapForTransientType(EdmType edmType, DataSpace typeSpace)
        {
            Debug.Assert(
                typeSpace == DataSpace.CSpace || typeSpace == DataSpace.OSpace || Helper.IsRowType(edmType) ||
                Helper.IsCollectionType(edmType));
            EdmType clrType = null;
            EdmType cdmType = null;
            var     index   = -1;

            if (typeSpace != DataSpace.OSpace)
            {
                if (_edmTypeIndexes.TryGetValue(edmType.Identity, out index))
                {
                    return((MappingBase)this[index]);
                }
                else
                {
                    cdmType = edmType;
                    clrType = ConvertCSpaceToOSpaceType(edmType);
                }
            }
            else if (typeSpace == DataSpace.OSpace)
            {
                if (_clrTypeIndexes.TryGetValue(edmType.Identity, out index))
                {
                    return((MappingBase)this[index]);
                }
                else
                {
                    clrType = edmType;
                    cdmType = ConvertOSpaceToCSpaceType(clrType);
                }
            }

            var typeMapping = new ObjectTypeMapping(clrType, cdmType);

            if (BuiltInTypeKind.RowType
                == edmType.BuiltInTypeKind)
            {
                var clrRowType = (RowType)clrType;
                var edmRowType = (RowType)cdmType;

                Debug.Assert(clrRowType.Properties.Count == edmRowType.Properties.Count, "Property count mismatch");
                for (var idx = 0; idx < clrRowType.Properties.Count; idx++)
                {
                    typeMapping.AddMemberMap(new ObjectPropertyMapping(edmRowType.Properties[idx], clrRowType.Properties[idx]));
                }
            }
            if ((!_edmTypeIndexes.ContainsKey(cdmType.Identity)) &&
                (!_clrTypeIndexes.ContainsKey(clrType.Identity)))
            {
                lock (_lock)
                {
                    var clrTypeIndexes = new Dictionary <string, int>(_clrTypeIndexes);
                    var edmTypeIndexes = new Dictionary <string, int>(_edmTypeIndexes);

                    typeMapping = AddInternalMapping(typeMapping, clrTypeIndexes, edmTypeIndexes);

                    _clrTypeIndexes = clrTypeIndexes;
                    _edmTypeIndexes = edmTypeIndexes;
                }
            }
            return(typeMapping);
        }
Ejemplo n.º 47
0
        // <summary>
        // Search for a Mapping metadata with the specified type key.
        // </summary>
        // <param name="identity"> identity of the type </param>
        // <param name="typeSpace"> The dataspace that the type for which map needs to be returned belongs to </param>
        // <param name="ignoreCase"> true for case-insensitive lookup </param>
        // <returns> Returns false if no match found. </returns>
        internal override bool TryGetMap(string identity, DataSpace typeSpace, bool ignoreCase, out MappingBase map)
        {
            EdmType cdmType = null;
            EdmType clrType = null;

            if (typeSpace == DataSpace.CSpace)
            {
                if (ignoreCase)
                {
                    // Get the correct casing of the identity first if we are asked to do ignore case
                    if (!_edmCollection.TryGetItem(identity, true, out cdmType))
                    {
                        map = null;
                        return(false);
                    }

                    identity = cdmType.Identity;
                }

                int index;
                if (_edmTypeIndexes.TryGetValue(identity, out index))
                {
                    map = (MappingBase)this[index];
                    return(true);
                }

                if (cdmType != null
                    ||
                    _edmCollection.TryGetItem(identity, ignoreCase, out cdmType))
                {
                    // If the mapping is not already loaded, then get the mapping ospace type
                    _objectCollection.TryGetOSpaceType(cdmType, out clrType);
                }
            }
            else if (typeSpace == DataSpace.OSpace)
            {
                if (ignoreCase)
                {
                    // Get the correct casing of the identity first if we are asked to do ignore case
                    if (!_objectCollection.TryGetItem(identity, true, out clrType))
                    {
                        map = null;
                        return(false);
                    }

                    identity = clrType.Identity;
                }

                int index;
                if (_clrTypeIndexes.TryGetValue(identity, out index))
                {
                    map = (MappingBase)this[index];
                    return(true);
                }

                if (clrType != null
                    ||
                    _objectCollection.TryGetItem(identity, ignoreCase, out clrType))
                {
                    // If the mapping is not already loaded, get the mapping cspace type
                    var cspaceTypeName = ObjectItemCollection.TryGetMappingCSpaceTypeIdentity(clrType);
                    _edmCollection.TryGetItem(cspaceTypeName, out cdmType);
                }
            }

            if ((clrType == null) ||
                (cdmType == null))
            {
                map = null;
                return(false);
            }
            else
            {
                map = GetDefaultMapping(cdmType, clrType);
                return(true);
            }
        }
Ejemplo n.º 48
0
        // <summary>
        // Returns all the FacetDescriptions for a particular type
        // </summary>
        // <param name="type"> the type to return FacetDescriptions for. </param>
        // <returns> The FacetDescriptions for the type given. </returns>
        public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType type)
        {
            if (Helper.IsPrimitiveType(type)
                && (type).DataSpace == DataSpace.OSpace)
            {
                // we don't have our own facets, just defer to the edm primitive type facets
                var basePrimitive = (PrimitiveType)type.BaseType;
                return basePrimitive.ProviderManifest.GetFacetDescriptions(basePrimitive);
            }

            return Helper.EmptyFacetDescriptionEnumerable;
        }
Ejemplo n.º 49
0
 /// <summary>
 ///     Dumps the specified EDM type metadata instance with the specified decoration
 /// </summary>
 /// <param name="type"> The type metadata to dump </param>
 /// <param name="name"> The decorating block name </param>
 internal void Dump(EdmType type, string name)
 {
     Begin(name);
     Dump(type);
     End(name);
 }