Beispiel #1
0
        public void CreateTypeWithArguments()
        {
            var result = Util.ActivatorCreateInstance(typeof(AddressWithNoEmptyConstructor), "98102") as AddressWithNoEmptyConstructor;

            Assert.NotNull(result);
            result.ZipCode.Should().Be("98102");
        }
Beispiel #2
0
        /// <summary>
        /// Returns true if the <paramref name="instance"/> contains a non-null dictionary property of string and object
        /// The dictionary should also not be decorated with IgnoreClientPropertyAttribute
        /// </summary>
        /// <param name="instance">Object with expected container property</param>
        /// <param name="containerProperty">Reference to the container property</param>
        /// <returns>true if expected container property is found</returns>
        internal static bool TryGetContainerProperty(object instance, out IDictionary <string, object> containerProperty)
        {
            Debug.Assert(instance != null, "instance != null");

            containerProperty = default(IDictionary <string, object>);

            PropertyInfo propertyInfo = instance.GetType().GetPublicProperties(true /* instanceOnly */).Where(p =>
                                                                                                              p.GetCustomAttributes(typeof(ContainerPropertyAttribute), true).Any() &&
                                                                                                              typeof(IDictionary <string, object>).IsAssignableFrom(p.PropertyType)).FirstOrDefault();

            if (propertyInfo == null)
            {
                return(false);
            }

            containerProperty = (IDictionary <string, object>)propertyInfo.GetValue(instance);

            // Is property initialized?
            if (containerProperty == null)
            {
                Type propertyType = propertyInfo.PropertyType;

                // Handle Dictionary<,> , SortedDictionary<,> , ConcurrentDictionary<,> , etc - must also have parameterless constructor
                if (!propertyType.IsInterface() && !propertyType.IsAbstract() && propertyType.GetInstanceConstructor(true, new Type[0]) != null)
                {
                    containerProperty = (IDictionary <string, object>)Util.ActivatorCreateInstance(propertyType);
                }
                else if (propertyType.Equals(typeof(IDictionary <string, object>)))
                {
                    // Default to Dictionary<,> for IDictionary<,> property
                    Type dictionaryType = typeof(Dictionary <,>).MakeGenericType(new Type[] { typeof(string), typeof(object) });
                    containerProperty = (IDictionary <string, object>)Util.ActivatorCreateInstance(dictionaryType);
                }
                else
                {
                    // Not easy to figure out the implementing type
                    return(false);
                }

                propertyInfo.SetValue(instance, containerProperty);

                return(true);
            }

            return(true);
        }
Beispiel #3
0
        internal static IEnumerable ProjectionSelect(ODataEntityMaterializer materializer, MaterializerEntry entry, Type expectedType, Type resultType, ProjectionPath path, Func <object, object, Type, object> selector)
        {
            ClientEdmModel             model = ClientEdmModel.GetModel(materializer.ResponseInfo.MaxProtocolVersion);
            ClientTypeAnnotation       clientTypeAnnotation = entry.ActualType ?? model.GetClientTypeAnnotation(model.GetOrCreateEdmType(expectedType));
            IEnumerable                enumerable           = (IEnumerable)Util.ActivatorCreateInstance(typeof(List <>).MakeGenericType(new Type[] { resultType }), new object[0]);
            MaterializerNavigationLink link     = null;
            ClientPropertyAnnotation   property = null;

            for (int i = 0; i < path.Count; i++)
            {
                ProjectionPathSegment segment = path[i];
                if (segment.SourceTypeAs != null)
                {
                    clientTypeAnnotation = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(segment.SourceTypeAs));
                }
                if (segment.Member != null)
                {
                    string member = segment.Member;
                    property = clientTypeAnnotation.GetProperty(member, false);
                    link     = GetPropertyOrThrow(entry.NavigationLinks, member, entry.Id);
                    if (link.Entry != null)
                    {
                        entry = link.Entry;
                        clientTypeAnnotation = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(property.PropertyType));
                    }
                }
            }
            ValidatePropertyMatch(property, link.Link);
            MaterializerFeed        feed = MaterializerFeed.GetFeed(link.Feed);
            Action <object, object> addToCollectionDelegate = ODataMaterializer.GetAddToCollectionDelegate(enumerable.GetType());

            foreach (ODataEntry entry2 in feed.Entries)
            {
                object obj2 = selector(materializer, entry2, property.EntityCollectionItemType);
                addToCollectionDelegate(enumerable, obj2);
            }
            ProjectionPlan plan = new ProjectionPlan {
                LastSegmentType = property.EntityCollectionItemType,
                Plan            = selector,
                ProjectedType   = resultType
            };

            materializer.FoundNextLinkForCollection(enumerable, feed.NextPageLink, plan);
            return(enumerable);
        }
Beispiel #4
0
        protected static void MaterializeComplexTypeProperty(Type propertyType, ODataComplexValue complexValue, bool ignoreMissingProperties, System.Data.Services.Client.ResponseInfo responseInfo)
        {
            object instance = null;

            if ((complexValue != null) && !complexValue.HasMaterializedValue())
            {
                ClientTypeAnnotation actualType = null;
                if (WebUtil.IsWireTypeCollection(complexValue.TypeName))
                {
                    actualType = responseInfo.TypeResolver.ResolveEdmTypeName(propertyType, complexValue.TypeName);
                }
                else
                {
                    ClientEdmModel model = ClientEdmModel.GetModel(responseInfo.MaxProtocolVersion);
                    actualType = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(propertyType));
                }
                instance = Util.ActivatorCreateInstance(propertyType, new object[0]);
                MaterializeDataValues(actualType, complexValue.Properties, ignoreMissingProperties);
                ApplyDataValues(actualType, complexValue.Properties, ignoreMissingProperties, responseInfo, instance);
                complexValue.SetMaterializedValue(instance);
            }
        }
 /// <summary>
 /// Creates the specified edm type.
 /// </summary>
 /// <param name="edmTypeReference">Type of the edm.</param>
 /// <param name="type">The type.</param>
 /// <remarks>In the future this class will have Materialize and Update will be adding this in upcoming changes</remarks>
 /// <returns>A created object</returns>
 public virtual object CreateNewInstance(IEdmTypeReference edmTypeReference, Type type)
 {
     return(Util.ActivatorCreateInstance(type));
 }
Beispiel #6
0
        /// <summary>Materializes the specified <paramref name="entry"/> as dynamic property.</summary>
        /// <param name="entry">Entry with object to materialize.</param>
        /// <param name="link">Nested resource link as parsed.</param>
        private void MaterializeDynamicProperty(MaterializerEntry entry, ODataNestedResourceInfo link)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(entry.ResolvedObject != null, "entry.ResolvedObject != null -- otherwise not resolved/created!");
            Debug.Assert(link != null, "link != null");

            ClientEdmModel model = this.MaterializerContext.Model;

            IDictionary <string, object> containerProperty;

            // Stop if owning type is not an open type
            // Or container property is not found
            // Or key with matching name already exists in the dictionary
            if (!ClientTypeUtil.IsInstanceOfOpenType(entry.ResolvedObject, model) ||
                !ClientTypeUtil.TryGetContainerProperty(entry.ResolvedObject, out containerProperty) ||
                containerProperty.ContainsKey(link.Name))
            {
                return;
            }

            MaterializerNavigationLink linkState = MaterializerNavigationLink.GetLink(link);

            if (linkState == null || (linkState.Entry == null && linkState.Feed == null))
            {
                return;
            }

            // NOTE: ODL (and OData WebApi) support navigational property on complex types
            // That support has not yet been implemented in OData client

            // An entity or entity collection as a dynamic property currently doesn't work as expected
            // due to the absence of a navigational property definition in the metadata
            // to express the relationship between that entity and the parent entity - unless they're the same type!
            // Only materialize a nested resource if its a complex or complex collection

            if (linkState.Feed != null)
            {
                string collectionTypeName     = linkState.Feed.TypeName; // TypeName represents a collection e.g. Collection(NS.Type)
                string collectionItemTypeName = CommonUtil.GetCollectionItemTypeName(collectionTypeName, false);

                // Highly unlikely, but the method return null if the typeName argument does not meet certain expectations
                if (collectionItemTypeName == null)
                {
                    return;
                }

                Type collectionItemType = ResolveClientTypeForDynamicProperty(collectionItemTypeName, entry.ResolvedObject);

                if (collectionItemType != null && ClientTypeUtil.TypeIsComplex(collectionItemType, model))
                {
                    Type  collectionType = typeof(System.Collections.ObjectModel.Collection <>).MakeGenericType(new Type[] { collectionItemType });
                    IList collection     = (IList)Util.ActivatorCreateInstance(collectionType);

                    IEnumerable <ODataResource> feedEntries = MaterializerFeed.GetFeed(linkState.Feed).Entries;
                    foreach (ODataResource feedEntry in feedEntries)
                    {
                        MaterializerEntry linkEntry = MaterializerEntry.GetEntry(feedEntry);
                        this.Materialize(linkEntry, collectionItemType, false /*includeLinks*/);
                        collection.Add(linkEntry.ResolvedObject);
                    }

                    containerProperty.Add(link.Name, collection);
                }
            }
            else
            {
                MaterializerEntry linkEntry = linkState.Entry;
                Type itemType = ResolveClientTypeForDynamicProperty(linkEntry.Entry.TypeName, entry.ResolvedObject);

                if (itemType != null && ClientTypeUtil.TypeIsComplex(itemType, model))
                {
                    this.Materialize(linkEntry, itemType, false /*includeLinks*/);
                    containerProperty.Add(link.Name, linkEntry.ResolvedObject);
                }
            }
        }
Beispiel #7
0
        public void CreateTypeWithConstructorArgsMismatch()
        {
            Action test = () => Util.ActivatorCreateInstance(typeof(AddressWithNoEmptyConstructor), "zipcode", "streetname");

            test.ShouldThrow <MissingMethodException>().WithMessage("Constructor on type 'AstoriaUnitTests.Tests.UtilUnitTests+AddressWithNoEmptyConstructor' not found.");
        }
Beispiel #8
0
        public void CreateTypeWithNoEmptyConstructor()
        {
            Action test = () => Util.ActivatorCreateInstance(typeof(AddressWithNoEmptyConstructor));

            test.ShouldThrow <MissingMethodException>().WithMessage("No parameterless constructor defined for this object.");
        }
Beispiel #9
0
        public void CreateEmptyConstructorType()
        {
            var result = Util.ActivatorCreateInstance(typeof(Address)) as Address;

            Assert.NotNull(result);
        }
Beispiel #10
0
        internal static object ProjectionValueForPath(ODataEntityMaterializer materializer, MaterializerEntry entry, Type expectedType, ProjectionPath path)
        {
            if ((path.Count == 0) || ((path.Count == 1) && (path[0].Member == null)))
            {
                if (!entry.EntityHasBeenResolved)
                {
                    materializer.Materialize(entry, expectedType, false);
                }
                return(entry.ResolvedObject);
            }
            object streamLink                = null;
            ODataNavigationLink link         = null;
            ODataProperty       atomProperty = null;
            ICollection <ODataNavigationLink> navigationLinks = entry.NavigationLinks;
            IEnumerable <ODataProperty>       properties      = entry.Entry.Properties;
            ClientEdmModel model = ClientEdmModel.GetModel(materializer.ResponseInfo.MaxProtocolVersion);

            for (int i = 0; i < path.Count; i++)
            {
                Func <StreamDescriptor, bool>    predicate = null;
                Func <ODataNavigationLink, bool> func2     = null;
                Func <ODataProperty, bool>       func3     = null;
                Func <ODataProperty, bool>       func4     = null;
                Func <ODataNavigationLink, bool> func5     = null;
                string propertyName;
                ProjectionPathSegment segment = path[i];
                if (segment.Member != null)
                {
                    bool flag = i == (path.Count - 1);
                    propertyName = segment.Member;
                    expectedType = segment.SourceTypeAs ?? expectedType;
                    ClientPropertyAnnotation property = model.GetClientTypeAnnotation(model.GetOrCreateEdmType(expectedType)).GetProperty(propertyName, false);
                    if (property.IsStreamLinkProperty)
                    {
                        if (predicate == null)
                        {
                            predicate = sd => sd.Name == propertyName;
                        }
                        StreamDescriptor descriptor = entry.EntityDescriptor.StreamDescriptors.Where <StreamDescriptor>(predicate).SingleOrDefault <StreamDescriptor>();
                        if (descriptor == null)
                        {
                            if (segment.SourceTypeAs == null)
                            {
                                throw new InvalidOperationException(System.Data.Services.Client.Strings.AtomMaterializer_PropertyMissing(propertyName, entry.Entry.Id));
                            }
                            return(WebUtil.GetDefaultValue <DataServiceStreamLink>());
                        }
                        streamLink = descriptor.StreamLink;
                    }
                    else
                    {
                        if (segment.SourceTypeAs != null)
                        {
                            if (func2 == null)
                            {
                                func2 = p => p.Name == propertyName;
                            }
                            if (!navigationLinks.Any <ODataNavigationLink>(func2))
                            {
                                if (func3 == null)
                                {
                                    func3 = p => p.Name == propertyName;
                                }
                                if (!properties.Any <ODataProperty>(func3) && flag)
                                {
                                    return(WebUtil.GetDefaultValue(property.PropertyType));
                                }
                            }
                        }
                        if (func4 == null)
                        {
                            func4 = p => p.Name == propertyName;
                        }
                        atomProperty = properties.Where <ODataProperty>(func4).FirstOrDefault <ODataProperty>();
                        if (func5 == null)
                        {
                            func5 = p => p.Name == propertyName;
                        }
                        link = ((atomProperty == null) && (navigationLinks != null)) ? navigationLinks.Where <ODataNavigationLink>(func5).FirstOrDefault <ODataNavigationLink>() : null;
                        if ((link == null) && (atomProperty == null))
                        {
                            throw new InvalidOperationException(System.Data.Services.Client.Strings.AtomMaterializer_PropertyMissing(propertyName, entry.Entry.Id));
                        }
                        if (link != null)
                        {
                            ValidatePropertyMatch(property, link);
                            MaterializerNavigationLink link2 = MaterializerNavigationLink.GetLink(link);
                            if (link2.Feed != null)
                            {
                                MaterializerFeed feed = MaterializerFeed.GetFeed(link2.Feed);
                                Type             implementationType = ClientTypeUtil.GetImplementationType(segment.ProjectionType, typeof(ICollection <>));
                                if (implementationType == null)
                                {
                                    implementationType = ClientTypeUtil.GetImplementationType(segment.ProjectionType, typeof(IEnumerable <>));
                                }
                                Type nestedExpectedType = implementationType.GetGenericArguments()[0];
                                Type projectionType     = segment.ProjectionType;
                                if (projectionType.IsInterfaceEx() || ODataMaterializer.IsDataServiceCollection(projectionType))
                                {
                                    projectionType = typeof(Collection <>).MakeGenericType(new Type[] { nestedExpectedType });
                                }
                                IEnumerable list = (IEnumerable)Util.ActivatorCreateInstance(projectionType, new object[0]);
                                MaterializeToList(materializer, list, nestedExpectedType, feed.Entries);
                                if (ODataMaterializer.IsDataServiceCollection(segment.ProjectionType))
                                {
                                    list = (IEnumerable)Util.ActivatorCreateInstance(WebUtil.GetDataServiceCollectionOfT(new Type[] { nestedExpectedType }), new object[] { list, TrackingMode.None });
                                }
                                ProjectionPlan plan = CreatePlanForShallowMaterialization(nestedExpectedType);
                                materializer.FoundNextLinkForCollection(list, feed.Feed.NextPageLink, plan);
                                streamLink = list;
                            }
                            else if (link2.Entry != null)
                            {
                                MaterializerEntry entry2 = link2.Entry;
                                if (flag)
                                {
                                    if ((entry2.Entry != null) && !entry2.EntityHasBeenResolved)
                                    {
                                        materializer.Materialize(entry2, property.PropertyType, false);
                                    }
                                }
                                else
                                {
                                    CheckEntryToAccessNotNull(entry2, propertyName);
                                }
                                properties      = entry2.Properties;
                                navigationLinks = entry2.NavigationLinks;
                                streamLink      = entry2.ResolvedObject;
                                entry           = entry2;
                            }
                        }
                        else
                        {
                            if (atomProperty.Value is ODataStreamReferenceValue)
                            {
                                streamLink      = null;
                                navigationLinks = ODataMaterializer.EmptyLinks;
                                properties      = ODataMaterializer.EmptyProperties;
                                continue;
                            }
                            ValidatePropertyMatch(property, atomProperty);
                            if (ClientTypeUtil.TypeOrElementTypeIsEntity(property.PropertyType))
                            {
                                throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.AtomMaterializer_InvalidEntityType(property.EntityCollectionItemType ?? property.PropertyType));
                            }
                            if (property.IsPrimitiveOrComplexCollection)
                            {
                                object instance = streamLink ?? (entry.ResolvedObject ?? Util.ActivatorCreateInstance(expectedType, new object[0]));
                                ODataMaterializer.ApplyDataValue(model.GetClientTypeAnnotation(model.GetOrCreateEdmType(instance.GetType())), atomProperty, materializer.ResponseInfo.IgnoreMissingProperties, materializer.ResponseInfo, instance);
                                navigationLinks = ODataMaterializer.EmptyLinks;
                                properties      = ODataMaterializer.EmptyProperties;
                            }
                            else if (atomProperty.Value is ODataComplexValue)
                            {
                                ODataComplexValue complexValue = atomProperty.Value as ODataComplexValue;
                                ODataMaterializer.MaterializeComplexTypeProperty(property.PropertyType, complexValue, materializer.ResponseInfo.IgnoreMissingProperties, materializer.ResponseInfo);
                                properties      = complexValue.Properties;
                                navigationLinks = ODataMaterializer.EmptyLinks;
                            }
                            else
                            {
                                if ((atomProperty.Value == null) && !ClientTypeUtil.CanAssignNull(property.NullablePropertyType))
                                {
                                    throw new InvalidOperationException(System.Data.Services.Client.Strings.AtomMaterializer_CannotAssignNull(atomProperty.Name, property.NullablePropertyType));
                                }
                                ODataMaterializer.MaterializePrimitiveDataValue(property.NullablePropertyType, atomProperty);
                                navigationLinks = ODataMaterializer.EmptyLinks;
                                properties      = ODataMaterializer.EmptyProperties;
                            }
                            streamLink = atomProperty.GetMaterializedValue();
                        }
                    }
                    expectedType = property.PropertyType;
                }
            }
            return(streamLink);
        }
Beispiel #11
0
 internal object CreateInstance()
 {
     return(Util.ActivatorCreateInstance(this.ElementType, new object[0]));
 }