OData custom pagination/nextLink for nested collection - odata

Using microsoft.aspnet.odata 5.10.0 (But I haven't found a solution in test projects using Microsoft.AspNet.OData 7.5.15 either)
I have an OData API that performs manual querying - we don't use IQueryable and instead do server-side paging manually. (We can't use something like EF to do this automatically)
Our code looks similar to this sample in that we use PageResult, except that we set the Total/NextLink like this:
this.Request.ODataProperties().TotalCount = pagedResult.Count;
this.Request.ODataProperties().NextLink = pagedResult.NextPageLink;
What we are looking for is similar to this question on github, which is attempting to set a different page size for a nested collection, compared to the root collection.
Taking the example from the spec, we would like to manually set Orders#odata.nextLink
{
"#odata.context": "http://host/service/$metadata#Customers/$entity",
...
"Orders#odata.count": 42,
"Orders": [ ... ],
"Orders#odata.nextLink": "...",
...
}
ODataProperties() doesn't work for nested Collections, it only applies to the outer value.
The odata serializer won't let you name a property with #odata in it, so we can't just make a new property on our model and name it Orders#odata.nextLink via an attribute.

ITruncatedCollection/TruncatedCollection is the way to solve this - it exists in both versions too. You can use it anywhere you need an IList. You can set the page size on the server and if the size of the underlying collection is larger than the page size the odata library will generate a next link + property.

Related

How to correctly query OData with filter in nested type based on property from parent type?

I am getting a dynamic value (_FilterDate) on the parent type that I want to use as a filter for the nested type /Trips but can't get it to work because I still get entries in the nested data that do not meet the filter. Actually, there is no difference whether I use this filter or not.
$filter=Trips/all(d:d/EndDate ge _FilterDate)
I also tried this:
$expand=Trips($filter=EndDate ge $it/_FilterDate)
but got the error: "Could not find a property named '_FilterDate' on type 'Default.Trips'."
So I'm wondering how to get the syntax right and thus kindly ask for help.
Example portion:
"value": [
{
"_FilterCompany": "YES",
"_FilterLocation": "YES",
"_FilterDate": "2020-01-08",
"Trips": [
{
"StartDate": "2019-06-24",
"EndDate": "2019-06-28",
},
{
"StartDate": "2020-02-07",
"EndDate": "2020-02-07",
}
]
}
There are two issues going on here:
this response is specifically regarding the OData v4 specification and the .Net ODataLib implementation.
You have correctly identified that when filtering results based on a nested collection you you must separately apply the filter within that collection if you want the fitler to apply to the items within that collection as well.
This is because the root level $filter criteria only affects the selection of the root items, think of it as if the $expand operator is applied after the $filter has identified the top level of row the return, $expand is simply executed as a Linq Include statement.
In your second attempt, $it references the instance of Trips, which is a known bug/by design, according to the spec it is expected to work the way you have implemented it:
5.1.1.6.4 $it
Example 82: customers along with their orders that shipped to the same city as the customer's address. The nested filter expression is evaluated in the context of Orders; $it allows referring to values in the outer context of Customers.
http://host/service/Customers?
$expand=Orders($filter=$it/Address/City eq ShipTo/City)
So knowing the $it is broken, the spec doc does specify a $root identifier that you might also be able to use, but in ODataLib 7.3 $root is still not supported OOTB either. There is an issue logged here: $it references the wrong resource #616
Workaround
If your Trips data type has a navigation property back to the Filter/root record, then you can use that navigation property as part of the $filter:
Assuming the navigation property is called Filter
$filter=Trips/all(d:d/EndDate ge _FilterDate)&$expand=Trips($filter=EndDate ge Filter/_FilterDate)
If your Trips type does not have this navigation link back to the parent record then you are stuck at this stage with these two workarounds:
Create a Function on the controller to return this filtered data specifically, as this would be simple to evaluate as a Linq query in the server-side.
Accept that the server will return extra rows in the Trips collections, and apply the filter over the results in the client-side.

OData Data read- latest entry on top

I am using OData API to read data in my Fiori Application. The issue is, in Odata API, the latest data entry is at the end rather it should be at the top. How do i do that ie put my latest data on top.
You can use the $orderby to decide what order the data is returned in. See the docs for more info. This URL is an example of ordering (using the OData TripPin example service) that sorts by the LastName property:
http://services.odata.org/V4/TripPinServiceRW/People?$orderby=LastName
We can use this same process to order by a DateTime value or an ID value to get your latest entries at the top. For example, here we order by the DateTimeOffset field StartsAt putting the latest entries first:
http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')/Trips?$orderby=StartsAt desc
1)
As mentioned before, you might have a look at server side sorting using “$orderby” as seen here.
2)
You might also want to check out the following tutorial on Sorting:
“
items="{
path : 'invoice>/Invoices',
sorter : {
path : 'ProductName'
}
}"
We add a declarative sorter to our binding syntax.
As usual, we transform the simple binding syntax to the object notation, specify the path to the data,
and now add an additional sorter property.
We specify the data path by which the invoice items should be sorted, the rest is done automatically.
By default, the sorting is ascending, but you could also add a property descending with the value true inside the sorter property to change the sorting order.”
Please see here and here
3)
This here might also be helpful:
“In this step, we will create a button at the top of the table which will change the sorting of the table.
When the current sorting state of the table is changed, the sorting state will be reflected in the URL.
This illustrates how to make the table sorting bookmarkable.”
Step 13: Make Table Sorting Bookmarkable
Sample: Navigation - Step 13 - Make Table Sorting Bookmarkable
4)
These links here also look interesting:
Sorting, Grouping and Filtering for Aggregation Binding
Sample: Sorting
Sample: With Sorting and Filtering Feature

how to set Personalizable attribute to generic list in webpart?

I develop web part with custom editor part and faced with this question.
Is it possible in web part set Personalizable attribute to generic List?
For example I want something like this:
[WebBrowsable(false)]
[Personalizable(PersonalizationScope.Shared)]
public List<AnnouncementItem> Announcements
{
get { return _announcements; }
set { _announcements = value; }
}
Is it possible, and what kind of types at all can be used as "Personalizable"?
Thanks.
Solution:
I use a custom EditorPart to select multiple lists using AssetUrlSelector, but I need a way to personalize this collection for end user.List<of custom objects> doesn't work, but I found that List<string> (and only string) work perfectly. So, I get required lists in EditorPart and pass their to the web part using List<string>.
Try using a custom EditorPart to add/remove items from the collection. I've never built a web part that personalized a collection so I don't know if it works but I'd definitely try the collection with an EditorPart. If it doesn't work, serialize XML into a string property.
Your question does not seem to match your code. Your code shows a collection of custom objects. I doubt an end user will be able to set such a property. To have a property that points to a generic list, you would probably be better off defining the property as a string that contains the URL to a list.

Code re-use with Linq-to-Sql - Creating 'generic' look-up tables

I'm working on an application at the moment in ASP.NET MVC which has a number of look-up tables, all of the form
LookUp {
Id
Text
}
As you can see, this just maps the Id to a textual value. These are used for things such as Colours. I now have a number of these, currently 6 and probably soon to be more.
I'm trying to put together an API that can be used via AJAX to allow the user to add/list/remove values from these lookup tables, so for example I could have something like:
http://example.com/Attributes/Colours/[List/Add/Delete]
My current problem is that clearly, regardless of which lookup table I'm using, everything else happens exactly the same. So really there should be no repetition of code whatsoever.
I currently have a custom route which points to an 'AttributeController', which figures out the attribute/look-up table in question based upon the URL (ie http://example.com/Attributes/Colours/List would want the 'Colours' table). I pass the attribute (Colours - a string) and the operation (List/Add/Delete), as well as any other parameters required (say "Red" if I want to add red to the list) back to my repository where the actual work is performed.
Things start getting messy here, as at the moment I've resorted to doing a switch/case on the attribute string, which can then grab the Linq-to-Sql entity corresponding to the particular lookup table. I find this pretty dirty though as I find myself having to write the same operations on each of the look-up entities, ugh!
What I'd really like to do is have some sort of mapping, which I could simply pass in the attribute name and get out some form of generic lookup object, which I could perform the desired operations on without having to care about type.
Is there some way to do this to my Linq-To-Sql entities? I've tried making them implement a basic interface (IAttribute), which simply specifies the Id/Text properties, however doing things like this fails:
System.Data.Linq.Table<IAttribute> table = GetAttribute("Colours");
As I cannot convert System.Data.Linq.Table<Colour> to System.Data.Linq.Table<IAttribute>.
Is there a way to make these look-up tables 'generic'?
Apologies that this is a bit of a brain-dump. There's surely imformation missing here, so just let me know if you'd like any further details. Cheers!
You have 2 options.
Use Expression Trees to dynamically create your lambda expression
Use Dynamic LINQ as detailed on Scott Gu's blog
I've looked at both options and have successfully implemented Expression Trees as my preferred approach.
Here's an example function that i created: (NOT TESTED)
private static bool ValueExists<T>(String Value) where T : class
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
Expression value = Expression.Equal(Expression.Property(pe, "ColumnName"), Expression.Constant(Value));
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(value, pe);
return MyDataContext.GetTable<T>().Where(predicate).Count() > 0;
}
Instead of using a switch statement, you can use a lookup dictionary. This is psuedocode-ish, but this is one way to get your table in question. You'll have to manually maintain the dictionary, but it should be much easier than a switch.
It looks like the DataContext.GetTable() method could be the answer to your problem. You can get a table if you know the type of the linq entity that you want to operate upon.
Dictionary<string, Type> lookupDict = new Dictionary<string, Type>
{
"Colour", typeof(MatchingLinqEntity)
...
}
Type entityType = lookupDict[AttributeFromRouteValue];
YourDataContext db = new YourDataContext();
var entityTable = db.GetTable(entityType);
var entity = entityTable.Single(x => x.Id == IdFromRouteValue);
// or whatever operations you need
db.SubmitChanges()
The Suteki Shop project has some very slick work in it. You could look into their implementation of IRepository<T> and IRepositoryResolver for a generic repository pattern. This really works well with an IoC container, but you could create them manually with reflection if the performance is acceptable. I'd use this route if you have or can add an IoC container to the project. You need to make sure your IoC container supports open generics if you go this route, but I'm pretty sure all the major players do.

How can I use nHibernate to get a small subset of object properties for list view

I am using ASP.NET-MVC and nHibernate for the first time. Great tools, but big learning curve!
I have a list view of objects that are quite large (each has about 60 properties). In the list view I am only using about 10 of these properties. Performance is not too bad, but it seems a waste to fully hydrate these objects. What is the recommended practice?
I tried using HQL to select fewer properties, but it seems like it won't partially hydrate an object. I also tried making property on the main object that was a header class with the list view properties, but I couldn't seem to get it mapped properly. I think this should be easy but I've really been struggling with it.
EDIT:
I kept coming back to this because I knew Anton had given me the answer and I just couldn't see it.
There are three things you need to do:
Make an object with the properties you want.
Make a mapping file to import this object.
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
namespace="Core.Entities"
assembly="Core"
default-access="property">
<import class="RequestHeader" />
</hibernate-mapping>
If you are using HQL, your object must contain a constructor with all the properties, in the same order, as your select new statement. If you use the Criteria API, you don't need to do this.
public IList<RequestHeader> ListAll()
{
using (ISession session = GetSession())
{
using (ITransaction tx = session.BeginTransaction())
{
IList<RequestHeader> results = session.CreateCriteria(typeof (Request), "r")
.CreateCriteria("Requestor", "req", JoinType.InnerJoin)
.CreateCriteria("r.Grant", "g", JoinType.InnerJoin)
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("r.Id"), "Id")
.Add(Projections.Property("r.Status"), "Status")
.Add(Projections.Property("r.SubmissionDate"), "SubmissionDate")
.Add(Projections.Property("req.Name"), "Requestor")
.Add(Projections.Property("g.Number"), "Number"))
.SetResultTransformer(Transformers.AliasToBean(typeof (RequestHeader)))
.SetMaxResults(10000)
.List<RequestHeader>();
tx.Commit();
return results;
}
}
}
60 properties is too much. See Component mapping.
As for selecting a subset of properties, see this: you need a select new HQL construct. Be aware, though, that you need an appropriate constructor and that an object you'll get cannot be saved back to the DB.

Resources