Пример #1
0
 public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
 {
     EdmEntityObject entity = new EdmEntityObject(entityType);
     entity.TrySetPropertyValue("Name", "Foo");
     entity.TrySetPropertyValue("ID", 100);
     collection.Add(entity);
     entity = new EdmEntityObject(entityType);
     entity.TrySetPropertyValue("Name", "Bar");
     entity.TrySetPropertyValue("ID", 101);
     collection.Add(entity);
 }
Пример #2
0
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);

            entity.TrySetPropertyValue("Name", "Foo");
            entity.TrySetPropertyValue("ID", 100);
            collection.Add(entity);
            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Bar");
            entity.TrySetPropertyValue("ID", 101);
            collection.Add(entity);
        }
Пример #3
0
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "abc");
            entity.TrySetPropertyValue("ID", 1);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(88, "abc_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "def");
            entity.TrySetPropertyValue("ID", 2);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(99, "def_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
        }
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Foo");
            entity.TrySetPropertyValue("ID", 100);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(2016, 1, 19, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));
            collection.Add(entity);

            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Bar");
            entity.TrySetPropertyValue("ID", 101);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(1978, 11, 15, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));

            collection.Add(entity);
        }
Пример #5
0
        protected IEnumerable <IEdmEntityObject> GetFilteredResult(IEnumerable <Dictionary <string, object> > group, string query, ParseContext parseContext)
        {
            // Create collection from group
            var collectionEntityTypeKey = parseContext.LatestStateDictionary
                                          .Keys.FirstOrDefault(p => p.Contains("collectionentitytype"));
            var entityRef     = (EdmEntityTypeReference)parseContext.LatestStateDictionary[collectionEntityTypeKey];
            var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
            var collection    = new EdmEntityObjectCollection(collectionRef);

            foreach (var entity in group)
            {
                var obj = new EdmEntityObject(entityRef);
                foreach (var kvp in entity)
                {
                    obj.TrySetPropertyValue(kvp.Key, kvp.Value);
                }
                collection.Add(obj);
            }
            // Create filter query using the entity supplied in the lateststatedictionary
            var serviceRoot    = new Uri(RequestFilterConstants.ODataServiceRoot);
            var resource       = entityRef.Definition.FullTypeName().Split(".").Last();
            var filterQuery    = "/" + resource + "?$filter=" + Uri.EscapeDataString(query.Substring(1, query.Length - 2).Replace("''", "'"));
            var oDataUriParser = new ODataUriParser(parseContext.Model, new Uri(filterQuery, UriKind.Relative));

            // Parse filterquery
            var filter         = oDataUriParser.ParseFilter();
            var odataFilter    = new ODataFilterPredicateParser();
            var filteredResult = odataFilter.ApplyFilter(parseContext.EdmEntityTypeSettings.FirstOrDefault(), collection, filter.Expression);

            return(filteredResult);
        }
Пример #6
0
        public EdmEntityObjectCollection Get(IEdmCollectionType collectionType, ODataQueryOptions queryOptions)
        {
            var entityType = collectionType.ElementType.Definition as EdmEntityType;
            var collection = new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType, true));

            if (entityType != null)
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    var sqlBuilder = new SqlQueryBuilder(queryOptions);
                    var sql        = sqlBuilder.ToSql();

                    Console.WriteLine(sql);

                    IEnumerable <dynamic> rows = connection.Query <dynamic>(sql);

                    foreach (dynamic row in rows)
                    {
                        var entity = CreateEdmEntity(entityType, row);
                        collection.Add(entity);
                    }
                }
            }

            return(collection);
        }
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);

            entity.TrySetPropertyValue("Name", "abc");
            entity.TrySetPropertyValue("ID", 1);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(88, "abc_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "def");
            entity.TrySetPropertyValue("ID", 2);
            entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(99, "def_detailinfo", entity.ActualEdmType));

            collection.Add(entity);
        }
Пример #8
0
        private static EdmEntityObjectCollection GetCustomers()
        {
            if (_untypedSimpleOpenCustormers != null)
            {
                return(_untypedSimpleOpenCustormers);
            }

            IEdmModel       edmModel     = OpenEntityTypeTests.GetUntypedEdmModel();
            IEdmEntityType  customerType = edmModel.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "UntypedSimpleOpenCustomer");
            EdmEntityObject customer     = new EdmEntityObject(customerType);

            customer.TrySetPropertyValue("CustomerId", 1);

            //Add Numbers primitive collection property
            customer.TrySetPropertyValue("DeclaredNumbers", new[] { 1, 2 });

            //Add Color, Colors enum(collection) property
            IEdmEnumType  colorType = edmModel.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "Color");
            EdmEnumObject color     = new EdmEnumObject(colorType, "Red");
            EdmEnumObject color2    = new EdmEnumObject(colorType, "0");
            EdmEnumObject color3    = new EdmEnumObject(colorType, "Red");

            customer.TrySetPropertyValue("Color", color);

            List <IEdmEnumObject> colorList = new List <IEdmEnumObject>();

            colorList.Add(color);
            colorList.Add(color2);
            colorList.Add(color3);
            IEdmCollectionTypeReference enumCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(colorType.ToEdmTypeReference(false)));
            EdmEnumObjectCollection     colors             = new EdmEnumObjectCollection(enumCollectionType, colorList);

            customer.TrySetPropertyValue("Colors", colors);
            customer.TrySetPropertyValue("DeclaredColors", colors);

            //Add Addresses complex(collection) property
            EdmComplexType addressType =
                edmModel.SchemaElements.OfType <IEdmComplexType>().First(c => c.Name == "Address") as EdmComplexType;
            EdmComplexObject address = new EdmComplexObject(addressType);

            address.TrySetPropertyValue("Street", "No1");
            EdmComplexObject address2 = new EdmComplexObject(addressType);

            address2.TrySetPropertyValue("Street", "No2");

            List <IEdmComplexObject> addressList = new List <IEdmComplexObject>();

            addressList.Add(address);
            addressList.Add(address2);
            IEdmCollectionTypeReference complexCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(addressType.ToEdmTypeReference(false)));
            EdmComplexObjectCollection  addresses             = new EdmComplexObjectCollection(complexCollectionType, addressList);

            customer.TrySetPropertyValue("DeclaredAddresses", addresses);

            EdmEntityObjectCollection customers = new EdmEntityObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(customerType.ToEdmTypeReference(false))));

            customers.Add(customer);
            _untypedSimpleOpenCustormers = customers;
            return(_untypedSimpleOpenCustormers);
        }
Пример #9
0
        public void Get(IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            EdmEntityObject entity = new EdmEntityObject(entityType);

            entity.TrySetPropertyValue("Name", "Foo");
            entity.TrySetPropertyValue("ID", 100);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(2016, 1, 19, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));
            collection.Add(entity);

            entity = new EdmEntityObject(entityType);
            entity.TrySetPropertyValue("Name", "Bar");
            entity.TrySetPropertyValue("ID", 101);
            entity.TrySetPropertyValue("School", Createchool(99, new DateTimeOffset(1978, 11, 15, 1, 2, 3, TimeSpan.Zero), entity.ActualEdmType));

            collection.Add(entity);
        }
Пример #10
0
        public void Get(ODataQueryOptions queryOptions, IEdmEntityTypeReference entityType, EdmEntityObjectCollection collection)
        {
            var name = entityType.Definition.FullTypeName().Remove(0, EdmNamespaceName.Length + 1); // ns.
            var obj  = new EdmEntityObject(entityType);

            obj.TrySetPropertyValue("Column1", "Hello World");
            obj.TrySetPropertyValue("Column2", "Hello World");

            collection.Add(obj);
        }
Пример #11
0
            internal static object ConvertFeed(ODataMessageReader oDataMessageReader, IEdmTypeReference edmTypeReference, ODataDeserializerContext readContext)
            {
                IEdmCollectionTypeReference collectionType = edmTypeReference.AsCollection();

                EdmEntitySet tempEntitySet = new EdmEntitySet(readContext.Model.EntityContainer, "temp",
                                                              collectionType.ElementType().AsEntity().EntityDefinition());

                ODataReader odataReader = oDataMessageReader.CreateODataFeedReader(tempEntitySet,
                                                                                   collectionType.ElementType().AsEntity().EntityDefinition());
                ODataFeedWithEntries feed =
                    ODataEntityDeserializer.ReadEntryOrFeed(odataReader) as ODataFeedWithEntries;

                ODataFeedDeserializer feedDeserializer =
                    (ODataFeedDeserializer)DeserializerProvider.GetEdmTypeDeserializer(collectionType);

                object      result     = feedDeserializer.ReadInline(feed, collectionType, readContext);
                IEnumerable enumerable = result as IEnumerable;

                if (enumerable != null)
                {
                    IEnumerable newEnumerable = CovertFeedIds(enumerable, feed, collectionType, readContext);
                    if (readContext.IsUntyped)
                    {
                        EdmEntityObjectCollection entityCollection =
                            new EdmEntityObjectCollection(collectionType);
                        foreach (EdmEntityObject entity in newEnumerable)
                        {
                            entityCollection.Add(entity);
                        }

                        return(entityCollection);
                    }
                    else
                    {
                        IEdmTypeReference elementTypeReference = collectionType.ElementType();

                        Type elementClrType = EdmLibHelpers.GetClrType(elementTypeReference,
                                                                       readContext.Model);
                        IEnumerable castedResult =
                            CastMethodInfo.MakeGenericMethod(elementClrType)
                            .Invoke(null, new object[] { newEnumerable }) as IEnumerable;
                        return(castedResult);
                    }
                }

                return(null);
            }
Пример #12
0
        public static IEdmObject ConvertToEdmObject(this IEnumerable enumerable, IEdmCollectionTypeReference collectionType)
        {
            Contract.Assert(enumerable != null);
            Contract.Assert(collectionType != null);

            IEdmTypeReference elementType = collectionType.ElementType();

            if (elementType.IsEntity())
            {
                EdmEntityObjectCollection entityCollection =
                    new EdmEntityObjectCollection(collectionType);

                foreach (EdmEntityObject entityObject in enumerable)
                {
                    entityCollection.Add(entityObject);
                }

                return(entityCollection);
            }
            else if (elementType.IsComplex())
            {
                EdmComplexObjectCollection complexCollection =
                    new EdmComplexObjectCollection(collectionType);

                foreach (EdmComplexObject complexObject in enumerable)
                {
                    complexCollection.Add(complexObject);
                }

                return(complexCollection);
            }
            else if (elementType.IsEnum())
            {
                EdmEnumObjectCollection enumCollection =
                    new EdmEnumObjectCollection(collectionType);

                foreach (EdmEnumObject enumObject in enumerable)
                {
                    enumCollection.Add(enumObject);
                }

                return(enumCollection);
            }

            return(null);
        }
Пример #13
0
        public IHttpActionResult Get()
        {
            IEdmModel      model        = Request.GetModel();
            IEdmEntityType customerType = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "Customer");

            EdmEntityObject customer = new EdmEntityObject(customerType);

            customer.TrySetPropertyValue("Id", 1);
            customer.TrySetPropertyValue("Tony", 1);

            EdmEntityObjectCollection customers =
                new EdmEntityObjectCollection(
                    new EdmCollectionTypeReference(new EdmCollectionType(customerType.ToEdmTypeReference(false))));

            customers.Add(customer);
            return(Ok(customers));
        }
Пример #14
0
        private EdmEntityObjectCollection GetCustomers()
        {
            IEdmModel edmModel = Request.ODataProperties().Model;

            IEdmEntityType  customerType = edmModel.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "Customer");
            IEdmEnumType    colorType    = edmModel.SchemaElements.OfType <IEdmEnumType>().Single(e => e.Name == "Color");
            IEdmComplexType addressType  = edmModel.SchemaElements.OfType <IEdmComplexType>().Single(e => e.Name == "Address");

            // an enum object
            EdmEnumObject color = new EdmEnumObject(colorType, "Red");

            // a complex object
            EdmComplexObject address1 = new EdmComplexObject(addressType);

            address1.TrySetPropertyValue("Street", "ZiXing Rd");                                            // Declared property
            address1.TrySetPropertyValue("StringProperty", "CN");                                           // a string dynamic property
            address1.TrySetPropertyValue("GuidProperty", new Guid("181D3A20-B41A-489F-9F15-F91F0F6C9ECA")); // a guid dynamic property

            // another complex object with complex dynamic property
            EdmComplexObject address2 = new EdmComplexObject(addressType);

            address2.TrySetPropertyValue("Street", "ZiXing Rd");       // Declared property
            address2.TrySetPropertyValue("AddressProperty", address1); // a complex dynamic property

            // an entity object
            EdmEntityObject customer = new EdmEntityObject(customerType);

            customer.TrySetPropertyValue("CustomerId", 1);      // Declared property
            customer.TrySetPropertyValue("Name", "Mike");       // Declared property
            customer.TrySetPropertyValue("Color", color);       // an enum dynamic property
            customer.TrySetPropertyValue("Address1", address1); // a complex dynamic property
            customer.TrySetPropertyValue("Address2", address2); // another complex dynamic property

            // a collection with one object
            EdmEntityObjectCollection collection =
                new EdmEntityObjectCollection(
                    new EdmCollectionTypeReference(
                        new EdmCollectionType(new EdmEntityTypeReference(customerType, isNullable: true))));

            collection.Add(customer);

            return(collection);
        }
Пример #15
0
        public async Task <ActionResult <IEnumerable <IEdmEntityObject> > > Get()
        {
            var entityType     = _oDataRequestHelper.GetEdmEntityTypeReference(Request);
            var collectionType = _oDataRequestHelper.GetEdmCollectionType(Request);

            var collection      = new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType));
            var queryCollection = new List <Dictionary <string, object> >();
            var modelSettings   = _oDataModelSettingsProvider.GetEdmModelSettingsFromRequest(Request);
            var entities        = _genericEntityRepository.GetEntities(modelSettings.RouteName);

            foreach (var entity in entities)
            {
                var dynamicEntityDictionary = entity.PropertyList;
                collection.Add(GetEdmEntityObject(dynamicEntityDictionary, entityType));
                queryCollection.Add(dynamicEntityDictionary);
            }
            var result = _oDataFilterManager.ApplyFilter(collection, queryCollection, Request);

            return(Ok(result));
        }
        public ODataQueryBenchmarks()
        {
            BeforeEachBenchmark(recordCount);
            _url = "https://localhost:44312/odata/entities/user?$apply=groupby((Title),aggregate(Salary with max as MaxSalary))";
            SetRequestHost(new Uri(_url));
            var request        = _httpContext.Request;
            var entityType     = _oDataRequestHelper.GetEdmEntityTypeReference(request);
            var collectionType = _oDataRequestHelper.GetEdmCollectionType(request);

            edmEntityObjectCollection = new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType));
            queryCollection           = new List <Dictionary <string, object> >();
            var entities = _genericEntityRepository.GetEntities("user");

            foreach (var entity in entities)
            {
                var dynamicEntityDictionary = entity.PropertyList;
                edmEntityObjectCollection.Add(GetEdmEntityObject(dynamicEntityDictionary, entityType));
                queryCollection.Add(dynamicEntityDictionary);
            }
            _oDataFilterManager = GetODataFilterManager();
        }
        private IEnumerable <IEdmEntityObject> ApplyODataFilterAndGetData(string url)
        {
            BeforeEachTest();
            SetRequestHost(new Uri(url));
            var request        = _httpContext.Request;
            var entityType     = _oDataRequestHelper.GetEdmEntityTypeReference(request);
            var collectionType = _oDataRequestHelper.GetEdmCollectionType(request);

            var collection      = new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType));
            var queryCollection = new List <Dictionary <string, object> >();
            var entities        = _genericEntityRepository.GetEntities(_edmEntityTypeSettings.RouteName);

            foreach (var entity in entities)
            {
                var dynamicEntityDictionary = entity.PropertyList;
                collection.Add(GetEdmEntityObject(dynamicEntityDictionary, entityType));
                queryCollection.Add(dynamicEntityDictionary);
            }
            var odataFilterManager = GetODataFilterManager();

            return(odataFilterManager.ApplyFilter(collection, queryCollection, _httpContext.Request));
        }
Пример #18
0
        public ParseContext Parse(ODataUriParser parser, ParseContext parseContext)
        {
            var rootfilter       = parser.ParseFilter();
            var sourceEdmSetting = parseContext.EdmEntityTypeSettings.FirstOrDefault();


            var collectionEntityTypeKey = parseContext.LatestStateDictionary
                                          .Keys.FirstOrDefault(p => p.Contains("collectionentitytype"));

            var entityRef     = (EdmEntityTypeReference)parseContext.LatestStateDictionary[collectionEntityTypeKey];
            var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
            var collection    = new EdmEntityObjectCollection(collectionRef);


            var filterdata      = ApplyFilter(sourceEdmSetting, parseContext.Result, rootfilter.Expression);
            var filteredResults = parseContext.Result.Intersect(filterdata);



            foreach (var entity in filteredResults)
            {
                collection.Add(entity);
            }

            var idList = filteredResults
                         .Select(p => p.TryGetPropertyValue(IdProperty, out object id) ? (Guid)id : Guid.Empty)
                         .ToDictionary(p => p, q => !q.Equals(Guid.Empty));

            var targetParseContext = new ParseContext
            {
                Result = collection,
                QueryableSourceEntities = parseContext.QueryableSourceEntities.Where(p => idList.ContainsKey((Guid)p[IdProperty])).ToList(),
                Model = parseContext.Model,
                EdmEntityTypeSettings = parseContext.EdmEntityTypeSettings,
                LatestStateDictionary = parseContext.LatestStateDictionary
            };

            return(targetParseContext);
        }
        public ParseContext Parse(ODataUriParser parser, ParseContext parseContext)
        {
            var top = parser.ParseTop();

            if (top.Value > 0)
            {
                bool isParsed = int.TryParse(top.Value.ToString(), out int count);

                var collectionEntityTypeKey = parseContext.LatestStateDictionary
                                              .Keys.FirstOrDefault(p => p.Contains("collectionentitytype"));

                var entityRef     = (EdmEntityTypeReference)parseContext.LatestStateDictionary[collectionEntityTypeKey];
                var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
                var collection    = new EdmEntityObjectCollection(collectionRef);

                var filteredResults = parseContext.Result.Take(count);

                foreach (var entity in filteredResults)
                {
                    collection.Add(entity);
                }

                var targetParseContext = new ParseContext
                {
                    Result = collection,
                    QueryableSourceEntities = parseContext.QueryableSourceEntities.Take(count),
                    Model = parseContext.Model,
                    EdmEntityTypeSettings = parseContext.EdmEntityTypeSettings,
                    LatestStateDictionary = parseContext.LatestStateDictionary
                };
                return(targetParseContext);
            }
            else
            {
                throw new InvalidPropertyException("Top", string.Empty);
            }
        }
Пример #20
0
        public EdmEntityObjectCollection Translate(IEnumerable <IDictionary <string, object> > fromRows, IEdmCollectionType toCollectionType)
        {
            var entityType = toCollectionType.ElementType.Definition as EdmEntityType;
            var collection = new EdmEntityObjectCollection(new EdmCollectionTypeReference(toCollectionType, true));

            var firstRow = fromRows.FirstOrDefault();

            if (firstRow == null)
            {
                return(collection);
            }

            var componentHelpClasses = EntityTypeToColumnsMap.GetOrAdd(
                entityType.Name,
                entityName => BuildMap(firstRow));

            foreach (dynamic row in fromRows)
            {
                var entity = CreateEdmEntity(entityType, row, componentHelpClasses);
                collection.Add(entity);
            }

            return(collection);
        }
Пример #21
0
        public IHttpActionResult Get()
        {
            IEdmModel model = Request.ODataProperties().Model;
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Customer");

            EdmEntityObject customer = new EdmEntityObject(customerType);

            customer.TrySetPropertyValue("Id", 1);
            customer.TrySetPropertyValue("Tony", 1);

            EdmEntityObjectCollection customers =
                new EdmEntityObjectCollection(
                    new EdmCollectionTypeReference(new EdmCollectionType(customerType.ToEdmTypeReference(false))));
            customers.Add(customer);
            return Ok(customers);

        }
Пример #22
0
        public ParseContext Parse(ODataUriParser parser, ParseContext sourceParseContext)
        {
            //Select implementation
            var targetParseContext            = new ParseContext();
            var targetQueryableSourceEntities = new List <Dictionary <string, object> >();
            var sourceEdmSetting = sourceParseContext.EdmEntityTypeSettings.FirstOrDefault();
            var targetEdmSetting = new EdmEntityTypeSettings()
            {
                RouteName  = SelectParser,
                Personas   = sourceEdmSetting.Personas,
                Properties = new List <EdmEntityTypePropertySetting>()
            };
            var selectExpandClause    = parser.ParseSelectAndExpand();
            var edmEntityType         = new EdmEntityType(EdmNamespaceName, SelectParser);
            var latestStateDictionary = new Dictionary <string, object>();

            //Construct the types. For now we support non-nested primitive types only. Everything else is an exception for now.
            var propertyList = new List <string>();

            foreach (var item in selectExpandClause.SelectedItems)
            {
                switch (item)
                {
                case PathSelectItem pathSelectItem:
                    IEnumerable <ODataPathSegment> segments = pathSelectItem.SelectedPath;
                    var firstPropertySegment = segments.FirstOrDefault();
                    if (firstPropertySegment != null)
                    {
                        var typeSetting = sourceEdmSetting.Properties.FirstOrDefault(predicate => predicate.PropertyName == firstPropertySegment.Identifier);

                        propertyList.Add(firstPropertySegment.Identifier);

                        if (typeSetting.GetEdmPrimitiveTypeKind() != EdmPrimitiveTypeKind.None)
                        {
                            var edmPrimitiveType = typeSetting.GetEdmPrimitiveTypeKind();
                            if (typeSetting.IsNullable.HasValue)
                            {
                                edmEntityType.AddStructuralProperty(firstPropertySegment.Identifier, edmPrimitiveType, typeSetting.IsNullable.Value);
                            }
                            else
                            {
                                edmEntityType.AddStructuralProperty(firstPropertySegment.Identifier, edmPrimitiveType);
                            }
                            targetEdmSetting.Properties.Add(new EdmEntityTypePropertySetting
                            {
                                PropertyName = typeSetting.PropertyName,
                                PropertyType = typeSetting.PropertyType,
                                IsNullable   = typeSetting.IsNullable
                            });
                        }
                        else
                        {
                            //We are doing $select on a property which is of type list. Which means
                            if (typeSetting.PropertyType == "List")
                            {
                                var edmComplexType = GetEdmComplexTypeReference(sourceParseContext);
                                edmEntityType.AddStructuralProperty(typeSetting.PropertyName, new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(edmComplexType, true))));
                                targetEdmSetting.Properties.Add(new EdmEntityTypePropertySetting
                                {
                                    PropertyName = typeSetting.PropertyName,
                                    PropertyType = typeSetting.PropertyType,
                                    IsNullable   = typeSetting.IsNullable
                                });
                            }
                            else
                            {
                                throw new FeatureNotSupportedException(SelectParser, $"Invalid Custom Selection-{typeSetting.PropertyName}-{typeSetting.PropertyType}");
                            }
                        }
                    }
                    else
                    {
                        throw new FeatureNotSupportedException(SelectParser, "Empty Path Segments");
                    }
                    break;

                case WildcardSelectItem wildcardSelectItem: throw new FeatureNotSupportedException(SelectParser, "WildcardSelect");

                case ExpandedNavigationSelectItem expandedNavigationSelectItem: throw new FeatureNotSupportedException(SelectParser, "ExpandedNavigation");

                case ExpandedReferenceSelectItem expandedReferenceSelectItem: throw new FeatureNotSupportedException(SelectParser, "ExpandedReference");

                case NamespaceQualifiedWildcardSelectItem namespaceQualifiedWildcardSelectItem: throw new FeatureNotSupportedException(SelectParser, "NamespaceQualifiedWildcard");
                }
            }

            //Register these dynamic types to model
            sourceParseContext.Model.AddElement(edmEntityType);
            ((EdmEntityContainer)sourceParseContext.Model.EntityContainer).AddEntitySet("Select", edmEntityType);


            //Construct the data
            var entityReferenceType         = new EdmEntityTypeReference(edmEntityType, true);
            var collectionRef               = new EdmCollectionTypeReference(new EdmCollectionType(entityReferenceType));
            var collection                  = new EdmEntityObjectCollection(collectionRef);
            var filteredQueryableEntityList = sourceParseContext.QueryableSourceEntities.Select(p => p.Where(p => propertyList.Contains(p.Key)));

            latestStateDictionary.Add(RequestFilterConstants.GetEntityTypeKeyName(SelectParser, StepIndex), entityReferenceType);

            foreach (var entity in filteredQueryableEntityList)
            {
                var entityDictionary = new Dictionary <string, object>();
                var obj = new EdmEntityObject(edmEntityType);
                foreach (var propertyKey in propertyList)
                {
                    var setting = targetEdmSetting.Properties.FirstOrDefault(predicate => predicate.PropertyName.Equals(propertyKey));
                    var data    = entity.FirstOrDefault(property => property.Key.Equals(propertyKey));

                    //This condition is when the type of selected property is a primitive type
                    if (setting.GetEdmPrimitiveTypeKind() != EdmPrimitiveTypeKind.None)
                    {
                        var propertyValue = !data.Equals(default(KeyValuePair <string, object>)) ? data.Value : null;
                        obj.TrySetPropertyValue(propertyKey, propertyValue);
                        entityDictionary.Add(propertyKey, propertyValue);
                    }
                    else
                    {
                        switch (setting.PropertyType)
                        {
                        case "List":
                            //TODO: There is scope for perf improvement
                            //We can re-use the previous constructed list instead of constructing one from scratch.
                            var subList        = (List <Dictionary <string, object> >)data.Value;
                            var subListContext = GetList(subList, GetEdmComplexTypeReference(sourceParseContext));
                            obj.TrySetPropertyValue(propertyKey, subListContext.Result);
                            entityDictionary.Add(propertyKey, subListContext.QueryAbleResult);
                            break;
                        }
                    }
                }
                collection.Add(obj);
                targetQueryableSourceEntities.Add(entityDictionary);
            }

            targetParseContext.Result = collection;
            targetParseContext.QueryableSourceEntities = targetQueryableSourceEntities;
            targetParseContext.Model = sourceParseContext.Model;
            targetParseContext.EdmEntityTypeSettings = new List <EdmEntityTypeSettings> {
                targetEdmSetting
            };
            targetParseContext.LatestStateDictionary = latestStateDictionary;
            return(targetParseContext);
        }
Пример #23
0
        EdmEntityObjectCollection Get(IEdmCollectionType edmType, string sqlCmd, List<ExpandedNavigationSelectItem> expands = null)
        {
            var entityType = edmType.ElementType.AsEntity();

            EdmEntityObjectCollection collection = new EdmEntityObjectCollection(new EdmCollectionTypeReference(edmType));
            using (DbAccess db = new DbAccess(this.ConnectionString))
            {
                db.ExecuteReader(sqlCmd, (reader) =>
                {
                    EdmEntityObject entity = new EdmEntityObject(entityType);
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        reader.SetEntityPropertyValue(i, entity);
                    }
                    if (expands != null)
                    {
                        foreach (var expanded in expands)
                        {
                            List<string> condition = new List<string>();
                            foreach (NavigationPropertySegment item in expanded.PathToNavigationProperty)
                            {
                                foreach (var p in item.NavigationProperty.ReferentialConstraint.PropertyPairs)
                                {
                                    condition.Add(packCondition(p, reader[p.DependentProperty.Name]));
                                }
                            }
                            var ss = Get(expanded.NavigationSource.Type as IEdmCollectionType, BuildSqlQueryCmd(expanded, string.Join(" and ", condition)));
                            bool t = entity.TrySetPropertyValue(expanded.NavigationSource.Name, ss);
                        }
                    }
                    collection.Add(entity);

                }, null, CommandType.Text);
            }
            return collection;
        }
        /// <summary>
        /// Gets the collection of records for the requested entity set and specified OData query options.
        /// </summary>
        /// <param name="model"><see cref="IEdmModel"/></param>
        /// <param name="entitySetName">Name of the entity set</param>
        /// <param name="queryOptions"><see cref="System.Web.Http.OData.Query.ODataQueryOptions"/></param>
        /// <param name="querySettings"><see cref="System.Web.Http.OData.Query.ODataQuerySettings"/></param>
        /// <param name="request"><see cref="HttpRequestMessage"/></param>
        /// <returns><see cref="EdmEntityObjectCollection"/></returns>
        public virtual EdmEntityObjectCollection SelectMultiple(IEdmModel model, string entitySetName, System.Web.Http.OData.Query.ODataQueryOptions queryOptions, System.Web.Http.OData.Query.ODataQuerySettings querySettings, HttpRequestMessage request)
        {
            var edmEntitySchemaType             = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, entitySetName));
            var edmEntityType                   = edmEntitySchemaType as IEdmEntityType;
            var entityListIdProperty            = edmEntityType.FindProperty("list-id") as IEdmStructuralProperty;
            var entityListIdString              = entityListIdProperty.DefaultValueString;
            var viewIdProperty                  = edmEntityType.FindProperty("view-id") as IEdmStructuralProperty;
            var viewIdString                    = viewIdProperty.DefaultValueString;
            var entityPermissionEnabledProperty =
                edmEntityType.FindProperty("entity-permissions-enabled") as IEdmStructuralProperty;
            bool entityPermissionsEnabled;

            bool.TryParse(entityPermissionEnabledProperty.DefaultValueString, out entityPermissionsEnabled);

            Guid viewId;

            Guid.TryParse(viewIdString, out viewId);
            var view        = GetView(viewId);
            var viewColumns = view.Columns.ToList();
            var fetch       = Fetch.Parse(view.FetchXml);

            queryOptions.ApplyTo(querySettings, fetch);
            var serviceContext = this.Dependencies.GetServiceContext();

            // If Entity Permissions on the view was enabled then restrict add entity Permissions to Fetch
            if (entityPermissionsEnabled)
            {
                var crmEntityPermissionProvider = new CrmEntityPermissionProvider();
                var perm = crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(
                    serviceContext,
                    CrmEntityPermissionRight.Read,
                    fetch);

                // Ensure the user has permissions to request read access to the entity.
                if (!perm.PermissionGranted && !perm.GlobalPermissionGranted)
                {
                    ADXTrace.Instance.TraceWarning(
                        TraceCategory.Exception,
                        string.Format(
                            "Access to oData, with the entity set name of '{0}', has been denied for the user with the following webroles: '{1}' due to entity permissions. Grant the webroles read access to the entityset if this was not an error.",
                            entitySetName,
                            string.Join("', '", crmEntityPermissionProvider.CurrentUserRoleNames)));
                    throw new SecurityAccessDeniedException();
                }
            }

            var dataSchemaType          = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, entitySetName));
            var dataEntityType          = dataSchemaType as IEdmEntityType;
            var dataEntityTypeReference = new EdmEntityTypeReference(dataEntityType, true);
            var collection = new EdmEntityObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(dataEntityTypeReference), true));
            var entityReferenceSchemaType           = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, "EntityReference"));
            var entityReferenceComplexType          = entityReferenceSchemaType as IEdmComplexType;
            var entityReferenceComplexTypeReference = new EdmComplexTypeReference(entityReferenceComplexType, true);
            var optionSetSchemaType           = model.FindDeclaredType(string.Format("{0}.{1}", NamespaceName, "OptionSet"));
            var optionSetComplexType          = optionSetSchemaType as IEdmComplexType;
            var optionSetComplexTypeReference = new EdmComplexTypeReference(optionSetComplexType, true);
            var entityCollection = fetch.Execute(serviceContext as IOrganizationService);

            if (entityCollection == null)
            {
                return(collection);
            }

            var records = entityCollection.Entities;

            foreach (var record in records)
            {
                var entityObject = BuildEdmEntityObject(record, view, viewColumns, dataEntityTypeReference, entityReferenceComplexTypeReference, optionSetComplexTypeReference, entityListIdString, viewIdString);
                collection.Add(entityObject);
            }

            if (entityCollection.MoreRecords && querySettings.PageSize.HasValue && querySettings.PageSize > 0)
            {
                var nextPageLink = ODataQueryOptionExtensions.GetNextPageLink(request, querySettings.PageSize.Value);
                request.SetNextPageLink(nextPageLink);
            }

            if (entityCollection.TotalRecordCount > 0)
            {
                request.SetInlineCount(entityCollection.TotalRecordCount);
            }

            return(collection);
        }
        public override object Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

            IEdmAction action = GetAction(readContext);
            Contract.Assert(action != null);

            // Create the correct resource type;
            Dictionary<string, object> payload;
            if (type == typeof(ODataActionParameters))
            {
                payload = new ODataActionParameters();
            }
            else
            {
                payload = new ODataUntypedActionParameters(action);
            }

            ODataParameterReader reader = messageReader.CreateODataParameterReader(action);

            while (reader.Read())
            {
                string parameterName = null;
                IEdmOperationParameter parameter = null;

                switch (reader.State)
                {
                    case ODataParameterReaderState.Value:
                        parameterName = reader.Name;
                        parameter = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                        // ODataLib protects against this but asserting just in case.
                        Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                        if (parameter.Type.IsPrimitive())
                        {
                            payload[parameterName] = reader.Value;
                        }
                        else
                        {
                            ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(parameter.Type);
                            payload[parameterName] = deserializer.ReadInline(reader.Value, parameter.Type, readContext);
                        }
                        break;

                    case ODataParameterReaderState.Collection:
                        parameterName = reader.Name;
                        parameter = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                        // ODataLib protects against this but asserting just in case.
                        Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                        IEdmCollectionTypeReference collectionType = parameter.Type as IEdmCollectionTypeReference;
                        Contract.Assert(collectionType != null);
                        ODataCollectionValue value = ODataCollectionDeserializer.ReadCollection(reader.CreateCollectionReader());
                        ODataCollectionDeserializer collectionDeserializer = (ODataCollectionDeserializer)DeserializerProvider.GetEdmTypeDeserializer(collectionType);
                        payload[parameterName] = collectionDeserializer.ReadInline(value, collectionType, readContext);
                        break;

                    case ODataParameterReaderState.Entry:
                        parameterName = reader.Name;
                        parameter = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                        Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));

                        IEdmEntityTypeReference entityTypeReference = parameter.Type as IEdmEntityTypeReference;
                        Contract.Assert(entityTypeReference != null);

                        ODataReader entryReader = reader.CreateEntryReader();
                        object item = ODataEntityDeserializer.ReadEntryOrFeed(entryReader);
                        ODataEntityDeserializer entityDeserializer = (ODataEntityDeserializer)DeserializerProvider.GetEdmTypeDeserializer(entityTypeReference);
                        payload[parameterName] = entityDeserializer.ReadInline(item, entityTypeReference, readContext);
                        break;

                    case ODataParameterReaderState.Feed:
                        parameterName = reader.Name;
                        parameter = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                        Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));

                        IEdmCollectionTypeReference feedType = parameter.Type as IEdmCollectionTypeReference;
                        Contract.Assert(feedType != null);

                        ODataReader feedReader = reader.CreateFeedReader();
                        object feed = ODataEntityDeserializer.ReadEntryOrFeed(feedReader);
                        ODataFeedDeserializer feedDeserializer = (ODataFeedDeserializer)DeserializerProvider.GetEdmTypeDeserializer(feedType);

                        object result = feedDeserializer.ReadInline(feed, feedType, readContext);

                        IEdmTypeReference elementTypeReference = feedType.ElementType();
                        Contract.Assert(elementTypeReference.IsEntity());

                        IEnumerable enumerable = result as IEnumerable;
                        if (enumerable != null)
                        {
                            if (readContext.IsUntyped)
                            {
                                EdmEntityObjectCollection entityCollection = new EdmEntityObjectCollection(feedType);
                                foreach (EdmEntityObject entityObject in enumerable)
                                {
                                    entityCollection.Add(entityObject);
                                }

                                payload[parameterName] = entityCollection;
                            }
                            else
                            {
                                Type elementClrType = EdmLibHelpers.GetClrType(elementTypeReference, readContext.Model);
                                IEnumerable castedResult =
                                    _castMethodInfo.MakeGenericMethod(elementClrType)
                                        .Invoke(null, new[] { result }) as IEnumerable;
                                payload[parameterName] = castedResult;
                            }
                        }
                        break;
                }
            }

            return payload;
        }
Пример #26
0
        private static EdmEntityObjectCollection GetCustomers()
        {
            if (_untypedSimpleOpenCustormers != null)
            {
                return _untypedSimpleOpenCustormers;
            }
            EdmEntityType customerType = new EdmEntityType("NS", "UntypedSimpleOpenCustomer", null, false, true);
            customerType.AddKeys(customerType.AddStructuralProperty("CustomerId", EdmPrimitiveTypeKind.Int32));
            EdmEntityObject customer = new EdmEntityObject(customerType);
            customer.TrySetPropertyValue("CustomerId", 1);

            //Add Numbers primitive collection property
            customer.TrySetPropertyValue("DeclaredNumbers", new[] { 1, 2 });

            //Add Color, Colors enum(collection) property
            EdmEnumType colorType = new EdmEnumType("NS", "Color");
            colorType.AddMember(new EdmEnumMember(colorType, "Red", new EdmIntegerConstant(0)));

            EdmEnumObject color = new EdmEnumObject(colorType, "Red");
            EdmEnumObject color2 = new EdmEnumObject(colorType, "0");
            EdmEnumObject color3 = new EdmEnumObject(colorType, "Red");
            customer.TrySetPropertyValue("Color", color);

            List<IEdmEnumObject> colorList = new List<IEdmEnumObject>();
            colorList.Add(color);
            colorList.Add(color2);
            colorList.Add(color3);
            IEdmCollectionTypeReference enumCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(colorType.ToEdmTypeReference(false)));
            EdmEnumObjectCollection colors = new EdmEnumObjectCollection(enumCollectionType, colorList);
            customer.TrySetPropertyValue("Colors", colors);
            customer.TrySetPropertyValue("DeclaredColors", colors);

            //Add Addresses complex(collection) property 
            EdmComplexType addressType = new EdmComplexType("NS", "Address", null, false, true);
            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);

            EdmComplexObject address = new EdmComplexObject(addressType);
            address.TrySetPropertyValue("Street", "No1");
            EdmComplexObject address2 = new EdmComplexObject(addressType);
            address2.TrySetPropertyValue("Street", "No2");

            List<IEdmComplexObject> addressList = new List<IEdmComplexObject>();
            addressList.Add(address);
            addressList.Add(address2);
            IEdmCollectionTypeReference complexCollectionType = new EdmCollectionTypeReference(new EdmCollectionType(addressType.ToEdmTypeReference(false)));
            EdmComplexObjectCollection addresses = new EdmComplexObjectCollection(complexCollectionType, addressList);
            customer.TrySetPropertyValue("DeclaredAddresses", addresses);

            EdmEntityObjectCollection customers = new EdmEntityObjectCollection(new EdmCollectionTypeReference(new EdmCollectionType(customerType.ToEdmTypeReference(false))));
            customers.Add(customer);
            _untypedSimpleOpenCustormers = customers;
            return _untypedSimpleOpenCustormers;
        }
        public override object Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
        {
            if (messageReader == null)
            {
                throw Error.ArgumentNull("messageReader");
            }

            IEdmAction action = GetAction(readContext);

            Contract.Assert(action != null);

            // Create the correct resource type;
            Dictionary <string, object> payload;

            if (type == typeof(ODataActionParameters))
            {
                payload = new ODataActionParameters();
            }
            else
            {
                payload = new ODataUntypedActionParameters(action);
            }

            ODataParameterReader reader = messageReader.CreateODataParameterReader(action);

            while (reader.Read())
            {
                string parameterName             = null;
                IEdmOperationParameter parameter = null;

                switch (reader.State)
                {
                case ODataParameterReaderState.Value:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    // ODataLib protects against this but asserting just in case.
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                    if (parameter.Type.IsPrimitive())
                    {
                        payload[parameterName] = reader.Value;
                    }
                    else
                    {
                        ODataEdmTypeDeserializer deserializer = DeserializerProvider.GetEdmTypeDeserializer(parameter.Type);
                        payload[parameterName] = deserializer.ReadInline(reader.Value, parameter.Type, readContext);
                    }
                    break;

                case ODataParameterReaderState.Collection:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    // ODataLib protects against this but asserting just in case.
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));
                    IEdmCollectionTypeReference collectionType = parameter.Type as IEdmCollectionTypeReference;
                    Contract.Assert(collectionType != null);
                    ODataCollectionValue        value = ReadCollection(reader.CreateCollectionReader());
                    ODataCollectionDeserializer collectionDeserializer = (ODataCollectionDeserializer)DeserializerProvider.GetEdmTypeDeserializer(collectionType);
                    payload[parameterName] = collectionDeserializer.ReadInline(value, collectionType, readContext);
                    break;

                case ODataParameterReaderState.Entry:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));

                    IEdmEntityTypeReference entityTypeReference = parameter.Type as IEdmEntityTypeReference;
                    Contract.Assert(entityTypeReference != null);

                    ODataReader entryReader = reader.CreateEntryReader();
                    object      item        = ODataEntityDeserializer.ReadEntryOrFeed(entryReader);
                    var         savedProps  = new List <ODataProperty>();
                    if (item is ODataEntryWithNavigationLinks)
                    {
                        var obj = CreateDataObject(readContext.Model as DataObjectEdmModel, entityTypeReference, item as ODataEntryWithNavigationLinks, out Type objType);
                        payload[parameterName] = obj;
                        break;
                    }

                    ODataEntityDeserializer entityDeserializer = (ODataEntityDeserializer)DeserializerProvider.GetEdmTypeDeserializer(entityTypeReference);
                    payload[parameterName] = entityDeserializer.ReadInline(item, entityTypeReference, readContext);
                    break;

                case ODataParameterReaderState.Feed:
                    parameterName = reader.Name;
                    parameter     = action.Parameters.SingleOrDefault(p => p.Name == parameterName);
                    Contract.Assert(parameter != null, String.Format(CultureInfo.InvariantCulture, "Parameter '{0}' not found.", parameterName));

                    IEdmCollectionTypeReference feedType = parameter.Type as IEdmCollectionTypeReference;
                    Contract.Assert(feedType != null);

                    ODataReader          feedReader = reader.CreateFeedReader();
                    object               feed       = ODataEntityDeserializer.ReadEntryOrFeed(feedReader);
                    IEnumerable          enumerable;
                    ODataFeedWithEntries odataFeedWithEntries = feed as ODataFeedWithEntries;
                    if (odataFeedWithEntries != null)
                    {
                        List <DataObject> list = new List <DataObject>();
                        Type objType           = null;
                        foreach (ODataEntryWithNavigationLinks entry in odataFeedWithEntries.Entries)
                        {
                            list.Add(CreateDataObject(readContext.Model as DataObjectEdmModel, feedType.ElementType() as IEdmEntityTypeReference, entry, out objType));
                        }

                        IEnumerable castedResult =
                            _castMethodInfo.MakeGenericMethod(objType)
                            .Invoke(null, new[] { list }) as IEnumerable;
                        payload[parameterName] = castedResult;
                        break;
                    }

                    ODataFeedDeserializer feedDeserializer = (ODataFeedDeserializer)DeserializerProvider.GetEdmTypeDeserializer(feedType);

                    object result = feedDeserializer.ReadInline(feed, feedType, readContext);

                    IEdmTypeReference elementTypeReference = feedType.ElementType();
                    Contract.Assert(elementTypeReference.IsEntity());

                    enumerable = result as IEnumerable;
                    if (enumerable != null)
                    {
                        var  isUntypedProp = readContext.GetType().GetProperty("IsUntyped", BindingFlags.NonPublic | BindingFlags.Instance);
                        bool isUntyped     = (bool)isUntypedProp.GetValue(readContext, null);
                        if (isUntyped)
                        {
                            EdmEntityObjectCollection entityCollection = new EdmEntityObjectCollection(feedType);
                            foreach (EdmEntityObject entityObject in enumerable)
                            {
                                entityCollection.Add(entityObject);
                            }

                            payload[parameterName] = entityCollection;
                        }
                        else
                        {
                            Type        elementClrType = EdmLibHelpers.GetClrType(elementTypeReference, readContext.Model);
                            IEnumerable castedResult   =
                                _castMethodInfo.MakeGenericMethod(elementClrType)
                                .Invoke(null, new[] { result }) as IEnumerable;
                            payload[parameterName] = castedResult;
                        }
                    }
                    break;
                }
            }

            return(payload);
        }
        public ParseContext Parse(ODataUriParser parser, ParseContext parseContext)
        {
            var sourceEdmSetting = parseContext.EdmEntityTypeSettings.FirstOrDefault();

            // Get primary collection type and setup collection
            var collectionEntityTypeKey = parseContext.LatestStateDictionary
                                          .Keys.FirstOrDefault(p => p.Contains("collectionentitytype"));
            var entityRef     = (EdmEntityTypeReference)parseContext.LatestStateDictionary[collectionEntityTypeKey];
            var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
            var collection    = new EdmEntityObjectCollection(collectionRef);

            // Get orderby clause
            var orderByClause = parser.ParseOrderBy();

            bool isFirstIter = true;
            IEnumerable <IEdmEntityObject>                    resultStart    = parseContext.Result;
            IEnumerable <Dictionary <string, object> >        queryableStart = parseContext.QueryableSourceEntities;
            IOrderedEnumerable <IEdmEntityObject>             result         = null;
            IOrderedEnumerable <Dictionary <string, object> > queryable      = null;

            while (orderByClause != null)
            {
                // Get attribute name
                string attributeName = "";
                var    kind          = orderByClause.Expression.Kind;
                if (kind == QueryNodeKind.SingleValueOpenPropertyAccess)
                {
                    attributeName = ((SingleValueOpenPropertyAccessNode)orderByClause.Expression).Name;
                }
                else if (kind == QueryNodeKind.SingleValuePropertyAccess)
                {
                    attributeName = ((SingleValuePropertyAccessNode)orderByClause.Expression).Property.Name;
                }
                else
                {
                    throw new FeatureNotSupportedException(OrderByParser, $"QueryNodeKind: {kind} Not Supported");
                }
                // Check if attribute name in model
                var typeSetting = sourceEdmSetting.Properties.FirstOrDefault(predicate => predicate.PropertyName == attributeName);
                // Get direction
                var direction = orderByClause.Direction.ToString();
                // Perform ordering
                Func <IEdmEntityObject, object>            resultExpression    = item => GetPropertyValue(item, attributeName);
                Func <Dictionary <string, object>, object> queryableExpression = item => item[attributeName];
                if (string.Compare(direction, "Ascending") == 0)
                {
                    result = (isFirstIter) ? resultStart.OrderBy(resultExpression) :
                             result.ThenBy(resultExpression);
                    queryable = (isFirstIter) ? queryableStart.OrderBy(queryableExpression) :
                                queryable.ThenBy(queryableExpression);
                }
                else
                {
                    result = (isFirstIter) ? resultStart.OrderByDescending(resultExpression) :
                             result.ThenByDescending(resultExpression);
                    queryable = (isFirstIter) ? queryableStart.OrderByDescending(queryableExpression) :
                                queryable.ThenByDescending(queryableExpression);
                }
                isFirstIter = false;
                // Go to next ordering clause
                orderByClause = orderByClause.ThenBy;
            }
            // Create collection
            foreach (var entity in result)
            {
                collection.Add(entity);
            }

            var targetParseContext = new ParseContext
            {
                Result = collection,
                QueryableSourceEntities = queryable,
                Model = parseContext.Model,
                EdmEntityTypeSettings = parseContext.EdmEntityTypeSettings,
                LatestStateDictionary = parseContext.LatestStateDictionary
            };

            return(targetParseContext);
        }
            internal static object ConvertFeed(ODataMessageReader oDataMessageReader, IEdmTypeReference edmTypeReference, ODataDeserializerContext readContext)
            {
                IEdmCollectionTypeReference collectionType = edmTypeReference.AsCollection();

                EdmEntitySet tempEntitySet = new EdmEntitySet(readContext.Model.EntityContainer, "temp",
                    collectionType.ElementType().AsEntity().EntityDefinition());

                ODataReader odataReader = oDataMessageReader.CreateODataFeedReader(tempEntitySet,
                    collectionType.ElementType().AsEntity().EntityDefinition());
                ODataFeedWithEntries feed =
                    ODataEntityDeserializer.ReadEntryOrFeed(odataReader) as ODataFeedWithEntries;

                ODataFeedDeserializer feedDeserializer =
                    (ODataFeedDeserializer)DeserializerProvider.GetEdmTypeDeserializer(collectionType);

                object result = feedDeserializer.ReadInline(feed, collectionType, readContext);
                IEnumerable enumerable = result as IEnumerable;
                if (enumerable != null)
                {
                    IEnumerable newEnumerable = CovertFeedIds(enumerable, feed, collectionType, readContext);
                    if (readContext.IsUntyped)
                    {
                        EdmEntityObjectCollection entityCollection =
                            new EdmEntityObjectCollection(collectionType);
                        foreach (EdmEntityObject entity in newEnumerable)
                        {
                            entityCollection.Add(entity);
                        }

                        return entityCollection;
                    }
                    else
                    {
                        IEdmTypeReference elementTypeReference = collectionType.ElementType();

                        Type elementClrType = EdmLibHelpers.GetClrType(elementTypeReference,
                            readContext.Model);
                        IEnumerable castedResult =
                            CastMethodInfo.MakeGenericMethod(elementClrType)
                                .Invoke(null, new object[] { newEnumerable }) as IEnumerable;
                        return castedResult;
                    }
                }

                return null;
            }
Пример #30
0
        public ParseContext Parse(ODataUriParser parser, ParseContext sourceParseContext)
        {
            SourceParseContext = sourceParseContext;
            var targetParseContext            = new ParseContext();
            var targetQueryableSourceEntities = new List <Dictionary <string, object> >();
            var sourceEdmSetting = sourceParseContext.EdmEntityTypeSettings.FirstOrDefault();
            var targetEdmSetting = new EdmEntityTypeSettings()
            {
                RouteName  = "Groups",
                Personas   = sourceEdmSetting.Personas,
                Properties = new List <EdmEntityTypePropertySetting>()
            };
            var latestStateDictionary = new Dictionary <string, object>();

            var edmEntityType = new EdmEntityType(EdmNamespaceName, "Groups");
            //This may only be used if we client uses Custom.List as aggregation
            var edmComplexType    = new EdmComplexType(EdmNamespaceName, "List");
            var aggregatePropList = new Dictionary <string, AggregateExpression>();
            var applyClause       = parser.ParseApply();

            //We support only single transformation
            if (applyClause.Transformations.Count() > 1)
            {
                throw new FeatureNotSupportedException(ApplyParser, "Multiple Transformations");
            }

            if (applyClause.Transformations.Count() == 0)
            {
                throw new FeatureNotSupportedException(ApplyParser, "Zero Transformations");
            }

            foreach (var transformation in applyClause.Transformations)
            {
                if (transformation.Kind == TransformationNodeKind.GroupBy)
                {
                    var transform = (GroupByTransformationNode)transformation;

                    ///Add all the grouping properties
                    foreach (var groupingProperty in transform.GroupingProperties)
                    {
                        var sourceProperty = sourceEdmSetting.Properties.FirstOrDefault(predicate => predicate.PropertyName.Equals(groupingProperty.Name));

                        edmEntityType.AddStructuralProperty(groupingProperty.Name, groupingProperty.TypeReference.PrimitiveKind());

                        targetEdmSetting.Properties.Add(new EdmEntityTypePropertySetting
                        {
                            PropertyName = sourceProperty.PropertyName,
                            PropertyType = sourceProperty.PropertyType,
                            IsNullable   = sourceProperty.IsNullable
                        });
                    }


                    //Add all the aggregate properties
                    if (transform.ChildTransformations != null)
                    {
                        var aggregationProperties = (AggregateTransformationNode)transform.ChildTransformations;
                        AddAggregationPropertiesToModel(aggregationProperties
                                                        , sourceEdmSetting, edmEntityType, aggregatePropList, targetEdmSetting
                                                        , edmComplexType, latestStateDictionary);
                    }

                    //Register these dynamic types to model
                    sourceParseContext.Model.AddElement(edmEntityType);
                    sourceParseContext.Model.AddElement(edmComplexType);
                    ((EdmEntityContainer)sourceParseContext.Model.EntityContainer).AddEntitySet("Groups", edmEntityType);

                    var fields = transform.GroupingProperties.Select(p => p.Name).ToList();
                    var groups = sourceParseContext.QueryableSourceEntities
                                 .GroupBy(r => fields.ToDictionary(c => c, c => r[c]), new CustomEqualityComparer());

                    var entityRef     = new EdmEntityTypeReference(edmEntityType, true);
                    var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
                    var collection    = new EdmEntityObjectCollection(collectionRef);
                    latestStateDictionary.Add(RequestFilterConstants.GetEntityTypeKeyName(ApplyParser, StepIndex), entityRef);
                    foreach (var group in groups)
                    {
                        var targetQueryableDictionary = new Dictionary <string, object>();
                        var obj = new EdmEntityObject(edmEntityType);
                        foreach (var prop in fields)
                        {
                            var value = group.Key[prop];
                            obj.TrySetPropertyValue(prop, value);
                            targetQueryableDictionary.Add(prop, value);
                        }
                        AddAggregationPropertyValuesToModel(targetQueryableDictionary, obj, group, edmComplexType, aggregatePropList);
                        collection.Add(obj);
                        targetQueryableSourceEntities.Add(targetQueryableDictionary);
                    }
                    targetParseContext.Result = collection;
                    targetParseContext.Model  = sourceParseContext.Model;
                    targetParseContext.QueryableSourceEntities = targetQueryableSourceEntities;
                    targetParseContext.EdmEntityTypeSettings   = new List <EdmEntityTypeSettings> {
                        targetEdmSetting
                    };
                    targetParseContext.LatestStateDictionary = latestStateDictionary;
                    return(targetParseContext);
                }
                else if (transformation.Kind == TransformationNodeKind.Aggregate)
                {
                    var targetQueryableDictionary = new Dictionary <string, object>();
                    var obj = new EdmEntityObject(edmEntityType);
                    var aggregationProperties = (AggregateTransformationNode)transformation;
                    AddAggregationPropertiesToModel(aggregationProperties
                                                    , sourceEdmSetting, edmEntityType, aggregatePropList, targetEdmSetting
                                                    , edmComplexType, latestStateDictionary);
                    //Register these dynamic types to model
                    sourceParseContext.Model.AddElement(edmEntityType);
                    sourceParseContext.Model.AddElement(edmComplexType);
                    var entityRef     = new EdmEntityTypeReference(edmEntityType, true);
                    var collectionRef = new EdmCollectionTypeReference(new EdmCollectionType(entityRef));
                    var collection    = new EdmEntityObjectCollection(collectionRef);
                    latestStateDictionary.Add(RequestFilterConstants.GetEntityTypeKeyName(ApplyParser, StepIndex), entityRef);
                    AddAggregationPropertyValuesToModel(targetQueryableDictionary, obj, sourceParseContext.QueryableSourceEntities, edmComplexType, aggregatePropList);
                    collection.Add(obj);
                    targetQueryableSourceEntities.Add(targetQueryableDictionary);
                    targetParseContext.Result = collection;
                    targetParseContext.Model  = sourceParseContext.Model;
                    targetParseContext.QueryableSourceEntities = targetQueryableSourceEntities;
                    targetParseContext.EdmEntityTypeSettings   = new List <EdmEntityTypeSettings> {
                        targetEdmSetting
                    };
                    targetParseContext.LatestStateDictionary = latestStateDictionary;
                    return(targetParseContext);
                }
                else
                {
                    throw new FeatureNotSupportedException(ApplyParser, $"Transformation Kind {transformation.Kind} is not supported");
                }
            }
            throw new FeatureNotSupportedException(ApplyParser, "Invalid Apply Clause");
        }