public HttpResponseMessage GetCount(ODataQueryOptions<ODataPackage> options) { var queryResults = (IQueryable<ODataPackage>)options.ApplyTo(Get()); var count = queryResults.Count(); return OkCount(count); }
// GET: odata/References(5) public async Task<IHttpActionResult> GetReference([FromODataUri] int key, ODataQueryOptions<Reference> queryOptions) { //Get access token to SharePoint string accessToken = await _tokenProvider.GetSharePointAccessToken(); if (accessToken == null) { throw new UnauthorizedAccessException(); } // validate the query. try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } //Get reference from SharePoint string eTag = Request.Headers.IfNoneMatch.ToString(); Reference reference = await _repository.GetReference(accessToken, key, eTag); //Check eTag if (reference.__eTag == eTag) { return new StatusCodeResult(HttpStatusCode.NotModified, Request); } return Ok(reference); }
public IHttpActionResult Get(int key, ODataQueryOptions<ETagsCustomer> queryOptions) { IEnumerable<ETagsCustomer> appliedCustomers = customers.Where(c => c.Id == key); if (appliedCustomers.Count() == 0) { return BadRequest("The key is not valid"); } if (queryOptions.IfNoneMatch != null) { appliedCustomers = queryOptions.IfNoneMatch.ApplyTo(appliedCustomers.AsQueryable()).Cast<ETagsCustomer>(); } if (queryOptions.IfMatch != null) { appliedCustomers = queryOptions.IfMatch.ApplyTo(appliedCustomers.AsQueryable()).Cast<ETagsCustomer>(); } if (appliedCustomers.Count() == 0) { return StatusCode(HttpStatusCode.NotModified); } else { return Ok(new SingleResult<ETagsCustomer>(appliedCustomers.AsQueryable())); } }
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; }
// GET: odata/Projects(5) public async Task<IHttpActionResult> GetProject([FromODataUri] int key, ODataQueryOptions<Project> queryOptions) { //Get access token to SharePoint string accessToken = ((Repository)_repository).GetAccessToken(); if (accessToken == null) { throw new UnauthorizedAccessException(); } // validate the query. try { queryOptions.Validate(_validationSettings); } catch (ODataException ex) { return BadRequest(ex.Message); } //Get project from SharePoint string eTag = Request.Headers.IfNoneMatch.ToString(); Project project = await _repository.GetProject(accessToken, key, eTag); //Check eTag if (project.__eTag == eTag) { return new StatusCodeResult(HttpStatusCode.NotModified, Request); } else { return Ok<Project>(project); } }
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; }
/// <summary> /// All standard OData web api support is handled here (except select and expand). /// This method also handles nested orderby statements the the current ASP.NET web api does not yet support. /// This method is called by base.OnActionExecuted /// </summary> /// <param name="queryable"></param> /// <param name="queryOptions"></param> /// <returns></returns> public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions) { var queryHelper = GetQueryHelper(queryOptions.Request); queryable = queryHelper.BeforeApplyQuery(queryable, queryOptions); queryable = queryHelper.ApplyQuery(queryable, queryOptions); return queryable; }
/// <summary> /// Gets the list of blog posts by specified filter. /// </summary> /// <param name="options">The options.</param> /// <param name="filter">The filter.</param> /// <returns> /// List of blog post service models. /// </returns> public DataListResponse<BlogPostModel> Get(ODataQueryOptions<BlogPostModel> options, [FromUri] GetBlogPostRequest filter) { using (var api = CmsContext.CreateApiContextOf<BlogsApiContext>()) { var results = api.GetBlogPostsAsQueryable(filter); return results.ToDataListResponse(options); } }
/// <summary> /// Gets the list of blog posts by specified filter. /// </summary> /// <param name="options">The options.</param> /// <returns> /// List of blog post service models. /// </returns> public DataListResponse<AuthorModel> Get(ODataQueryOptions<AuthorModel> options) { using (var api = CmsContext.CreateApiContextOf<BlogsApiContext>()) { var results = api.GetAuthorsAsQueryable(); return results.ToDataListResponse(options); } }
public IHttpActionResult Get(ODataQueryOptions<V1FeedPackage> options) { var queryable = _packagesRepository.GetAll() .Where(p => !p.IsPrerelease && !p.Deleted) .WithoutVersionSort() .ToV1FeedPackageQuery(_configurationService.GetSiteRoot(UseHttps())); return QueryResult(options, queryable, MaxPageSize); }
public override IQueryable BeforeApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions) { var nhQueryable = queryable as IQueryableInclude; if (nhQueryable != null) { queryable = ApplyExpand(nhQueryable); } return queryable; }
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/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); }
// 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>; }
public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions) { var queryHelper = GetQueryHelper(queryOptions.Request); if (queryOptions.SelectExpand?.RawExpand != null) { queryOptions = QueryHelper.RemoveOptions(queryOptions, new List<string>() { "$expand" }); //queryOptions = new ODataQueryOptions() } return queryHelper.ApplyQuery(queryable, queryOptions); }
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); }
/// <summary> /// Overrides the method in QueryHelper to perform the $expands in NHibernate. /// Also populates the ExpandTypeMap that controls lazy initialization and serialization. /// </summary> /// <param name="queryable"></param> /// <param name="expandsQueryString"></param> /// <returns></returns> public override IQueryable ApplyExpand(IQueryable queryable, ODataQueryOptions queryOptions) { var expandQueryString = queryOptions.RawValues.Expand; if (string.IsNullOrWhiteSpace(expandQueryString)) return queryable; var session = GetSession(queryable); var fetcher = new NHEagerFetch(session.SessionFactory); queryable = fetcher.ApplyExpansions(queryable, expandQueryString, expandMap); return queryable; }
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); }
private async Task<IHttpActionResult> GetCore(ODataQueryOptions<V1FeedPackage> options, string id, string version, bool return404NotFoundWhenNoResults) { var packages = _packagesRepository.GetAll() .Include(p => p.PackageRegistration) .Where(p => p.PackageRegistration.Id.Equals(id, StringComparison.OrdinalIgnoreCase) && !p.IsPrerelease && !p.Deleted); if (!string.IsNullOrEmpty(version)) { packages = packages.Where(p => p.Version == version); } // try the search service try { var searchAdaptorResult = await SearchAdaptor.FindByIdAndVersionCore( _searchService, GetTraditionalHttpContext().Request, packages, id, version, curatedFeed: null); // If intercepted, create a paged queryresult if (searchAdaptorResult.ResultsAreProvidedBySearchService) { // Packages provided by search service packages = searchAdaptorResult.Packages; // Add explicit Take() needed to limit search hijack result set size if $top is specified var totalHits = packages.LongCount(); if (return404NotFoundWhenNoResults && totalHits == 0) { return NotFound(); } var pagedQueryable = packages .Take(options.Top != null ? Math.Min(options.Top.Value, MaxPageSize) : MaxPageSize) .ToV1FeedPackageQuery(GetSiteRoot()); return QueryResult(options, pagedQueryable, MaxPageSize, totalHits, (o, s, resultCount) => SearchAdaptor.GetNextLink(Request.RequestUri, resultCount, new { id }, o, s)); } } catch (Exception ex) { // Swallowing Exception intentionally. If *anything* goes wrong in search, just fall back to the database. // We don't want to break package restores. We do want to know if this happens, so here goes: QuietLog.LogHandledException(ex); } if (return404NotFoundWhenNoResults && !packages.Any()) { return NotFound(); } var queryable = packages.ToV1FeedPackageQuery(GetSiteRoot()); return QueryResult(options, queryable, MaxPageSize); }
// GET: odata/GeoCaches(1) public GeoCache GetGeoCache([FromODataUri] int key, ODataQueryOptions<GeoCache> queryOptions) { var geoCache = GeoCacheService.GetGeoCache(key); return new GeoCache { Id = geoCache.Id, Latitude = geoCache.Latitude, Longitude = geoCache.Longitude, Name = geoCache.Name }; }
//[Queryable] public IEnumerable<Member> GetMembers( ODataQueryOptions query) { var mappedQuery = query.Parse<Models.Member>(Request); var results = new List<Member>(); foreach (var result in mappedQuery.ApplyTo(db.Members)) { results.Add(Mapper.Map<Member>(result)); } return results; }
public async Task<IHttpActionResult> FindPackagesById(ODataQueryOptions<V2FeedPackage> options, string curatedFeedName, [FromODataUri]string id) { if (string.IsNullOrEmpty(curatedFeedName) || string.IsNullOrEmpty(id)) { var emptyResult = Enumerable.Empty<Package>().AsQueryable() .ToV2FeedPackageQuery(GetSiteRoot(), _configurationService.Features.FriendlyLicenses); return QueryResult(options, emptyResult, MaxPageSize); } return await GetCore(options, curatedFeedName, id, version: null, return404NotFoundWhenNoResults: false); }
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 IHttpActionResult Get(ODataQueryOptions<V2FeedPackage> options, string curatedFeedName) { if (!_entities.CuratedFeeds.Any(cf => cf.Name == curatedFeedName)) { return NotFound(); } var queryable = _curatedFeedService.GetPackages(curatedFeedName) .ToV2FeedPackageQuery(_configurationService.GetSiteRoot(UseHttps()), _configurationService.Features.FriendlyLicenses) .InterceptWith(new NormalizeVersionInterceptor()); return QueryResult(options, queryable, MaxPageSize); }
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 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 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 IHttpActionResult Get(int key, ODataQueryOptions<StoreGeneratedPatternCustomer> queryOptions) { IEnumerable<StoreGeneratedPatternCustomer> appliedCustomers = customers.Where(c => c.Id == key); if (appliedCustomers.Count() == 0) { return BadRequest("The key is not valid"); } else { return Ok(new SingleResult<StoreGeneratedPatternCustomer>(appliedCustomers.AsQueryable())); } }
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 IQueryable <Object> CompanyInfoAndOrders(System.Web.Http.OData.Query.ODataQueryOptions options) { // Need to handle this specially for NH, to prevent $top being applied to Orders var query = ContextProvider.Context.Customers; var queryHelper = new NHQueryHelper(); // apply the $filter, $skip, $top to the query var query2 = queryHelper.ApplyQuery(query, options); // execute query, then expand the Orders var r = query2.Cast <Customer>().ToList(); NHInitializer.InitializeList(r, "Orders"); // after all is loaded, create the projection var stuff = r.AsQueryable().Select(c => new { c.CompanyName, c.CustomerID, c.Orders }); queryHelper.ConfigureFormatter(Request, query);
public List <RedmondCustomer> GetListOfCustomer(ODataQueryOptions options) { throw new NotImplementedException(); }
public CustomerCollection GetStronglyTypedCustomer(ODataQueryOptions options) { throw new NotImplementedException(); }
public IQueryable <Customer> Get(ODataQueryOptions options) { throw new NotImplementedException(); }
public object GetObject_WithODataQueryOptionsOfT(ODataQueryOptions <Customer> options) { // this can return Customer or BellevueCustomer throw new NotImplementedException(); }
public IEnumerable GetNonQueryable_WithODataQueryOptionsOfT(ODataQueryOptions <Customer> options) { throw new NotImplementedException(); }
public TwoGenericsCollection GetTwoGenericsCollection_WithODataQueryOptionsOfT(ODataQueryOptions <Customer> options) { throw new NotImplementedException(); }
public void GetVoidReturn_WithODataQueryOptionsOfT(ODataQueryOptions <Customer> options) { throw new NotImplementedException(); }
public Collection <SeattleCustomer> GetCollectionOfCustomer(ODataQueryOptions options) { throw new NotImplementedException(); }
public void GetVoidReturn(ODataQueryOptions options) { throw new NotImplementedException(); }
public IEnumerable <BellevueCustomer> GetIEnumerableOfCustomer(ODataQueryOptions options) { throw new NotImplementedException(); }
public TwoGenericsCollection GetTwoGenericsCollection(ODataQueryOptions options) { throw new NotImplementedException(); }
public void GetNextPageLink_ThatTakesUri_GetsNextPageLink() { Uri nextPageLink = ODataQueryOptions.GetNextPageLink(new Uri("http://localhost/Customers?$filter=Age ge 18"), 10); Assert.Equal("http://localhost/Customers?$filter=Age%20ge%2018&$skip=10", nextPageLink.AbsoluteUri); }
public IEnumerable GetNonQueryable(ODataQueryOptions options) { throw new NotImplementedException(); }
public void IsSystemQueryOption_Returns_True_For_All_Supported_Query_Names(string queryName) { // Arrange & Act & Assert Assert.True(ODataQueryOptions.IsSystemQueryOption(queryName)); }
public void IsSystemQueryOption_Returns_False_For_Unrecognized_Query_Name() { // Arrange & Act & Assert Assert.False(ODataQueryOptions.IsSystemQueryOption("$invalidqueryname")); }