Something akin to "Sparse Fieldsets" in .NET - asp.net

I'm trying to find the vocabulary to describe what I want and if it exists.
I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?
I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.
Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.
Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:
_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
.Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
.Include(f => f.Recipe)

Maybe you are looking for Anonymous Types?
For example, if you had a typed object with three properties, but you only wanted to operate on two:
var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };
var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.
Typically, when passing data around in c#, you want to have it typed.

C# is a strongly-typed language and I would say that it is unusual for C# to support scenarios, when object definition (properties) are not known in advance, like in JSON API "fields" parameter case. Implementing this would imply using reflection to filter the properties, which is usually slow and error-prone.
When implementing C# web-services, people usually create one DTO response model per each request.
If your table has fixed set of fields, I would personally recommend to create a DTO class containing only the fields which are required for your table, and then create a method which returns this response for your specific request. While it doesn't align with "without having to define a new object" in the question, it makes the intention clear and makes it really easier to maintain the API in future.
You might want to use libraries like AutoMapper to save time and avoid duplicated code of copying the values from data model to DTO, if you have many such methods.

Related

is it possible to get the Entity object before objectify saves it (and fill some other data)

I have some personal data structure mixed with "standard fields". I would like to avoid the manual work on simple fields (with datastore native API):
toPersist.setProperty("field1", value1);
toPersist.setUnindexedProperty("field2", value2);
but I still want to get the prefilled Entity instance toPersist so I can add my own #Ignore fields my self
For example:
Entity filled = OfyService.ofy().save().entity(this).fill();
filled.setProperty("mySpecialField", jsonValue);
//...
// I want to save my entities alone
datastore.put( filled );
reversely I'd like to get the Entity object representing each entry in a load() call.
Is this possible? or do I have to dive into Objectify code to hack it?
thanks for your answers
I don't follow your question exactly, but I'm pretty sure what you're looking for are the #OnLoad and #OnSave annotations. You add them to methods within your entity classes, and those methods will be called just after an entity is loaded, or just before one is saved, respectively. The documentation for them is here.
Edit:
After your comments (below) I now understand what you are trying to accomplish. Yes, Objectify supports this (though I have never tried it myself). You want to use the Saver.toEntity() and Loader.fromEntity() methods. It appears you can use them like this:
// Use Objectify to convert a POJO into an Entity
Entity filled = ofy().save().toEntity(myPojo);
// Use Objectify to convert an Entity into a POJO
Object pojoCopy = ofy().load().fromEntity(filled);

NHibernate.IFutureValue<> when serialized includes .Value

I'm building an ASP.NET (2.0, no, I can't change it) site with NHibernate, and have a custom JSON converter so I can not-serialize properties I want hidden from the client. This lets me just return the objects, and never have to worry about their serialized values - they're always secure.
Unfortunately, it appears that if I use query.FutureValue<class>(), the object that gets serialized is first the NHibernate.Impl.FutureValue<class> and not my entity, which means I get JSON that looks like this if I throw it in a dictionary and return it to the client:
{key: { Value: { /* my serialized object properties */ } }
Previously I discovered that I can't get any interfaces to work in ASP's JavaScriptConverter implementations... only regular or abstract classes. So returning typeof(IFutureValue<MyBaseClass>) as a supported type means my converter is completely ignored. I can catch MyBaseClass, because I refactored things earlier to use an abstract base instead of an interface, but not the interface.
And then I discover that the FutureValue implementation in .Impl is internal to the assembly, or some other such nonsense that only serves to make my .NET experience even more painful. So I can't use typeof(FutureValue<MyBaseClass>) to handle it all, because FutureValue exists only in my debugging sessions.
Is there a way to get the class type out of the assembly? Or a way to convince ASP that interfaces do in fact have uses? Or might there be some superclass I can access that would let me get around the whole issue?
Help! I like my Futures, it lets me batch a whole heck-ton of calls at once!
(if something isn't clear, or you want more code, by all means, ask! I can post quite a bit.)
If I'm understanding you correctly, it seems you are mixing things a together a little bit.
It sounds like you're trying to serialize an instance of query.FutureValue<class>(), which unsurprisingly gives you just that: a JSON object where the Value fields has JSON representing your entity.
To me it sounds like you really want to just serialize query.FutureValue<class>().Value.
Using NHibernate futures like this gives you little benefit though, so you're probably after something like:
var future1 = query1.FutureValue<SomeEntity>();
var future2 = query2.FutureValue<AnotherEntity>();
var json1 = serializer.Serialize(future1.Value); //<BAM! Multi-query gets fired!
var json2 = serializer.Serialize(future2.Value);
Does that make sense?

Creating custom objects for wcf

I have an existing web application that uses EF and POCO objects. I want to improve the client experience by exposing some of my objects through WCF(JSON). I have this working fine but where I am unsure is how to handle derived objects(not sure if that is the correct term) or IEnumerable anonymous objects if you will.
Let's say I have 3 tables structured like so:
Templates
ID
Template
Groups
ID
Group
Instances
ID
TemplateID
GroupID
This is obviously a one-to-many type relationship. I have my navigation properties setup correctly and getting strongly typed object properties works great. However, how do I send serialized anonymous type object(s) over the wire. Like an object that sends all instances that are equal to groupid=1 and include the names of the template and the object.
Am I missing something or do I have to create another class object for WCF that would look like this:
WCF Object
InstanceID
TemplateID
TemplateName
GroupID
GroupName
I guess I could alter my tables to account for this but that seems wrong too. I know that IEnumerable objects can't be serialized and I know that throw away objects are probably not the way to go either. I want to do this the right way but I am not sure how to go about it.
Your suggestions are appreciated.
Regards
Based on what you're doing, I'd suggest looking at OData with WCF Data Services. You state that you want to be able to send all instances where the groupid=1 - OData is great at this type of filtering.
If you're want to stick with your current approach and not use OData, then my first question is why are you sending back anonymous types at all? You can do what you are seeking (all instances with a groupid=1) without sending back an anonymous type. In your select clause you just create new instances of your concrete objects rather than newing up anonymous types. If your query is really just filtering and not executing any meaningful projection with the selct to anonymous type, then I don't see any reason to send back your anonymous type at all.

Passing a web service an unknown number of parameters

I'm relatively new to utilizing web services. I'm trying to create one that will be accepting data from a ASP.Net form whose input controls are created dynamically at runtime and I don't how many control values will be getting passed.
I'm thinking I'll be using jQuery's serialize() on the form to get the data, but what do I have the web service accept for a parameter? I thought maybe I could use serializeArray(), but still I don't know what type of variable to accept for the JavaScript array.
Finally, I was thinking that I might need to create a simple data transfer object with the data before sending it along to the web service. I just didn't wanna go through with the DTO route if there was a much simpler way or an established best practice that I should follow.
Thanks in advance for any direction you can provide and let me know I wasn't clear enough, or if you have any questions.
The answer to the headline question (assuming this is an ASP.Net web service) is to use the params keyword in your web service method:
[WebMethod]
public void SendSomething(params string[] somethings)
{
foreach (string s in somethings)
{
// do whatever you're gonna do
}
}
Examples:
SendSomething("whatever");
SendSomething("whatever 1", "whatever 2", "whatever 3");
In fact, you don't really even need the params keyword - using an ordinary array as a parameter will let you pass in an unknown number of values.
Well I went with creating my own data transfer object which I guess was always the front of brain solution, I was just thinking that there was probably a recognized best practice on how to handle this.

DLR and reflection

Everywhere I read about the new DLR in .net 4, they say that a good use for it is reflection, and the code snippet always shown is something like
dynamic d = GetSomeObject();
d.DoSomething();
d.SomeMember = 1;
What does GetSomeObject() look like? I can't find anywhere that explains that.
I understand that it can be anything, but in the context of reflection what is it? Is it the assembly? an instance of a type?
The return type of GetSomeObject() will be an instance of some type. For example, here's what it might look like:
public Customer GetSomeObject() {
return new Customer("John", "Doe", 12345);
}
And then the code would say:
dynamic customer = GetSomeObject();
string s = customer.FirstName;
// now the "s" variable would have "John" in it
The GetSomeObject() can return anything. It might return a Customer object or a Product. And it doesn't matter! The idea is that when the variable is declared as being dynamic that when you call a method or a property, as you have shown, the compiler will generate code that uses Reflection to try and call the method or property. If they exist then the calls will succeed. If not then you'll get an error at runtime.
In the general case this example is just simplifying the usage of Reflection by having the compiler generate the code for you.
Having said that, if the Customer or Product object implement IDynamicObject themselves then they can do far more advanced stuff.
What you are describing is the duck-typing aspect of dynamic (there are other facets). The answer is that it could be anything:
a true dynamic object (IDynamicObject)
any regular object, via reflection
A useful example (for reading properties, at least) might be an anonymous type; it could also be a COM object, for example - or (in Silverlight) an object in the html DOM. Or it could be your vendor's Customer object that doesn't implement any common interface, but is remarkably like your own InternalCustomer object. Heck, it could be an IronPyton object.
Well, GetSomeObject() could, for instance, return an instance of type _ComObject. That's one of the primary reasons of having it dynamic, I think.
I think that it's more interesting, as far as dynamic, DLR and reflection concerns, to see what happend in line 2 for instance.
using dynmic you go like this
dynamic d = GetSomeObject();
d.DoSomething();
while with reflection it's a bit more noisy
var d = GetSomeObject();
var mi = d.GetType().GetMethod("DoSomething");
mi.Invoke(d,mi);
As I see it, the first one is more elegant and we are talking about an argument less method, things can go really crazy when you are interoping with COM or APIs with long signature methods. I been there ;)

Categories

Resources