Silverlight, DataPager, RIA Services, and smart paging - silverlight-3.0

I'm still trying to get my feet on the ground with Silverlight and RIA Services, and of course starting with some of the more "fun" stuff like grids and intelligent paging. I can connect to RIA Services (using a home-grown ORM, not L2S or EF), get data on the grid, and connect to a DataPager. The domain service is working well with the home-grown ORM, at least for queries. (Still working on full CRUD.) However, there are still problems:
To support the user application, I need user-controlled sorting and filtering, in addition to smart paging (only run the query for the rows needed to display) and grouping.
So far, I've seen nothing in the DataGrid or DataPager to externalize these capabilities so that filtering, sorting, and paging parameters can be passed to the server to build the appropriate query.
The datasets are potentially quite large; my table I've chosen for prototyping work can have up to 35,000 entries at some customers, and I'm sure there are other tables far larger that I will have to deal with at some point. So the "smart paging" aspect is essential.
Ideas, suggestions, guidance, and nerf bricks are all welcome.

OK, I've spent a few days in the weeds with this one, and I think I've got a handle on it.
First, an important piece of magic. For paging to work properly, the pager has to know the total item count, no matter how many items were returned by the current query. If the query returns everything, the item count is obviously the number of items returned. For smart paging, the item count is still the total of available items, although the query returns only what gets displayed. With filtering, even the total of available items changes every time the filter changes.
The Silverlight Datapager control has a property called ItemCount. It is readonly and cannot be databound in XAML, or set directly in code. However, if the user control containing the pager has a DataContext that implements IPagedCollectionView, then the data context object must implement an ItemCount property with PropertyChanged notification, and the DataPager seems to pick this up automagically.
Second, I highly recommend Brad Abrams' excellent series of blog posts on RIA Services, especially this one on ViewModel. It contains most of what you need to make paging and filtering work, although it's missing the critical piece on managing the item count. His downloadable sample also contains a very good basic framework for implementing ModelViewViewModel (MVVM). Thank you, Brad!
So here's how to make the item count work. (This code refers to a custom ORM, while Brad's code uses Entity Framework; between the two you can figure you what you need in your environment.)
First, your ORM needs to support getting record counts, with and without your filter. Here's my domain service code that makes the counts available to RIA Services:
[Invoke]
public int GetExamCount()
{
return Context.Exams.Count();
}
[Invoke]
public int GetFilteredExamCount(string descriptionFilter)
{
return Context.Exams.GetFilteredCount(descriptionFilter);
}
Note the [Invoke] attribute. You need this for any DomainService method that doesn't return an Entity or an Entity collection.
Now for the ViewModel code. You need an ItemCount, of course. (This is from Brad's example.)
int itemCount;
public int ItemCount
{
get { return itemCount; }
set
{
if (itemCount != value)
{
itemCount = value;
RaisePropertyChanged(ItemCountChangedEventArgs);
}
}
}
Your LoadData method will run the query to get the current set of rows for display in the DataGrid. (This doesn't implement custom sorting yet, but that's an easy addition.)
EntityQuery<ExamEntity> query =
DomainContext.GetPagedExamsQuery(PageSize * PageIndex, PageSize, DescriptionFilterText);
DomainContext.Load(query, OnExamsLoaded, null);
The callback method then runs the query to get the counts. If no filter is being used, we get the count for all rows; if there's a filter, then we get the count for filtered rows.
private void OnExamsLoaded(LoadOperation<ExamEntity> loadOperation)
{
if (loadOperation.Error != null)
{
//raise an event...
ErrorRaising(this, new ErrorEventArgs(loadOperation.Error));
}
else
{
Exams.MoveCurrentToFirst();
if (string.IsNullOrEmpty(DescriptionFilterText))
{
DomainContext.GetExamCount(OnCountCompleted, null);
}
else
{
DomainContext.GetFilteredExamCount(DescriptionFilterText, OnCountCompleted, null);
}
IsLoading = false;
}
}
There's also a callback method for counts:
void OnCountCompleted(InvokeOperation<int> op)
{
ItemCount = op.Value;
TotalItemCount = op.Value;
}
With the ItemCount set, the Datapager control picks it up, and we have paging with filtering and a smart query that returns only the records to be displayed!
LINQ makes the query easy with .Skip() and .Take(). Doing this with raw ADO.NET is harder. I learned how to do this by taking apart a LINQ-generated query.
SELECT * FROM
(select ROW_NUMBER() OVER (ORDER BY Description) as rownum, *
FROM Exams as T0 WHERE T0.Description LIKE #description ) as T1
WHERE T1.rownum between #first AND #last ORDER BY rownum
The clause "select ROW_NUMBER() OVER (ORDER BY Description) as rownum" is the interesting part, because not many people use "OVER" yet. This clause sorts the table on Description before assigning row numbers, and the filter is also applied before row numbers are assigned. This allows the outer SELECT to filter on row numbers, after sorting and filtering.
So there it is, smart paging with filtering, in RIA Services and Silverlight!

Here's the quick and dirty solution (that I went for):
Just move your DomainDataSource to your ViewModel! Done!
May not exactly be great for testability and probably some other limitations I haven't discovered yet, but personally I don't care about that until something better comes along.
Inside your ViewModel just instantiate the data source :
// Feedback DataSource
_dsFeedback = new DomainDataSource();
_dsFeedback.DomainContext = _razorSiteDomainContext;
_dsFeedback.QueryName = "GetOrderedFeedbacks";
_dsFeedback.PageSize = 10;
_dsFeedback.Load();
and provide a bindable property :
private DomainDataSource _dsFeedback { get; set; }
public DomainDataSource Feedback
{
get
{
return _dsFeedback;
}
}
And add your DataPager to your XAML:
<data:DataPager Grid.Row="1"
HorizontalAlignment="Stretch"
Source="{Binding Feedback.Data}"
Margin="0,0,0,5" />
<data:DataGrid ItemsSource="{Binding Feedback.Data}">
PS. Thanks to 'Francois' from the above linked page. I didn't even realize I could take the DomainDataSource out of the XAML until I saw your comment!

This is an interesting article from May 2010 about the possible future support for this type of feature in the framework.
http://www.riaservicesblog.net/Blog/post/WCF-RIA-Services-Speculation-EntityCollectionView.aspx

Related

BreezeJS count of expanded entities

This is using BreezeJS and a Breeze controller through to an EF provider. I have a couple of related Entities, lets call them Customer, which has a Navigation Property called Orders which links to a set of Order Entities for that customer.
What I'd like to display on the UI is a summary of Order Counts for a set of customers who match a partial name search. I can do this through returning all the Order objects, but they're quite large objects and I don't really want to return 100's of them when I don't have to. The inlineCount() method seems to always give the count of the top-level entity (Customer) rather than of the sub-Entities, no matter where I place it in the statement.
var predicate = breeze.Predicate.create('displayName', 'contains', partialName);
return this.entityQuery.from('Customers')
.where(predicate)
.orderBy('displayName')
.using(this.manager)
.expand('Orders')
.execute();
The documentation suggests that you can chain the expand in some way, but I have yet to find a syntax which is valid.
Ideally, I'd like to apply a where to the Orders by a property on Order called Status of say 0 (incomplete) and then give me just the count of those matching Orders. ie, return me all the Customer entities, but have a matching order count for each (rather than the whole list of Order objects and filter client-side).
Would appreciate any pointers in the right direction if it's possible to achieve. My current thinking is that I'll have to create a custom method on the server-side controller and do the work there, but before I make assumptions about what OData can support, I thought I'd check here for some confirmation.
So far, this is my best approach (maybe someone can correct me if there's a better way).
On the server, add this method:
public IQueryable<object> CustomerSummaries()
{
return Context.Customers.Select(p => new
{
Customer = p,
ActiveOrderCount = p.Orders.Count(o => o.Status == 1)
});
}
Then on the client end:
var predicate = breeze.Predicate.create('customer.displayName', 'contains', partialName);
return this.entityQuery.from('CustomerSummaries')
.where(predicate)
.using(this.manager)
.execute();

Generic pagination with the dapper

I am using dapper and also dapper.contrib.My question is how can I create an generic pagination class.
Here is the what I have tried so far.
public class GenericRepository<T> :IGenericRepository<T> where T : class
{
public async Task<IEnumerable<T>> GetAllPagedAsync(int limit,int offset)
{
var list = await Connection.GetAllAsync<T>();//but this return IEnumarable
return list;
}
}
What I am thinking is get the T name of the class which is the same as Table name,and write an sql string called sql_statement which is apply pagination.later apply this code.
var list = await Connection.QueryAsync<T>("sql_statement")
Does this make sense? I s there any better way to achive that.
It looks currently as though you are planning to retrieve all of the rows in the table and then select from them the page of data you actually require. It would likely be quicker to just select the page you need straight from the database, unless you do actually need all of the rows for some reason.
Assuming that your table names are always going to match exactly with their respective class/entity names, the following will give you a paged result (using postgres):
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public async Task<IEnumerable<T>> GetAllPagedAsync(int limit, int offset)
{
var tableName = typeof(T).Name;
// assuming here you want the newest rows first, and column name is "created_date"
// may also wish to specify the exact columns needed, rather than *
var query = "SELECT * FROM #TableName ORDER BY created_date DESC Limit #Limit Offset #Offset";
var results = Connection.QueryAsync<T>(query, new {Limit = limit, Offset = offset});
return results;
}
}
A note regarding this. I am obviously not familiar with the structure or size of your database, however for most general purposes the limit/offset approach to paging shown here will most probably be sufficient. There are however some potential issues you may wish to consider:
When the offset value gets very large performance may suffer.
Paging tables with a high frequency of inserts in this fashion may cause results to be duplicated/ appear on multiple pages as the offset values does not take into account new rows added to the table since the last retrieval.
Whether or not these are likely to cause issues to your particular case, these potential drawbacks, as well as some alternatives solutions are outlined here.

Constrain the number of child entities in Entity Framework

Bottom Line Up Front
Is there a succinct way that I can constrain the number of child entities that can belong to a parent in Entity Framework. I am using 4.3.1 at the moment.
The Problem
I am developing an ASP.NET MVC3 site which accesses data via a data access layer that uses Entity Framework. I have a SearchList entity which has a many to many relationship to a Search entity. A SearchList may have many Searches, and a Search may belong to many SearchLists.
At one point in the workflow of the site, a user needs to select the searches and other items to use in a batch search. We want the page to load the entire search list.
SearchLists can get quite large, and as a test we created one with 21,000 searches. It took a few seconds, and the data returned was about 9.5 MB, which we were expecting, but jQueryUI choked when trying to table-ify that much.
What we would like
So we want to impose a limit on the number of searches any search list can have. I can go through the application and put a bunch of rules in that checks the size of the collection and if the searches that are trying to be added plus the size of the current... yada yada yada.
If however there was a better way (especially one that could easily output an error message that MVC would pick up) I would totally take that instead.
I have googled, and perused a number of EF blogs to no avail. Constrain children and max number of children in collection and similar searches have returned results that are about Linq queries and the Count and Max methods.
Any help would be appreciated.
There is no built-in way so you will have to code such validation yourselves. Some quick ideas:
You can for example use custom collection for the navigation property which will fire exception when you try to add additional search exceeding the threshold. It is simple but it demands you to have all searches loaded, it will have concurrency problems and moreover it can fire during loading search list and searches from database.
You can handle it in overriden SaveChanges. You will at least have to check how many searches are already related to search list but you will still have concurrency problem (what if other request tries to add search to the same list but only one place is remaining - both can succeed the check and insert related search)
You can handle it in database trigger - again it will have concurrency problems
Avoiding concurrency problems completely requires hand written queries with locking hints to ensure that only one request can check number of searches per search list and insert a new search in atomic transaction.
I ended up going with CustomValidationAttribute, and implemented it with a great deal of success. See below for my implementation info:
In the SearchList entity
[NotMapped]
public String ValidationMessage { get; set; }
[CustomValidation(typeof(EntityValidation.EntityValidators), "ValidateSearchCount")]
public virtual List<Search> Searches { get; set; }
public static bool Create(ProjectContext db, SearchList searchList)
{
try
{
db.SearchLists.Add(searchList);
db.SaveChanges();
return true;
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
searchList.ValidationMessage += validationError.ErrorMessage;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
EntityValidators Class
public static ValidationResult ValidateSearchCount(List<Search> Searches)
{
bool isValid;
int count = Searches.Count();
isValid = (count <= 5000 ? true : false);
if (isValid)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("A maximum of 5000 searches may be added to a SearchList.");
}
}
A similar exception block is on the update method. In this way, when SaveChanges gets called it attempts to validate the entity and its child collections, and when the collection count is greater than 5000 the validator will return an error message which gets caught in the exception handler and stored in a local property for my controller to check when things go wrong.

Asp.Net MVC Entity Framework Parent-Child with overridable values

Ok, so let me explain a little of what I am trying to do.
I have a table called WebsitePage that contains all of the pages on my site with some information about them. Then, I have a Customer table for all of my customers. Then I have another table called CustomerWebsitePage that stores customer values for some of the columns in the WebsitePage table.
So, using the entity framework, I imported these three tables. What I want to be able to do is return a strongly typed WebsitePage list that has any values from CustomerWebsitePage if there are any values for it. So, for example, say one of my customers added a CustomerWebsitePageName for one of my website pages. I want to return a list of WebsitePages that contains the CustomerWebsitePageName instead of the WebsitePage Name in that case. But the original WebsitePage Name for everything else since it wasn't overridden.
The kicker here is that my WebsitePage table has a foreign key to itself for a Parent/Child relationship. So, I also want to return the child WebsitePages at the same time. I tried using a function import to get what I wanted, but then of course I lost the ChildPages.
I have tried just about everything to get what I want using the Entity framework and LINQ. But so far almost everything I try ends up with an exception being thrown. Here are a few:
The EntityCollection has already been initialized
The entity or complex type 'MyEntityModel.WebsitePage' cannot be constructed in a LINQ to Entities query.
I have one idea of how I can get around all this, and that would be to duplicate the ParentPageID into my WebsitePage table, but this really seems to violate a lot of principles and I really just don't want to add the maintenance headache related to this.
Anyone have any ideas how to accomplish this type of thing?
A simple DB diagram. http://images.tehone.com/screenshots/2009-08-17_013009.png
The object that you need to return is a CustomerWebsitePage and not a WebsitePage. The reason is that whatever object you return must know about the customer since the property will need it to determine which field (CustomerPage or WebsitePage) to use.
Considering that, you can have a function CustomerWebsitePage.GetAllPagesForCustomer(Customer c) that would return an enumeration of pages. However, to achieve the functionality you are looking for, you must implement some read-through properties in the CustomerWebsitePage. Let's take the example of Name. Here would be how to implement it in CustomerWebsitePage:
public string Name
{
get{ if( String.IsNullOrEmpty(CustomerWebsitePageName) )
return WebsitePage.Name;
return CustomerWebsitePageName; }
}
For the Children pages, you could have a property:
public IEnumerable<CustomerWebPage> Children
{
get
{
return WebsitePage.Children.Select( it => it.Customer.CustomerID == this.CustomerID ); }
}
Note that with this setup you couldn't run EF Linq queries on these new fields (because they exist only in the objects themselves, not in the database mapping). You can pepper the code with Load() if you want to seamlessly load all the children, but it will cost you in performance. To ensure that all the children are loaded, try the following loading function:
IEnumerable<CusomterWebPage> GetAllPagesForCustomer(Customer c)
{
return Context.CustomerWebPageSet.Include("WebsitePage").Where( it => it.Customer.CustomerID == c.CustomerID );
}

Best practices when limiting changes to specific fields with LINQ2SQL

I was reading Steven Sanderson's book Pro ASP.NET MVC Framework and he suggests using a repository pattern:
public interface IProductsRepository
{
IQueryable<Product> Products { get; }
void SaveProduct(Product product);
}
He accesses the products repository directly from his Controllers, but since I will have both a web page and web service, I wanted to have add a "Service Layer" that would be called by the Controllers and the web services:
public class ProductService
{
private IProductsRepository productsRepsitory;
public ProductService(IProductsRepository productsRepository)
{
this.productsRepsitory = productsRepository;
}
public Product GetProductById(int id)
{
return (from p in productsRepsitory.Products
where p.ProductID == id
select p).First();
}
// more methods
}
This seems all fine, but my problem is that I can't use his SaveProduct(Product product) because:
1) I want to only allow certain fields to be changed in the Product table
2) I want to keep an audit log of each change made to each field of the Product table, so I would have to have methods for each field that I allow to be updated.
My initial plan was to have a method in ProductService like this:
public void ChangeProductName(Product product, string newProductName);
Which then calls IProductsRepository.SaveProduct(Product)
But there are a few problems I see with this:
1) Isn't it not very "OO" to pass in the Product object like this? However, I can't see how this code could go in the Product class since it should just be a dumb data object. I could see adding validation to a partial class, but not this.
2) How do I ensure that no one changed any other fields other than Product before I persist the change?
I'm basically torn because I can't put the auditing/update code in Product and the ProductService class' update methods just seem unnatural (However, GetProductById seems perfectly natural to me).
I think I'd still have these problems even if I didn't have the auditing requirement. Either way I want to limit what fields can be changed in one class rather than duplicating the logic in both the web site and the web services.
Is my design pattern just bad in the first place or can I somehow make this work in a clean way?
Any insight would be greatly appreciated.
I split the repository into two interfaces, one for reading and one for writing.
The reading implements IDisposeable, and reuses the same data-context for its lifetime. It returns the entity objects produced by linq to SQL. For example, it might look like:
interface Reader : IDisposeable
{
IQueryable<Product> Products;
IQueryable<Order> Orders;
IQueryable<Customer> Customers;
}
The iQueryable is important so I get the delayed evaluation goodness of linq2sql. This is easy to implement with a DataContext, and easy enough to fake. Note that when I use this interface I never use the autogenerated fields for related rows (ie, no fair using order.Products directly, calls must join on the appropriate ID columns). This is a limitation I don't mind living with considering how much easier it makes faking read repository for unit tests.
The writing one uses a separate datacontext per write operation, so it does not implement IDisposeable. It does NOT take entity objects as input or out- it takes the specific fields needed for each write operation.
When I write test code, I can substitute the readable interface with a fake implementation that uses a bunch of List<>s which I populate manually. I use mocks for the write interface. This has worked like a charm so far.
Don't get in a habit of passing the entity objects around, they're bound to the datacontext's lifetime and it leads to unfortunate coupling between your repository and its clients.
To address your need for the auditing/logging of changes, just today I put the finishing touches on a system I'll suggest for your consideration. The idea is to serialize (easily done if you are using LTS entity objects and through the magic of the DataContractSerializer) the "before" and "after" state of your object, then save these to a logging table.
My logging table has columns for the date, username, a foreign key to the affected entity, and title/quick summary of the action, such as "Product was updated". There is also a single column for storing the change itself, which is a general-purpose field for storing a mini-XML representation of the "before and after" state. For example, here's what I'm logging:
<ProductUpdated>
<Deleted><Product ... /></Deleted>
<Inserted><Product ... /></Inserted>
</ProductUpdated>
Here is the general purpose "serializer" I used:
public string SerializeObject(object obj)
{
// See http://msdn.microsoft.com/en-us/library/bb546184.aspx :
Type t = obj.GetType();
DataContractSerializer dcs = new DataContractSerializer(t);
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlWriter writer = XmlWriter.Create(sb, settings);
dcs.WriteObject(writer, obj);
writer.Close();
string xml = sb.ToString();
return xml;
}
Then, when updating (can also be used for logging inserts/deletes), grab the state before you do your model-binding, then again afterwards. Shove into an XML wrapper and log it! (or I suppose you could use two columns in your logging table for these, although my XML approach allows me to attach any other information that might be helpful).
Furthermore, if you want to only allow certain fields to be updated, you'll be able to do this with either a "whitelist/blacklist" in your controller's action method, or you could create a "ViewModel" to hand in to your controller, which could have the restrictions placed upon it that you desire. You could also look into the many partial methods and hooks that your LTS entity classes should have on them, which would allow you to detect changes to fields that you don't want.
Good luck! -Mike
Update:
For kicks, here is how I deserialize an entity (as I mentioned in my comment), for viewing its state at some later point in history: (After I've extracted it from the log entry's wrapper)
public Account DeserializeAccount(string xmlString)
{
MemoryStream s = new MemoryStream(Encoding.Unicode.GetBytes(xmlString));
DataContractSerializer dcs = new DataContractSerializer(typeof(Product));
Product product = (Product)dcs.ReadObject(s);
return product;
}
I would also recommend reading Chapter 13, "LINQ in every layer" in the book "LINQ in Action". It pretty much addresses exactly what I've been struggling with -- how to work LINQ into a 3-tier design. I'm leaning towards not using LINQ at all now after reading that chapter.

Resources