public IEnumerable<Customer> GetCustomers(ODataQueryOptions<Customer> queryOptions)
        {
            // validate the query.
            queryOptions.Validate(_validationSettings);

            // Apply the query.
            IQuery query = queryOptions.ApplyTo(_db);

            Console.WriteLine("Executing HQL:\t" + query);
            Console.WriteLine();

            return query.List<Customer>();
        }
        // GET: odata/Images
        public PageResult<Image> GetImages(ODataQueryOptions<Image> options)
        {
            ODataQuerySettings settings = new ODataQuerySettings()
            {
                PageSize = CollectionOfWorkers.SizeOfPage
            };

            IQueryable results = options.ApplyTo(db.Images.AsQueryable(), settings);

            return new PageResult<Image>(
                results as IEnumerable<Image>,
                null,
                db.Images.Count());
        }
Example #3
0
 public IHttpActionResult Get(ODataQueryOptions<ODataQueryOptionTest_EntityModel> queryOptions)
 {
     // Don't apply Filter and Expand, but apply Select.
     var appliedQueryOptions = AllowedQueryOptions.Skip | AllowedQueryOptions.Filter | AllowedQueryOptions.Expand;
     var res = queryOptions.ApplyTo(_entityModels, appliedQueryOptions);
     return Ok(res.AsQueryable());
 }
        public IHttpActionResult Get([FromODataUri] string key, ODataQueryOptions<Person> queryOptions)
        {
            IEnumerable<Person> appliedPeople = TripPinSvcDataSource.Instance.People.Where(item => item.UserName == key);

            if (appliedPeople.Count() == 0)
            {
                return NotFound();
            }

            // TODO : Bug https://aspnetwebstack.codeplex.com/workitem/2033, should get from ODataQueryOptions
            if (Request.Headers.IfNoneMatch.Count > 0)
            {
                if (Request.Headers.IfNoneMatch.ElementAt(0).Tag.Equals("*"))
                {
                    return StatusCode(HttpStatusCode.NotModified);
                }
                else
                {
                    appliedPeople = queryOptions.IfNoneMatch.ApplyTo(appliedPeople.AsQueryable()).Cast<Person>();
                }
            }

            if (appliedPeople.Count() == 0)
            {
                return StatusCode(HttpStatusCode.NotModified);
            }
            else
            {
                return Ok(appliedPeople.Single());
            }
        }
 public IHttpActionResult Get(int key, ODataQueryOptions<Customer> options)
 {
     IQueryable<Customer> customerByIdQuery = _context.Customers.Where(c => c.Id == key);
     if (options.IfNoneMatch != null)
     {
         IQueryable<Customer> customerQuery = options.IfNoneMatch.ApplyTo(customerByIdQuery) as IQueryable<Customer>;
         if (!customerQuery.Any())
         {
             // The entity has the same ETag as the one in the If-None-Match header of the request,
             // so it hasn't been modified since it was retrieved the first time.
             return StatusCode(HttpStatusCode.NotModified);
         }
         else
         {
             // The entity has a different ETag than the one specified in the If-None-Match header of the request,
             // so we return the entity.
             return Ok(SingleResult<Customer>.Create(customerByIdQuery));
         }
     }
     else
     {
         // The request didn't contain any ETag, so we return the entity.
         return Ok(SingleResult<Customer>.Create(customerByIdQuery));
     }
 }
        // Pass ODataQueryOptions as parameter, and call validation manually
        public IHttpActionResult GetFromManager(ODataQueryOptions<Manager> queryOptions)
        {
            if (queryOptions.SelectExpand != null)
            {
                queryOptions.SelectExpand.LevelsMaxLiteralExpansionDepth = 5;
            }

            var validationSettings = new ODataValidationSettings { MaxExpansionDepth = 5 };

            try
            {
                queryOptions.Validate(validationSettings);
            }
            catch (ODataException e)
            {
                var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
                responseMessage.Content = new StringContent(
                    string.Format("The query specified in the URI is not valid. {0}", e.Message));
                return ResponseMessage(responseMessage);
            }

            var querySettings = new ODataQuerySettings();
            var result = queryOptions.ApplyTo(_employees.OfType<Manager>().AsQueryable(), querySettings).AsQueryable();
            return Ok(result, result.GetType());
        }
        /// <summary>
        /// Validates the specified query options.
        /// </summary>
        /// <param name="queryOptions">The query options.</param>
        /// <param name="validationSettings">The validation settings.</param>
        /// <exception cref="ODataException">Thrown if the validation fails.</exception>
        internal static void Validate(ODataQueryOptions queryOptions, ODataValidationSettings validationSettings)
        {
            if (queryOptions.Filter != null)
            {
                if ((validationSettings.AllowedQueryOptions & AllowedQueryOptions.Filter) != AllowedQueryOptions.Filter)
                {
                    throw new ODataException(Messages.FilterQueryOptionNotSupported);
                }

                ValidateFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateStringFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateDateFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateMathFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateLogicalOperators(queryOptions.Filter.RawValue, validationSettings);
                ValidateArithmeticOperators(queryOptions.Filter.RawValue, validationSettings);
            }

            if (queryOptions.RawValues.Expand != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Expand) != AllowedQueryOptions.Expand)
            {
                throw new ODataException(Messages.ExpandQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Format != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Format) != AllowedQueryOptions.Format)
            {
                throw new ODataException(Messages.FormatQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.InlineCount != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.InlineCount) != AllowedQueryOptions.InlineCount)
            {
                throw new ODataException(Messages.InlineCountQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.OrderBy != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.OrderBy) != AllowedQueryOptions.OrderBy)
            {
                throw new ODataException(Messages.OrderByQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Select != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Select) != AllowedQueryOptions.Select)
            {
                throw new ODataException(Messages.SelectQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Skip != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Skip) != AllowedQueryOptions.Skip)
            {
                throw new ODataException(Messages.SkipQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Top != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Top) != AllowedQueryOptions.Top)
            {
                throw new ODataException(Messages.TopQueryOptionNotSupported);
            }
        }
Example #8
0
        public IHttpActionResult GetDiamondImport(ODataQueryOptions<ProductDiamondImport> options)
        {
            var imports = this.database.DiamondImports.AsQueryable();
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("Products")) imports = imports.Include(s => s.Products);

            return Ok(imports);
        }
Example #9
0
        public Task<IHttpActionResult> GetDiamondImport([FromODataUri] Guid id, ODataQueryOptions<ProductDiamondImport> options)
        {
            var imports = this.database.DiamondImports.Where(s => s.Id == id);
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("Products")) imports = imports.Include(s => s.Products);

            return GetODataSingleAsync(imports, options);
        }
        // Override this method to plug in our custom validator.
        public override void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)
        {
            IEdmModel model = queryOptions.Context.Model;
            IPrincipal principal = request.GetRequestContext().Principal;

            queryOptions.Validator = new AuthorizedRolesQueryValidator(model, principal);
            base.ValidateQuery(request, queryOptions);
        }
Example #11
0
		public virtual object ApplyQueryOptions(object value, HttpRequest request, ActionDescriptor actionDescriptor, AssembliesResolver assembliesResolver)
		{
			var elementClrType = value is IEnumerable
				? TypeHelper.GetImplementedIEnumerableType(value.GetType())
				: value.GetType();

			var model = request.ODataProperties().Model;
			if (model == null)
			{
				throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull);
			}

			var queryContext = new ODataQueryContext(
				model,
				elementClrType,
				assembliesResolver,
				request.ODataProperties().Path
				);

			var queryOptions = new ODataQueryOptions(queryContext, request, assembliesResolver);

			var enumerable = value as IEnumerable;
			if (enumerable == null)
			{
				// response is single entity.
				return value;
			}

			// response is a collection.
			var query = (value as IQueryable) ?? enumerable.AsQueryable();

			query = queryOptions.ApplyTo(query,
				new ODataQuerySettings
				{
					// TODO: If we are using SQL, set this to false
					// otherwise if it is entities in code then
					// set it to true
					HandleNullPropagation = 
					//HandleNullPropagationOption.True
					HandleNullPropagationOptionHelper.GetDefaultHandleNullPropagationOption(query),
					PageSize = actionDescriptor.PageSize(),
					SearchDerivedTypeWhenAutoExpand = true
				},
				AllowedQueryOptions.None);
			// Determine if this result should be a single entity
			
			if (ODataCountMediaTypeMapping.IsCountRequest(request))
			{
				long? count = request.ODataProperties().TotalCount;

				if (count.HasValue)
				{
					// Return the count value if it is a $count request.
					return count.Value;
				}
			}
			return query;
		}
Example #12
0
 public override void ValidateQuery(HttpRequestMessage request,
     ODataQueryOptions queryOptions)
 {
     if (queryOptions.OrderBy != null)
     {
         queryOptions.OrderBy.Validator = new MyOrderByValidator();
     }
     base.ValidateQuery(request, queryOptions);
 }
Example #13
0
        public IHttpActionResult Get(ODataQueryOptions<SaleHeader> options)
        {
            var sales = this.database.SaleHeaders.AsQueryable();
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("SaleLineItems")) sales = sales.Include(s => s.Items);
            if (expands.Contains("CustomerContacts")) sales = sales.Include(s => s.CustomerContacts);

            return Ok(sales);
        }
Example #14
0
        public Task<IHttpActionResult> Get([FromODataUri] Guid id, ODataQueryOptions<SaleHeader> options)
        {
            var sales = this.database.SaleHeaders.Where(s => s.Id == id);
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("SaleLineItems")) sales = sales.Include(s => s.Items);
            if (expands.Contains("CustomerContacts")) sales = sales.Include(s => s.CustomerContacts);

            return GetODataSingleAsync(sales, options);
        }
        // GET: odata/Orders(5)
        public IHttpActionResult GetOrder([FromODataUri] int key, ODataQueryOptions<Order> queryOptions)
        {
            if (key == 1)
            {
                return Ok(_someOrder);
            }

            return NotFound();
        }
 public IHttpActionResult GetBranchesCount(ODataQueryOptions<Office> options)
 {
     IQueryable<Office> eligibleBranches = MonstersInc.Branches.AsQueryable();
     if (options.Filter != null)
     {
         eligibleBranches = options.Filter.ApplyTo(eligibleBranches, new ODataQuerySettings()).Cast<Office>();
     }
     return Ok(eligibleBranches.Count());
 }
 /// <summary>
 /// Validates the specified query options.
 /// </summary>
 /// <param name="queryOptions">The query options.</param>
 /// <exception cref="ODataException">Thrown if the validation fails.</exception>
 internal static void Validate(ODataQueryOptions queryOptions)
 {
     if (queryOptions.Skip != null)
     {
         if (queryOptions.Skip.Value < 0)
         {
             throw new ODataException(Messages.SkipRawValueInvalid);
         }
     }
 }
        public void Ctor_SuccedsIfEntityTypesMatch()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");

            ODataQueryContext context = new ODataQueryContext(builder.GetEdmModel(), typeof(Customer));

            ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, new HttpRequestMessage(HttpMethod.Get, "http://server/?$top=10"));
            Assert.Equal("10", query.Top.RawValue);
        }
        public IQueryable<SkaterStat> GetAllStats(ODataQueryOptions queryOptions)
        {
            //assume the client sends top and skip
            var filtered = _stats.Skip(queryOptions.Skip.Value);

            if (queryOptions.Top.Value > 0)
            {
                filtered = filtered.Take(queryOptions.Top.Value);
            }

            return filtered.AsQueryable();
        }
 public async Task<IHttpActionResult> Put(int key, Customer customer, ODataQueryOptions<Customer> options)
 {
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }
     if (!(key == customer.Id))
     {
         return BadRequest("The customer Id must match the key in the URI");
     }
     if (options.IfMatch != null)
     {
         if (!_context.Customers.Where(c => c.Id == key).Any())
         {
             // The entity doesn't exist on the database and as the request contains an If-Match header we don't
             // insert the entity instead (No UPSERT behavior if the If-Match header is present).
             return NotFound();
         }
         else if (!((IQueryable<Customer>)options.IfMatch.ApplyTo(_context.Customers.Where(c => c.Id == key))).Any())
         {
             // The ETag of the entity doesn't match the value sent on the If-Match header, so the entity has
             // been modified by a third party between the entity retrieval and update..
             return StatusCode(HttpStatusCode.PreconditionFailed);
         }
         else
         {
             // The entity exists in the database and the ETag of the entity matches the value on the If-Match 
             // header, so we update the entity.
             _context.Entry(customer).State = EntityState.Modified;
             await _context.SaveChangesAsync();
             return Ok(customer);
         }
     }
     else
     {
         if (!_context.Customers.Where(c => c.Id == key).Any())
         {
             // The request didn't contain any If-Match header and the entity doesn't exist on the database, so
             // we create a new one. For more details see the section 11.4.4 of the OData v4.0 specification.
             _context.Customers.Add(customer);
             await _context.SaveChangesAsync();
             return base.Created(customer);
         }
         else
         {
             // the request didn't contain any If-Match header and the entity exists on the database, so we
             // update it's value.
             _context.Entry(customer).State = EntityState.Modified;
             await _context.SaveChangesAsync();
             return Ok(customer);
         }
     }
 }
        // GET: odata/Products
        public IHttpActionResult GetProducts(ODataQueryOptions<Product> queryOptions)
        {
            // validate the query.
            try
            {
                queryOptions.Validate(_validationSettings);
            }
            catch (ODataException ex)
            {
                return BadRequest(ex.Message);
            }

            // return Ok<IEnumerable<Product>>(products);
            return StatusCode(HttpStatusCode.NotImplemented);
        }
Example #22
0
 public IHttpActionResult Get(ODataQueryOptions<AttributedSelectExpandCustomer> options)
 {
     IQueryable result = options.ApplyTo(Enumerable.Range(1, 10).Select(i => new AttributedSelectExpandCustomer
     {
         Id = i,
         Name = "Name " + i,
         Orders = Enumerable.Range(1, 10).Select(j => new AttributedSelectExpandOrder
         {
             CustomerName = "Customer Name" + j,
             Id = j,
             Total = i * j
         }).ToList()
     }).AsQueryable());
     return Ok(result);
 }
        public IHttpActionResult GetShipAddressesCount(int key, ODataQueryOptions<Address> options)
        {
            Customer customer = customers.SingleOrDefault(c => c.Id == key);
            if (customer == null)
            {
                return NotFound();
            }

            IQueryable<Address> eligibleAddresses = customer.ShipAddresses.AsQueryable();
            if (options.Filter != null)
            {
                eligibleAddresses = options.Filter.ApplyTo(eligibleAddresses, new ODataQuerySettings()).Cast<Address>();
            }
            return Ok(eligibleAddresses.Count());
        }
        // GET: odata/Orders(5)
        public IHttpActionResult GetOrder([FromODataUri] int key, ODataQueryOptions<Order> queryOptions)
        {
            // validate the query.
            try
            {
                queryOptions.Validate(_validationSettings);
            }
            catch (ODataException ex)
            {
                return BadRequest(ex.Message);
            }

            // return Ok<Order>(order);
            return StatusCode(HttpStatusCode.NotImplemented);
        }
Example #25
0
        public IHttpActionResult GetPlayers(ODataQueryOptions<Player> queryOptions)
        {
            // validate the query.
            try
            {
                queryOptions.Validate(_validationSettings);
            }
            catch (ODataException ex)
            {
                return BadRequest(ex.Message);
            }

            var players = _cricketContext.Players;
            return Ok<IEnumerable<Player>>(players);
        }
Example #26
0
        // GET: Domains
        public IEnumerable<DomainsProjection> Get(ODataQueryOptions<DomainsProjection> options)
        {
            var querySettings = new ODataQuerySettings()
            {
                EnableConstantParameterization = true,
                EnsureStableOrdering = true
            };

            var raw = GetDomains().OrderBy(d => d.HostName);
            var total = options.Filter == null ? raw.Count() : options.Filter.ApplyTo(raw, querySettings).Count();
            var res = (IQueryable<DomainsProjection>) options.ApplyTo(raw, querySettings);

            return new PageResult<DomainsProjection>(res, options.GetNextLink(total), total);

            //return GetDomains().ToArray();
        }
        public void ValidateAllowOrderBy()
        {
            // Arrange
            HttpRequestMessage message = new HttpRequestMessage(
                HttpMethod.Get,
                new Uri("http://localhost/?$orderby=Name")
            );
            ODataQueryOptions option = new ODataQueryOptions(_context, message);
            ODataValidationSettings settings = new ODataValidationSettings()
            {
                AllowedQueryOptions = AllowedQueryOptions.OrderBy
            };

            // Act & Assert
            Assert.DoesNotThrow(() => _validator.Validate(option, settings));
        }
        public void Validate_DoesNotThrow_ForAllowedQueryOptions(string queryOptionName, string queryValue, AllowedQueryOptions queryOption)
        {
            // Arrange
            HttpRequestMessage message = new HttpRequestMessage(
                HttpMethod.Get,
                new Uri("http://localhost/?$" + queryOptionName + "=" + queryValue)
            );
            ODataQueryOptions option = new ODataQueryOptions(_context, message);
            ODataValidationSettings settings = new ODataValidationSettings()
            {
                AllowedQueryOptions = queryOption
            };

            // Act & Assert
            Assert.DoesNotThrow(() => _validator.Validate(option, settings));
        }
        public void ValidateDisallowFilter()
        {
            // Arrange
            HttpRequestMessage message = new HttpRequestMessage(
                HttpMethod.Get,
                new Uri("http://localhost/?$filter=Name eq 'abc'")
            );
            ODataQueryOptions option = new ODataQueryOptions(_context, message);
            ODataValidationSettings settings = new ODataValidationSettings()
            {
                AllowedQueryOptions = AllowedQueryOptions.OrderBy
            };

            // Act & Assert
             Assert.Throws<ODataException>(() => _validator.Validate(option, settings),
                 "Query option 'Filter' is not allowed. To allow it, try setting the 'AllowedQueryOptions' property on QueryableAttribute or QueryValidationSettings.");
        }
Example #30
0
        public IQueryable <LicensePlate> Get(ODataQueryOptions <LicensePlate> queryOptions)
        {
            var res = GetQueryable(queryOptions);

            return(res);
        }
 internal static string GetValidationFailedMessage <T>(ODataQueryOptions <T> options)
 {
     return($"A query with \"{ODataQueryFilter.ODataOptionsMap(options)}\" set of operators is not supported. Please refer to : https://github.com/NuGet/Home/wiki/Filter-OData-query-requests for additional information.");
 }
Example #32
0
 public IHttpActionResult HandleQuery <OriginType, TResult>(IQueryable <OriginType> query, ODataQueryOptions <OriginType> queryOptions)
 {
     return(base.HandleQuery <OriginType, TResult>(query, queryOptions));
 }
Example #33
0
 public PageResult <RetType> HandlePageResult <OriginType, RetType>(IQueryable <OriginType> query, ODataQueryOptions <OriginType> queryOptions)
 {
     return(base.HandlePageResult <OriginType, RetType>(query, queryOptions));
 }
Example #34
0
 // GET api/Default1
 public Task <IEnumerable <Person> > GetAllPersons(ODataQueryOptions query)
 {
     return(QueryAsync(query));
 }
 public IEnumerable <ProductDTO> GetProductsByEntityOptions(ODataQueryOptions <ProductDTO> options)
 {
     var filter = options.GetFilter();
     // Here the type of filter variable is Expression<Func<ProductDTO, bool>> as desired
     // The rest ...
 }
Example #36
0
 public IActionResult Get(int key, ODataQueryOptions <Order> options) =>
 Ok(new Order()
 {
     Id = key, Customer = "Bill Mei"
 });
Example #37
0
 public PageResult <PermissionDto> GetPermissions(ODataQueryOptions <Permission> options)
 {
     return(_permissionService.GetAllAsync(options));
 }
Example #38
0
        public async Task <IQueryResult <T> > GetAllAsync(Expression <Func <T, bool> > filter, ODataQueryOptions <T> queryOptions = null, IEnumerable <string> includeProperties = null)
        {
            IQueryable <T> query = entities.AsQueryable();

            if (includeProperties != null)
            {
                foreach (string include in includeProperties)
                {
                    query = query.Include(include);
                }
            }
            query = query.Where(filter);
            query = queryOptions.ApplyTo(query) as IQueryable <T>;
            PageInfo pageInfo = null;

            if (queryOptions != null)
            {
                long total = await entities.AsQueryable().LongCountAsync();

                if (queryOptions.Top?.Value > 0)
                {
                    pageInfo = new PageInfo(total, queryOptions?.Skip?.Value, queryOptions?.Top?.Value);
                }
            }
            IEnumerable <T> data = (await query.ToListAsync()).AsEnumerable();

            return(new QueryResult <T>(data, pageInfo));
        }
        public async Task <ActionResult <List <ODataUpdateViewModel> > > List(string culture, ODataQueryOptions <MixAttributeSetData> queryOptions)
        {
            var result = await base.GetListAsync <ODataUpdateViewModel>(queryOptions);

            return(Ok(result));
        }
        internal static async Task WriteToStreamAsync(
            Type type,
            object value,
            IEdmModel model,
            ODataVersion version,
            Uri baseAddress,
            MediaTypeHeaderValue contentType,
            HttpRequest request,
            IHeaderDictionary requestHeaders,
            IODataSerializerProvider serializerProvider)
        {
            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
            }

            IODataSerializer serializer = GetSerializer(type, value, request, serializerProvider);

            ODataPath            path = request.ODataFeature().Path;
            IEdmNavigationSource targetNavigationSource = GetTargetNavigationSource(path, model);
            HttpResponse         response = request.HttpContext.Response;

            // serialize a response
            string preferHeader     = RequestPreferenceHelpers.GetRequestPreferHeader(requestHeaders);
            string annotationFilter = null;

            if (!string.IsNullOrEmpty(preferHeader))
            {
                ODataMessageWrapper messageWrapper = ODataMessageWrapperHelper.Create(response.Body, response.Headers);
                messageWrapper.SetHeader(RequestPreferenceHelpers.PreferHeaderName, preferHeader);
                annotationFilter = messageWrapper.PreferHeader().AnnotationFilter;
            }

            IODataResponseMessageAsync responseMessage = ODataMessageWrapperHelper.Create(new StreamWrapper(response.Body), response.Headers, request.GetRouteServices());

            if (annotationFilter != null)
            {
                responseMessage.PreferenceAppliedHeader().AnnotationFilter = annotationFilter;
            }

            ODataMessageWriterSettings writerSettings = request.GetWriterSettings();

            writerSettings.BaseUri     = baseAddress;
            writerSettings.Version     = version;
            writerSettings.Validations = writerSettings.Validations & ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;

            string metadataLink = request.CreateODataLink(MetadataSegment.Instance);

            if (metadataLink == null)
            {
                throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
            }

            // Set this variable if the SelectExpandClause is different from the processed clause on the Query options
            SelectExpandClause selectExpandDifferentFromQueryOptions = null;
            ODataQueryOptions  queryOptions = request.GetQueryOptions();
            SelectExpandClause processedSelectExpandClause = request.ODataFeature().SelectExpandClause;

            if (queryOptions != null && queryOptions.SelectExpand != null)
            {
                if (queryOptions.SelectExpand.ProcessedSelectExpandClause != processedSelectExpandClause)
                {
                    selectExpandDifferentFromQueryOptions = processedSelectExpandClause;
                }
            }
            else if (processedSelectExpandClause != null)
            {
                selectExpandDifferentFromQueryOptions = processedSelectExpandClause;
            }

            writerSettings.ODataUri = new ODataUri
            {
                ServiceRoot = baseAddress,

                // TODO: 1604 Convert webapi.odata's ODataPath to ODL's ODataPath, or use ODL's ODataPath.
                SelectAndExpand = processedSelectExpandClause,
                Apply           = request.ODataFeature().ApplyClause,
                Path            = path
            };

            ODataMetadataLevel metadataLevel = ODataMetadataLevel.Minimal;

            if (contentType != null)
            {
                IEnumerable <KeyValuePair <string, string> > parameters =
                    contentType.Parameters.Select(val => new KeyValuePair <string, string>(val.Name.ToString(),
                                                                                           val.Value.ToString()));
                metadataLevel = ODataMediaTypes.GetMetadataLevel(contentType.MediaType.ToString(), parameters);
            }

            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
            {
                ODataSerializerContext writeContext = BuildSerializerContext(request);
                writeContext.NavigationSource = targetNavigationSource;
                writeContext.Model            = model;
                writeContext.RootElementName  = GetRootElementName(path) ?? "root";
                writeContext.SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.ResourceSet;
                writeContext.Path          = path;
                writeContext.MetadataLevel = metadataLevel;
                writeContext.QueryOptions  = queryOptions;
                writeContext.SetComputedProperties(queryOptions?.Compute?.ComputeClause);

                //Set the SelectExpandClause on the context if it was explicitly specified.
                if (selectExpandDifferentFromQueryOptions != null)
                {
                    writeContext.SelectExpandClause = selectExpandDifferentFromQueryOptions;
                }

                await serializer.WriteObjectAsync(value, type, messageWriter, writeContext).ConfigureAwait(false);
            }
        }
Example #41
0
 public SqlQueryBuilder(ODataQueryOptions queryOptions)
 {
     _queryOptions  = queryOptions;
     _edmEntityType = queryOptions.Context.ElementType as EdmEntityType;
 }
Example #42
0
 public IActionResult NewHires(DateTime since, ODataQueryOptions <Person> options) => Get(options);
Example #43
0
 public IActionResult Get(ODataQueryOptions <Order> options) =>
 Ok(new[] { new Order()
            {
                Id = 1, Customer = "Bill Mei"
            } });
Example #44
0
        public async Task <IActionResult> OData(ODataQueryOptions <DeveloperDto> oDataQuery)
        {
            var edmModel     = EdmModelConfig.GetEdmModel();
            var edmEntitySet = edmModel.FindDeclaredEntitySet(nameof(Developer));

            var context = new ODataQueryContext(edmModel, typeof(Developer), oDataQuery.Context.Path);
            var edmType = context.ElementType;

            var parameters = new Dictionary <string, string>();

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.Filter))
            {
                parameters.Add("$filter", oDataQuery.RawValues.Filter);
            }

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.Expand))
            {
                parameters.Add("$expand", oDataQuery.RawValues.Expand);
            }

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.OrderBy))
            {
                parameters.Add("$orderby", oDataQuery.RawValues.OrderBy);
            }

            var parser = new ODataQueryOptionParser(edmModel, edmType, edmEntitySet, parameters);

            var queryable = (IQueryable <Developer>)_databaseContext.Developer;

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.Filter))
            {
                var filter = new FilterQueryOption(oDataQuery.RawValues.Filter, context, parser);
                queryable = (IQueryable <Developer>)filter.ApplyTo(queryable, new ODataQuerySettings());
            }

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.OrderBy))
            {
                var orderBy = new OrderByQueryOption(oDataQuery.RawValues.OrderBy, context, parser);
                queryable = orderBy.ApplyTo(queryable, new ODataQuerySettings());
            }

            IQueryable <object> expandableQueryable = null;

            if (!string.IsNullOrWhiteSpace(oDataQuery.RawValues.Expand))
            {
                var expand = new SelectExpandQueryOption(null, oDataQuery.RawValues.Expand, context, parser);
                expandableQueryable = (IQueryable <object>)expand.ApplyTo(queryable, new ODataQuerySettings());
            }

            int pageIndex    = 1;
            var hasPageIndex = oDataQuery.Request.Query.TryGetValue("$pageindex", out StringValues pageIndexRaw);

            if (hasPageIndex)
            {
                var isTrue = int.TryParse(pageIndexRaw, out int _pageIndexRaw);
                pageIndex = (isTrue && _pageIndexRaw > 0) ? _pageIndexRaw : pageIndex;
            }

            int pageSize    = 10;
            var hasPageSize = oDataQuery.Request.Query.TryGetValue("$pagesize", out StringValues pageSizeRaw);

            if (hasPageSize)
            {
                var isTrue = int.TryParse(pageSizeRaw, out int _pageSizeRaw);
                pageSize = (isTrue && _pageSizeRaw > 0) ? _pageSizeRaw : pageSize;
            }

            IQueryable <object> queryToExecute = expandableQueryable ?? queryable;
            var records = await queryToExecute.Skip((pageIndex - 1) *pageSize).Take(pageSize).ToListAsync();

            var count = await queryToExecute.CountAsync();

            var pageList = new PageList <Developer, DevCode>(MapDomain(records).ToList(), count, pageIndex, pageSize);
            var response = PageListDto <DeveloperDto> .Map(pageList, DeveloperDto.MapDomainToDto);

            return(Ok(response));
        }
 public IActionResult Get(int key, ODataQueryOptions <Order> options, ApiVersion apiVersion) =>
 Ok(new Order()
 {
     Id = key, Customer = $"Customer v{apiVersion}"
 });
        public void ProcessLevelsCorrectly_WithAutoExpand(string url)
        {
            // Arrange
            var model   = GetAutoExpandEdmModel();
            var context = new ODataQueryContext(
                model,
                model.FindDeclaredType("Microsoft.AspNet.OData.Test.Common.Models.AutoExpandCustomer"));
            var request     = RequestFactory.Create(HttpMethod.Get, url);
            var queryOption = new ODataQueryOptions(context, request);

            queryOption.AddAutoSelectExpandProperties();
            var selectExpand = queryOption.SelectExpand;

            // Act
            SelectExpandClause clause = selectExpand.ProcessLevels();

            // Assert
            Assert.True(clause.AllSelected);
            Assert.Equal(2, clause.SelectedItems.Count());

            // Level 1 of Customer.
            var cutomer = Assert.Single(
                clause.SelectedItems.OfType <ExpandedNavigationSelectItem>().Where(
                    item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment &&
                    ((NavigationPropertySegment)item.PathToNavigationProperty.FirstSegment).NavigationProperty
                    .Name == "Friend")
                );

            var clauseOfCustomer = cutomer.SelectAndExpand;

            Assert.True(clauseOfCustomer.AllSelected);
            Assert.Equal(2, clauseOfCustomer.SelectedItems.Count());

            // Order under Customer.
            var order = Assert.Single(
                clause.SelectedItems.OfType <ExpandedNavigationSelectItem>().Where(
                    item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment &&
                    ((NavigationPropertySegment)item.PathToNavigationProperty.FirstSegment).NavigationProperty
                    .Name == "Order")
                );

            Assert.Null(order.LevelsOption);

            var clauseOfOrder = order.SelectAndExpand;

            Assert.True(clauseOfOrder.AllSelected);
            Assert.Single(clauseOfOrder.SelectedItems);

            // Choice Order under Order
            var choiceOrder = Assert.IsType <ExpandedNavigationSelectItem>(clauseOfOrder.SelectedItems.Single());

            Assert.Null(choiceOrder.LevelsOption);
            Assert.True(choiceOrder.SelectAndExpand.AllSelected);
            Assert.Empty(choiceOrder.SelectAndExpand.SelectedItems);

            // Level 2 of Order.
            order = Assert.Single(
                clauseOfCustomer.SelectedItems.OfType <ExpandedNavigationSelectItem>().Where(
                    item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment &&
                    ((NavigationPropertySegment)item.PathToNavigationProperty.FirstSegment).NavigationProperty
                    .Name == "Order")
                );
            Assert.Null(order.LevelsOption);

            clauseOfOrder = order.SelectAndExpand;
            Assert.True(clauseOfOrder.AllSelected);
            Assert.Empty(clauseOfOrder.SelectedItems);

            // Level 2 of Customer.
            cutomer = Assert.Single(
                clauseOfCustomer.SelectedItems.OfType <ExpandedNavigationSelectItem>().Where(
                    item => item.PathToNavigationProperty.FirstSegment is NavigationPropertySegment &&
                    ((NavigationPropertySegment)item.PathToNavigationProperty.FirstSegment).NavigationProperty
                    .Name == "Friend")
                );
            Assert.Null(cutomer.LevelsOption);

            clauseOfCustomer = cutomer.SelectAndExpand;
            Assert.True(clauseOfCustomer.AllSelected);
            Assert.Empty(clauseOfCustomer.SelectedItems);
        }
 public IActionResult Get(ODataQueryOptions <Order> options, ApiVersion apiVersion) =>
 Ok(new[] { new Order()
            {
                Id = 1, Customer = $"Customer v{apiVersion}"
            } });
Example #48
0
        public ActionResult <List <ContractRecord> > GetRecords(ODataQueryOptions <CareerLog> queryOptions)
        {
            List <ContractRecord> events = _careerLogService.GetRecords(queryOptions);

            return(events);
        }
Example #49
0
 //GET: odata/LicensePlates(5)
 /// <summary>
 /// GET API endpoint for a single license plate
 /// </summary>
 /// <param name="key">Returns the licenseplate identified by key</param>
 /// <param name="queryOptions"></param>
 /// <returns></returns>
 public IQueryable <LicensePlate> Get([FromODataUri] int key, ODataQueryOptions <LicensePlate> queryOptions)
 {
     return(GetQueryable(key, queryOptions));
 }
Example #50
0
        public ActionResult <List <ContractEventWithCareerInfo> > GetContracts(ODataQueryOptions <CareerLog> queryOptions)
        {
            List <ContractEventWithCareerInfo> events = _careerLogService.GetAllContractEvents(queryOptions);

            return(events);
        }
Example #51
0
        public ActionResult <List <CareerListItem> > GetCareerListItems(ODataQueryOptions <CareerLog> queryOptions)
        {
            var res = _careerLogService.GetCareerList(queryOptions);

            return(res);
        }
Example #52
0
 public PageResult <RelationshipDto> GetRelationships(ODataQueryOptions <Relationship> options)
 {
     return(_relationshipService.GetAllAsync(options));
 }
Example #53
0
        public Task <List <Category> > Get(ODataQueryOptions <Category> queryOptions)
        {
            var query = ApplyODataQueryConditions <Category, GetCategoriesQuery>(queryOptions, new GetCategoriesQuery());

            return(_mediator.ProcessQueryAsync(query));
        }
Example #54
0
        public ITestActionResult Put(int key, [FromBody] ETagsCustomer eTagsCustomer, ODataQueryOptions <ETagsCustomer> queryOptions)
        {
            if (key != eTagsCustomer.Id)
            {
                return(BadRequest("The Id of customer is not matched with the key"));
            }

            IEnumerable <ETagsCustomer> appliedCustomers = customers.Where(c => c.Id == eTagsCustomer.Id);

            if (appliedCustomers.Count() == 0)
            {
                customers.Add(eTagsCustomer);
                return(Ok(eTagsCustomer));
            }

            if (queryOptions.IfMatch != null)
            {
                IQueryable <ETagsCustomer> ifMatchCustomers = queryOptions.IfMatch.ApplyTo(appliedCustomers.AsQueryable()).Cast <ETagsCustomer>();

                if (ifMatchCustomers.Count() == 0)
                {
                    return(StatusCode(HttpStatusCode.PreconditionFailed));
                }
            }

            ETagsCustomer customer = appliedCustomers.Single();

            customer.Name                   = eTagsCustomer.Name;
            customer.Notes                  = eTagsCustomer.Notes;
            customer.BoolProperty           = eTagsCustomer.BoolProperty;
            customer.ByteProperty           = eTagsCustomer.ByteProperty;
            customer.CharProperty           = eTagsCustomer.CharProperty;
            customer.DecimalProperty        = eTagsCustomer.DecimalProperty;
            customer.DoubleProperty         = eTagsCustomer.DoubleProperty;
            customer.ShortProperty          = eTagsCustomer.ShortProperty;
            customer.LongProperty           = eTagsCustomer.LongProperty;
            customer.SbyteProperty          = eTagsCustomer.SbyteProperty;
            customer.FloatProperty          = eTagsCustomer.FloatProperty;
            customer.UshortProperty         = eTagsCustomer.UshortProperty;
            customer.UintProperty           = eTagsCustomer.UintProperty;
            customer.UlongProperty          = eTagsCustomer.UlongProperty;
            customer.GuidProperty           = eTagsCustomer.GuidProperty;
            customer.DateTimeOffsetProperty = eTagsCustomer.DateTimeOffsetProperty;

            return(Ok(customer));
        }
Example #55
0
        public ActionResult <List <ContractEventWithCareerInfo> > GetContracts(string contract, ODataQueryOptions <CareerLog> queryOptions)
        {
            List <ContractEventWithCareerInfo> events = _careerLogService.GetEventsForContract(contract, ContractEventType.Complete, queryOptions);

            return(events);
        }
Example #56
0
 public static ICollection <TModel> Get <TModel, TData>(this IQueryable <TData> query, IMapper mapper, ODataQueryOptions <TModel> options, HandleNullPropagationOption handleNullPropagation = HandleNullPropagationOption.Default)
     where TModel : class
 => Task.Run(async() => await query.GetAsync(mapper, options, handleNullPropagation)).Result;
Example #57
0
        public static async Task <ICollection <TModel> > GetAsync <TModel, TData>(this IQueryable <TData> query, IMapper mapper, ODataQueryOptions <TModel> options, HandleNullPropagationOption handleNullPropagation = HandleNullPropagationOption.Default)
            where TModel : class
        {
            ICollection <Expression <Func <IQueryable <TModel>, IIncludableQueryable <TModel, object> > > > includeExpressions = options.SelectExpand.GetIncludes().BuildIncludesExpressionCollection <TModel>()?.ToList();
            Expression <Func <TModel, bool> > filter = options.Filter.ToFilterExpression <TModel>(handleNullPropagation);
            Expression <Func <IQueryable <TModel>, IQueryable <TModel> > > queryableExpression = options.GetQueryableExpression();
            Expression <Func <IQueryable <TModel>, long> > countExpression = LinqExtensions.GetCountExpression <TModel>(filter);

            options.AddExpandOptionsResult();
            if (options.Count?.Value == true)
            {
                options.AddCountOptionsResult <TModel, TData>(await query.QueryAsync(mapper, countExpression));
            }

            return(await query.GetAsync(mapper, filter, queryableExpression, includeExpressions));
        }
Example #58
0
        public static async Task <IQueryable <TModel> > GetQueryAsync <TModel, TData>(this IQueryable <TData> query, IMapper mapper, ODataQueryOptions <TModel> options, HandleNullPropagationOption handleNullPropagation = HandleNullPropagationOption.Default)
            where TModel : class
        {
            var expansions = options.SelectExpand.GetExpansions(typeof(TModel));
            List <Expression <Func <TModel, object> > > includeExpressions = expansions.Select(list => new List <Expansion>(list)).BuildIncludes <TModel>
                                                                             (
                options.SelectExpand.GetSelects()
                                                                             )
                                                                             .ToList();

            Expression <Func <TModel, bool> > filter = options.Filter.ToFilterExpression <TModel>(handleNullPropagation);
            Expression <Func <IQueryable <TModel>, IQueryable <TModel> > > queryableExpression = options.GetQueryableExpression();
            Expression <Func <IQueryable <TModel>, long> > countExpression = LinqExtensions.GetCountExpression <TModel>(filter);

            options.AddExpandOptionsResult();
            if (options.Count?.Value == true)
            {
                options.AddCountOptionsResult <TModel, TData>(await query.QueryAsync(mapper, countExpression));
            }

            IQueryable <TModel> queryable = await query.GetQueryAsync(mapper, filter, queryableExpression, includeExpressions);

            return(queryable.UpdateQueryableExpression(expansions));
        }
Example #59
0
 public async Task <Event[]> Get(ODataQueryOptions <Event> options)
 {
     return(await options.ApplyTo(_connection.GetTable <Event>()).Cast <Event>().ToArrayAsync());
 }
Example #60
-1
        public IQueryable<Team> GetTeams(ODataQueryOptions queryOptions)
        {
            // Validate query options
            var settings = new ODataValidationSettings()
            {
                MaxTop = 400
            };
            queryOptions.Validate(settings);

            // Apply the filter before going through to check if links exist for significant performance improvements
            var teams = (IQueryable<Team>)queryOptions.ApplyTo(Db.core.Teams);

            // RouteLinker creates Uris for actions
            var linker = new RouteLinker(Request);

            foreach (var team in teams)
            {
                if (team.Links == null)
                {
                    team.Links = new SerializableDynamic();
                    team.Links.url = linker.GetUri<TeamsController>(c => c.GetTeam(team.Number)).ToString();
                }
            }

            var nextRequest = Request.RequestUri;

            return Db.core.Teams.AsQueryable();
        }