Is it possible to sort Cofoundry custom entities by fields in the data model? - cofoundry

Assume a custom entity booking like this:
public class BookingDataModel : ICustomEntityDataModel
{
public DateTime ArrivalDate { get; set; }
}
Is there any way to query the database for custom entities of type Booking and order the result by ArrivalData (besides loading all bookings into to memory and then sort them using C#)? Or is this asking too much of the custom entity framework?
I am aware that the data model is serialized as JSON and as such not readily sortable in SQL (although newer SQL server versions can do it) - but perhaps the Cofoundry framework has some tricks up it's sleeves?

No, as of v0.9 sorting/filtering on custom entity model data is not directly supported. Issue 318 discusses workaround with building a search index, and there are open issues for implementing similar features.

Related

Web API and queries with foreign keys

I'm playing around with Web API, and I'm struggling a bit with creating queries to pull back data based on a filter. The classic example would be pulling back a list of items based on a foreign key.
Let's say I have the following entity:
Movie
======
id
directorId
categoryId
It would not be uncommon for me to build a DAO with the following methods:
MovieRepo.GetByDirector(int directoryId);
MovieRepo.GetByCategory(int category);
Recently, I have been using Linq and the Entity Framework to build retrieval methods that can be used by multiple calling clients, but whose returned list can filtered based on whatever criteria is passed to a filter
public IEnumerable<Movie> Get(MovieFilter filter){
IQueryable<Movie> query = _context.tblMovie;
if(!String.IsNullOrEmpty(filter.directorId))
query.Where(m => m.directoryId == filter.directorId);
if(!String.IsNullOrEmpty(filter.categoryId))
query.Where(m => m.categoryId == filter.categoryId);
return query.ToList();
}
The boilerplate Web API controller actions are:
IEnumerable<Movie> Get();
Movie Get(int id)
If I wanted to filter my query by directory or category with Web API, how exactly would I do it in a RESTful way? Given the way routing gets resolved, the following would be an ambiguous call:
IEnumerable<Movie> GetByCategory(int categoryId);
I haven't see much guidance on this, can someone provide some for me?
Regards,
Chris
One of the ways is to use OData protocol http://www.odata.org/docs/
There is also a library supporting OData filtering http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api, supporting querying over the IQueryable interface
It could be seen as a bit more complex, but you gain a lot. Parts of the OData standard :
$filter - Filters the results, based on a Boolean condition.
$select - which columns/properties should be selected
$inlinecount - Tells the server to include the total count of matching entities in the response. (Useful for server-side paging.)
$orderby - Sorts the results.
$skip - Skips the first n results.
$top - Returns only the first n the results.
Honestly, we are using the OData ... while not using the IQueryable and MS libraries. We just created own parser, supporting only limited stuff. But there is OData standard in place

RavenDB - building dynamic queries

I am building a simple CMS with .NET MVC and RavenDB and i need to filter pages with x amount of incoming parameters.
Example Page:
public class Page{
string Name
string Content
List<string> Tags
//etc...
}
In my pages controller i have this method and i want to get all the pages that have matching tags. they must be excluding filter so it is an AND condition that should be added
public ActionResult Index(List<string> tagFilters)
{
var pages = MyRavenSession.Query<Page>().Where( how to compare tagFilters List to pages Tags List? )
return View(pages);
}
I have been searching the internet for answers on this scenario and there should be others that have the same problem.
How should i solve this?
I read that predicatebuilder could not be translated to RavenDB LINQ queries.
I also read that you could build some kind of RavenDB lucene query but i cannot find any examples.
You can do that by using Session.Advanced.LuceneQuery() it allows fine grained dynamic query building

Entity Framework for Multi-tenant architecture - filterings single table by tenant ID

We are looking for a way of automatically filtering all CRUD operations by a tenant ID in Entity Framework.
The ideas we thought of were:
Using table valued user defined functions
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Any tips?
-thanks
Alex.
Using table valued user defined functions
Table valued function are only available in .NET 4.5 Beta (and not available in code first). Using them will still not help you because you will have to use the function in every LINQ query so it is the same as using where clause.
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
It can be useful for some special complex queries but generally it is not what you want.
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Too complex and on completely different level of abstraction.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Close to ideal solution. You simply need to wrap access to your entity set into some code which will look like:
public class MultiTenantAccess<T> where T : IMultitenant
{
private IDbSet<T> set;
...
public IQueryable<T> GetQuery(int tenantID)
{
return set.Where(e => e.TenantID == tenantID);
}
}
Sometimes this is core for something called Generic repository but it is really just a wrapper around EF set. You will always use GetQuery to query your data store instead of using DbSet directly.
you may also separate the tenants data into different databases
or into same database, but with different schemas? You can read more about this in an old MSDN article called "Multi-Tenant Data Architecture"

Best Way to Write an Asp.Net Web Service To Play Well In the Wild

I am writing an API for my ASP.NET application that other developers will use. The API will basically return a list of people with their first name, last name, and id. There are lots of ways to write web services in ASP.NET, the easiest probably being create a web service function (asmx) that returns a DataTable. This is simple enough for other .NET developers to deal with, but I am not convinced that this is the best way to write a web service for general platform and language independence.
What is the currently accepted standard to write a web service like this that plays well in the wild today?
Some ideas that come to mind from experience:
Use WCF, not .asmx. WCF does all the same things that ASMX files do, and is generally the replacement for ASMX services (see here and here).
Write methods using simple POCO data types, like List<Person> rather than DataTable. Basic types serialize more easily and will make more sense in other programming environments since you want your service to be language independent.
Provide generic CRUD methods for managing data. Depending on how your service will be consumed, if the user needs to modify data, a simple method is to provide getBlah(), updateBlah(obj newObj), deleteBlah(obj objToDelete), etc. that use the same data types.
Hide the details that the service consumer doesn't need to know, rather than just blindly exposing all of your data types, structures, and field names as-is. This will make your service more robust for handling internal changes, and you can simplify and control what the end-users see. For instance, if you have a Person class with 30 properties, and only 5 are relevant to the end-user, provide a class that interfaces between Person and a PersonSimple class which is exposed. Without this layer, your end-users will have to modify your code every time you change your data structure, and you will be locked down by this tight coupling.
If security is important
Execute your service over SSL. This protects data transfered over the wire from being sniffed.
Use authentication, either with a Login method and session, or SOAP headers. Services by default are anonymous unless there is some sort of authentication scheme. Even if you think nobody will find your service because you only provide the URL to your users, it will get out somehow, somewhere, and people will try to misuse the service when it does. Plus, you can control who can do what by different logins and authorization schemes.
I am currently working on a similar issue: A web api service in .NET that receives data tables as input parameters, apply some operations on them (using Table Valued Functions), and return some output data tables.
In your case, you don't need to use a complex class like DataTable; you could use an array (List<>) of a simple class with fields like first name, last name and id. Using Web Api of ASP.NET you could do something like the following:
1) Create a new WebApi project in Visual Studio: For example (in VS 2012) C# > Web > ASP.NET MVC 4 Web Application > select "Wep Api" as project template
You will see a VS project with lots of folders, including one named Models
For help see: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
2) Create a new model code file Person.cs with a class like the following:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string[] Friends { get; set; }
}
3) Create e new controller code file PersonController.cs with methods for getting, inserting and updating records of the database. All the necessary serialization/deserialization (JSON and XML) and data binding is done automatically by the Web Api environment set by the project template.
// Get all the records of persons
public IList<Person> Get()
{
// read database into a list of persons (List<Person>)
// return List<Person>
}
Return record of a selected person:
public Person Get(int id)
{
// read database for a selected person
}
Parameter binding (reading a JSON/XML content sent by http POST into an object, or into a list objects) is also done automatically, as easy as the following:
// parameter binding: Create a Person object with content from XML/JSON
public void ReadPerson(Person p)
{
Trace.WriteLine(Person.Id);
}
public void ReadPersonList(List<Person> plist)
{
Trace.WriteLine(plist.Count);
}

XML Serializiation migration to MySql

I have an ASP.NET project that uses XML Serialization for the main operation for saving data. This project was to stay small relative to size of data. However, the amount of data has ballooned as it always will and now I'm consider moving to a SQL based alternative for managing the data.
For now I have multiple objects defined that are simply storage classes for saving my data for the project to work.
public class Customer
{
public Customer() { }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
public class Order
{
public Order() { }
public int ID { get; set; }
public Date OrderDate { get; set; }
public string Product { get; set; }
}
Something along these lines although not so rudimentary. Migrating to SQL seems to be a no-brainer and I've landed on using MySql because of the free availability of the service. What I'm running into is that the only way I can see to do this now is to have a solution where there is a storage class, Order, and a class built to Load/Save the data, OrderIO.
The project relies heavily on using List<> to populate the data fields on the page. I'm not using any built-in .NET controls such as DataGrid to assist in displaying the data. Simple TextBox or ComboBox controls that are populated on Page_Load.
I'm aware it would make better sense to pick a way in which the data fields could bind to the SQL through a Repeater but I'm not looking at a full redesign, just a difference on the infrastructure to manage the data.
I would like to be able to create a class that can return an object similar to what I'm dealing with now, such as List<>, from the SQL statements I'm executing. I'm having some trouble getting started on the best method of approach.
Any suggestions on how best to Load/Save this data using SQL or some tutorials on ideas using the .NET framework would be helpful. This is quite a generalized question but I'm open to most ideas. Thanks.
What you need is a Data Access Layer (DAL) that takes care of running the SQL code and returning the required data in the List<> format that you require. I would definitely recommend you read the two series of articles by Imar Spaanjar on Building a N-Layer Application. Note that there are two sets of series, but I linked to the second set, because it contains links to the first one.
Also, it might be beneficial to know that Sql Server 2008 R2 express edition is free to use, but has a limit of 10 GB per database. I am not saying that you shouldn't use MySQL, but just wanted to inform you in case you didn't know that there is a free edition of Sql Server available.

Resources