// GET: odata/Orders public async Task<IHttpActionResult> GetOrders(ODataQueryOptions<Order> queryOptions) { // validate the query. try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } var repository = new Repositories.OrderMemoryRepository(); var orders = queryOptions.ApplyTo(repository.Get().AsQueryable<Order>()); return Ok<IQueryable<Order>>((IQueryable<Order>)orders); }
public async Task<IHttpActionResult> GetCategoryTrees(ODataQueryOptions<CategoryTree> queryOptions) { logger.Trace("Call CategoryTreesController GetCategoryTrees"); try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } var data = await repository.All(); var query = (IQueryable<CategoryTree>)queryOptions .ApplyTo(data.AsQueryable()); return Ok(query); }
public HttpResponseMessage GetCount(ODataQueryOptions<ODataPackage> options) { var queryResults = (IQueryable<ODataPackage>)options.ApplyTo(Get()); var count = queryResults.Count(); return OkCount(count); }
public IQueryable<ProductType> Get(ODataQueryOptions<Domain.ProductType> paramters) { var resultset = paramters.ApplyTo(_db.ProductTypes).AsQueryable() as IQueryable<Domain.ProductType>; // ReSharper disable once AssignNullToNotNullAttribute var productTypes = resultset.ToArray().Select(Mapper.Map<ProductType>).AsQueryable(); return productTypes; }
public static bool IsHijackable(ODataQueryOptions<V2FeedPackage> options, out HijackableQueryParameters hijackable) { // Check if we can process the filter clause if (!CanProcessFilterClause(options)) { hijackable = null; return false; } // Build expression (this works around all internal classes in the OData library - all we want is an expression tree) var expression = options.ApplyTo(EmptyQueryable, QueryResultDefaults.DefaultQuerySettings).Expression; // Unravel the comparisons into a list we can reason about List<Tuple<Target, string>> comparisons = new List<Tuple<Target, string>>(); Expression remnant = FindQueryableWhere(expression as MethodCallExpression); MethodCallExpression where; while (IsQueryableWhere(where = remnant as MethodCallExpression)) { var extractedComparisons = ExtractComparison(where).ToList(); if (!extractedComparisons.Any() || extractedComparisons.Any(c => c == null)) { hijackable = null; return false; } else { // We recognize this comparison, record it and keep iterating on the nested expression comparisons.AddRange(extractedComparisons); remnant = where.Arguments[0]; } } // We should be able to hijack here if (comparisons.Any()) { hijackable = new HijackableQueryParameters(); foreach (var comparison in comparisons) { if (comparison.Item1 == Target.Id) { hijackable.Id = comparison.Item2; } else if (comparison.Item1 == Target.Version) { hijackable.Version = comparison.Item2; } else { hijackable = null; return false; } } return true; } hijackable = null; return false; }
public IHttpActionResult GetSalesLeads(ODataQueryOptions<SalesLead> queryOptions) { try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } var queryResults = queryOptions.ApplyTo(SalesLeadFactory.GetSalesLeads()).Cast<SalesLead>(); return Ok<IQueryable<SalesLead>>(queryResults); }
// GET api/PurchaseRequisitionDescription public IEnumerable<PurchaseRequisitionDescription> GetPurchaseRequisitionDescriptions(ODataQueryOptions Options) { //return db.PurchaseRequisitionDescriptions.Include(p=>p.Product).AsEnumerable(); //return Options.ApplyTo(db.PurchaseRequisitionDescriptions.Include(p => p.Product) as IQueryable) as IEnumerable<PurchaseRequisitionDescription>; //db.PurchaseRequisitionDescriptions.Include(p => p.Product).Include() return Options.ApplyTo(db.PurchaseRequisitionDescriptions.AsQueryable().Include(p => p.Product).Include(p => p.Product.ProductCategory).Include(u => u.UOM)) as IEnumerable<PurchaseRequisitionDescription>; }
// GET api/buildingupgrade public IQueryable<BuildingUpgrade> Get(ODataQueryOptions<Domain.BuildingUpgrade> paramters) { var logStart = LogHelper.StartLog("Started BuildingUpgradeController.Get", Logger); var resultset = paramters.ApplyTo(_db.BuildingUpgrades).AsQueryable() as IQueryable<Domain.BuildingUpgrade>; // ReSharper disable once AssignNullToNotNullAttribute var buildingUpgrades = resultset.ToArray().Where(x=>x.Name.StartsWith("Property") && x.Completed == false).OrderBy(x=>x.Name). Select(Mapper.Map<BuildingUpgrade>).AsQueryable(); return LogHelper.EndLog(logStart, buildingUpgrades); }
public HttpResponseMessage CountSearch( [FromODataUri] string searchTerm, [FromODataUri] string targetFramework, [FromODataUri] bool includePrerelease, ODataQueryOptions<ODataPackage> options) { var queryResults = (IQueryable<ODataPackage>)options.ApplyTo(Search(searchTerm, targetFramework, includePrerelease, options)); var count = queryResults.Count(); return OkCount(count); }
public void ApplyTo_Succeeds_If_QueryTypeMatchesOptionsType() { 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.DoesNotThrow( () => query.ApplyTo(Enumerable.Empty<Customer>().AsQueryable())); }
public IQueryable<LessonViewModel> Get(ODataQueryOptions<LessonViewModel> queryOptions) { var result = _lessonService.GetLessons().Select(l => new LessonViewModel { Date = l.Date, GroupId = l.Group.GroupId, LessonId = l.LessonId, GroupDisplayName = l.Group.GroupNumber + " (" + l.Group.Year + ")" }); var filteredResult = ((IQueryable<LessonViewModel>)queryOptions.ApplyTo(result)); return filteredResult; }
public IQueryable<Facet> GetFacets(ODataQueryOptions<Car> options) { if (options.RawValues.Expand.IsNullOrEmpty()) { return new Facet[0].AsQueryable(); } IQueryable results = options.ApplyTo(SearchContext.GetQueryable<Car>()); string[] facets = StringUtil.Split(options.RawValues.Expand, '|', true); var query = results as IQueryable<Car>; return SearchService.GetFacets(query, facets); }
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>(); }
public PageResult<Order> GetOrders(ODataQueryOptions<Order> options) { var settings = new ODataQuerySettings(); var fromDatabase = _context.Orders.Where(order => order.Freight != 123); var results = options.ApplyTo(fromDatabase.AsQueryable(), settings); return new PageResult<Order>( results as IQueryable<Order>, Request.ODataProperties().NextLink, Request.ODataProperties().TotalCount); }
public void ApplyTo_ThrowsInvalidOp_If_QueryTypeDoesnotMatch() { 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.Throws<InvalidOperationException>( () => query.ApplyTo(Enumerable.Empty<int>().AsQueryable()), "Cannot apply ODataQueryOptions of 'System.Web.Http.OData.TestCommon.Models.Customer' to IQueryable of 'System.Int32'."); }
public PageResult<ArticleDto> Get(ODataQueryOptions<ArticleDto> options) { var settings = new ODataQuerySettings { PageSize = 10, EnsureStableOrdering = false }; var artikelQuery = productsContext.Articles .OrderBy(a => a.Id).AsNoTracking().Project().To<ArticleDto>(null, dest => dest.Id, dest => dest.Name, dest => dest.Code); var results = options.ApplyTo(artikelQuery, settings); return new PageResult<ArticleDto>( results as IEnumerable<ArticleDto>, Request.ODataProperties().NextLink, Request.ODataProperties().TotalCount); }
public IQueryable<UserViewModel> Get(ODataQueryOptions<UserViewModel> queryOptions) { var result = _userService.GetUsers().Select(s => new UserViewModel { UserId = s.UserId, Email = s.Email, FirstName = s.FirstName, LastName = s.LastName, DisplayName = s.FirstName + " " + s.LastName, GroupId = s.Group == null ? (int?)null : s.Group.GroupId }); var filteredResult = ((IQueryable<UserViewModel>)queryOptions.ApplyTo(result)); return filteredResult; }
public IQueryable<Car> GetCars(ODataQueryOptions<Car> options) { TopQueryOption top; SkipQueryOption skip; OrderByQueryOption orderby; var customOptions = new ODataQueryOptions<Car>(options.Context, options.BuildCustomRequest(out top, out skip, out orderby)); IQueryable query = customOptions.ApplyTo( SearchContext.GetQueryable<Car>().Where(c => c.TemplateId == Constants.Templates.CarModel)); var results = query as IQueryable<Car>; if (results != null) { if (skip != null) { results = results.Skip(skip.Value); } if (top != null) { results = results.Take(top.Value); } if (orderby != null) { string[] parts = orderby.RawValue.Split(' '); if (parts.Length > 1 && !string.IsNullOrEmpty(parts[0]) && !string.IsNullOrEmpty(parts[1])) { string fieldName = parts[0]; if (parts[1] == "asc") { results = results.OrderBy(c => c[fieldName]); } else if (parts[1] == "desc") { results = results.OrderByDescending(c => c[fieldName]); } } } return results; } return null; }
public IQueryable<GroupViewModel> Get(ODataQueryOptions<GroupViewModel> queryOptions) { var result = _groupService.GetAll().Select(g => new GroupViewModel { GroupId = g.GroupId, GroupNumber = g.GroupNumber, Year = g.Year, ContactEmail = g.ContactEmail, ContactName = g.ContactName, ContactPhone = g.ContactPhone, DisplayName = g.GroupNumber + " (" + g.Year + ")" }); var filteredResult = ((IQueryable<GroupViewModel>)queryOptions.ApplyTo(result)); return filteredResult; }
internal static IEnumerable<VELEMIMUNKAINMLIST> GetDbPage(ODataQueryOptions<VELEMIMUNKAINMLIST> queryOptions) { using (MIRTUSZContext.MIRTUSZDataContext mirtuszDC = new MIRTUSZContext.MIRTUSZDataContext()) { mirtuszDC.Connection.Open(); if (queryOptions.Filter != null) { IQueryable query = queryOptions.ApplyTo(mirtuszDC.VELEMIMUNKAINMLISTs); var a = query.Provider.Execute< IEnumerable<VELEMIMUNKAINMLIST>>(query.Expression); return a.ToArray(); // return a.Skip(queryOptions.Skip == null ? 0 : queryOptions.Skip.Value).Take(queryOptions.Top.Value).ToArray(); } return mirtuszDC.VELEMIMUNKAINMLISTs.Skip(queryOptions.Skip == null ? 0 : queryOptions.Skip.Value).Take(queryOptions.Top.Value).ToArray(); } }
// GET api/todos public IHttpActionResult Get(ODataQueryOptions<TodoModel> options, bool? overdue = null) { IEnumerable<TodoModel> todos = _repository.GetAll(); if (overdue.HasValue) { todos = overdue == false ? todos.Where(x => !x.completed && x.deadlineUtc >= DateTime.UtcNow) : todos.Where(x => !x.completed && x.deadlineUtc < DateTime.UtcNow); } IEnumerable<TodoModel> results = (IEnumerable<TodoModel>)options.ApplyTo(todos.AsQueryable(), new ODataQuerySettings()); var representation = results.Select(_mapper.Map<TodoModel, TodoRepresentation>).ToList(); return Ok(representation); }
public PageResult<ViewTradeResource> Get([FromUri] FilterOptions filterOptions, ODataQueryOptions queryOptions) { var querySettings = new ODataQuerySettings { PageSize = 20 }; var data = _tradeRepository .Get(filterOptions.BasketName); var results = queryOptions.ApplyTo(_mappingEngine.Map<IEnumerable<Trade>, IEnumerable<ViewTradeResource>>(data).AsQueryable(), querySettings) .Cast<ViewTradeResource>(); return new PageResult<ViewTradeResource>( results, Request.GetNextPageLink(), Request.GetInlineCount() ); }
internal static int GetCount(ODataQueryOptions<VELEMIMUNKAINMLIST> queryOptions) { using (MIRTUSZContext.MIRTUSZDataContext mirtuszDC = new MIRTUSZContext.MIRTUSZDataContext()) { mirtuszDC.Connection.Open(); if (queryOptions.Filter != null) { ODataQuerySettings settings = new ODataQuerySettings() { PageSize = 1000000 }; IQueryable query = queryOptions.ApplyTo(mirtuszDC.VELEMIMUNKAINMLISTs, settings); return query.Cast<VELEMIMUNKAINMLIST>().Count(); } return mirtuszDC.VELEMIMUNKAINMLISTs.Count(); } }
// Note this can be done through Queryable attribute as well public IQueryable<Order> Get(ODataQueryOptions queryOptions) { // Register a custom FilterByValidator to disallow custom logic in the filter query if (queryOptions.Filter != null) { queryOptions.Filter.Validator = new RestrictiveFilterByQueryValidator(); } // Validate the query, we only allow order by Id property and // we only allow maximum Top query value to be 9 ODataValidationSettings settings = new ODataValidationSettings(){ MaxTop = 9 }; settings.AllowedOrderByProperties.Add("Id"); queryOptions.Validate(settings); // Apply the query return queryOptions.ApplyTo(OrderList.AsQueryable()) as IQueryable<Order>; }
public IQueryable<ScoreViewModel> Get(ODataQueryOptions<ScoreViewModel> queryOptions) { var result = _scoreService.GetScores().Select(s => new ScoreViewModel { ScoreId = s.ScoreId, Score = s.Score, AssignedToId = s.AssignedTo.UserId, AssignedById = s.AssignedBy.UserId, AssignedTo = s.AssignedTo.FirstName + " " + s.AssignedTo.LastName, AssignedBy = s.AssignedBy.FirstName + " " + s.AssignedBy.LastName, VisitId = s.Visit == null ? (int?) null : s.Visit.VisitId, LessonId = s.Visit.Lesson.LessonId, DisplayDate = s.Visit.Lesson.Date }); var filteredResult = ((IQueryable<ScoreViewModel>)queryOptions.ApplyTo(result)); return filteredResult; }
public async Task<IHttpActionResult> GetProducts(ODataQueryOptions<AggregateProduct> queryOptions) { logger.Trace("Call ProductsController GetProducts"); try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } var orders = (IQueryable<AggregateProduct>)queryOptions .ApplyTo(repository.Get().AsQueryable()); return Ok(orders); }
/// <summary> /// Gets the document sets. /// </summary> /// <param name="queryOptions">The query options.</param> /// <returns></returns> public IHttpActionResult GetDocumentSets(ODataQueryOptions<DocumentSet> queryOptions) { try { queryOptions.Validate(ValidationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } try { string json = File.ReadAllText(HttpContext.Current.Server.MapPath("~/app_data/documentsets.json")); var list = JsonConvert.DeserializeObject<List<DocumentSet>>(json).AsQueryable(); var results = queryOptions.ApplyTo(list) as IEnumerable<DocumentSet>; return Ok(results); } catch (Exception ex) { return InternalServerError(ex); } }
// demo 2: low level APIs public IQueryable<QueryCompositionCustomer> Get(ODataQueryOptions queryOptions) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } IQueryable<QueryCompositionCustomer> result = null; try { result = queryOptions.ApplyTo(QueryCompositionCustomerController.CustomerList.AsQueryable()) as IQueryable<QueryCompositionCustomer>; } catch (ODataException exception) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exception)); } return result; }
public PageResult<SeaDayViewModel> Get(int tripId, ODataQueryOptions<TripHeader> options) { var days = TubsDataService .GetRepository<PurseSeineSeaDay>(MvcApplication.CurrentSession) .FilterBy(d => d.Trip.Id == tripId); var dayViewModels = from day in days select Mapper.Map<PurseSeineSeaDay, SeaDayViewModel>(day); int inlineCount = dayViewModels.Count(); IQueryable results = options.ApplyTo(dayViewModels); // Not sure how to get the appropriate count // what is wanted is repo.All().Where(???).Count(); return new PageResult<SeaDayViewModel>( results as IEnumerable<SeaDayViewModel>, Request.GetNextPageLink(), inlineCount ); }
public PageResult<Vessel> Get(ODataQueryOptions<Vessel> options) { // Implementation from here: // http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options // TODO May want to limit additional query options ODataQuerySettings settings = new ODataQuerySettings() { PageSize = 15 }; var repo = TubsDataService.GetRepository<Vessel>(MvcApplication.CurrentSession); IQueryable results = options.ApplyTo(repo.All(), settings); // Not sure how to get the appropriate count // what is wanted is repo.All().Where(???).Count(); return new PageResult<Vessel>( results as IEnumerable<Vessel>, Request.GetNextPageLink(), Request.GetInlineCount() ); }
// demo 2: low level APIs public IQueryable <QueryCompositionCustomer> Get(ODataQueryOptions queryOptions) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } IQueryable <QueryCompositionCustomer> result = null; try { ODataQuerySettings querySettings = new ODataQuerySettings { EnsureStableOrdering = false }; result = queryOptions.ApplyTo(QueryCompositionCustomerController.CustomerList.AsQueryable(), querySettings) as IQueryable <QueryCompositionCustomer>; } catch (ODataException exception) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exception)); } return(result); }