Does Simple.OData.Client support open properties? - c#

I am working with Simple Odata Library
https://github.com/object/Simple.OData.Client/wiki
I need to define open parameters, but i dont seam to see any definition or documentation for this.
Example for clarification:
Along with my oData call, i send a parameter called "mode", which i can set to any number between 0-10. My server will know what to do with it. This parameter however is not pre-defined.

Recent releases of Simple.OData.Client support OData open types, look at examples here:
https://github.com/object/Simple.OData.Client/blob/master/Simple.OData.Client.IntegrationTests/TripPinTests.cs
Search for tests containing "OpenProperty".

user2824991:
I think so. I have tested the untyped and typed scenario for both query and update.
For example:
var order = await client.For("Orders")
.Set(new {OrderId = 9, OrderName = "New Order", MyProperty = "Dynamic Property", GuidProperty = Guid.NewGuid()})
.InsertEntryAsync();
Where, "OrderId" and "OrderName" are both declared properties, while "MyProperty" and "GuidProperty" are both dynamic properties.
Here's my test codes update. it belongs to my sample project.

Related

What's the easiest way to create a managed visualiser in C#?

I have a background in C++ and recently I started working in C#.
I have written following pieces of code (in Visual Studio):
var list_Loads = database.GetData<Load>().ToList();
var test_list = list_Loads.Where(o => (o.Name.Substring(0, 3) == "123")).ToList();
When I run the program and I move my mouse over both lists, first I get the count, which is very useful, but when I ask for the entries, this is what I get:
0 : namespace.Load
1 : namespace.Load
2 : namespace.Load
...
Not very useful, as you can imagine :-)
So my question: how can I show the Name attributes of those objects?
I thought: no problem. I have a background in native visualisers, so it should be rather easy to turn this into useful information, but then it comes:
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Then I found another solution, which comes down to: "Write an entire C# project, debug, test and install it and it might work" (see documentation on "Custom visualisers of data" on the Microsoft website).
I almost choked in my coffee: writing an entire project, just for altering the view of an object??? (While, in C++, you just create a simple .natvis file, mention the classname and some configuration, launch .nvload and that's it.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
By the way, when I try to load a natvis file in Visual Studio immediate window, this is what I get:
.nvload "C:\Temp_Folder\test.natvis"
error CS1525: Invalid expression term '.'
What am I doing wrong?
Thanks in advance
OP (my emphasis):
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
If you just want to specify [DebuggerDisplay] on a type, you don't have to have access to the source code. You can make use of [assembly:DebuggerDisplay()] and control how a type appears in the debugger. The only downside is that [assembly:DebuggerDisplay()] naturally only affects the current assembly whose code your mouse is hovering over. If you wish to use the customised display in other assemblies that you own, then you must repeat the [assembly:DebuggerDisplay()] definition.
Here's an easy before-and-after example with DateTime. I picked DateTime because we generally don't have access to the source code and it has some interesting properties:
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
...which on my machine defaults to:
Maybe I'm fussy and I just want to see:
Day of the week and
Day of the year
...I can do that via:
using System.Diagnostics;
[assembly: DebuggerDisplay("{DayOfWeek} {DayOfYear}", Target = typeof(DateTime))]
...which results in:
Example:
namespace DebuggerDisplayTests
{
public class DebuggerDisplayTests
{
public DebuggerDisplayTests()
{
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
}
}
.
.
.
}
Overrides
[assembly:DebuggerDisplay()] can also be used as a means to override pre-existing [DebuggerDisplay] on a 3-rd party type. Don't like what style they have chosen? Is the type showing far too much information? Change it with [assembly:DebuggerDisplay()].

ArangoDB create edge collection

I tried create collection of edges in c# via ArangoDB-NET driver (https://github.com/yojimbo87/ArangoDB-NET) and this code not working.. My code:
var response = dbClient.Collection.Type(ACollectionType.Edge).KeyGeneratorType(AKeyGeneratorType.Autoincrement).WaitForSync(true).Create(
"EdgesCollection");
dbClient is ADatabase object.
Collection is created but document type is not edge. How can I do?
I'm not familiar with that driver, and your question seems to be related to implementation, not DB functionality. However, my best guess would be to omit the KeyGeneratorType and WaitForSync options:
var cType = ACollectionType.Edge;
var cName = "EdgesCollection";
var response = dbClient.Collection.Type(cType).Create(cName);
If this fails to work, then you may need to review the docs, maybe add some other options like KeyIncrement. Generally, I would accept the defaults and only modify (or provide explicit parameters for) things that you NEED to change (i.e. "don't work").

How to do partial responses using ASP.Net Web Api 2

I'm really new to API design and MVC concepts, but as far as I can tell, something like GET /api/products should return a list of products and GET /api/products/1 should return a single product. In terms of speed my feeling is that /api/products should return less information i.e. just id and name, whereas /api/products/1 should return more i.e. id, name, and description.
As far as I can see, the best way to handle this is to make certain fields of the product class not be returned in the /api/products endpoint. This is especially necessary in the case of /api/products?fields=name . I'm using ASP.Net Web Api 2 and have tried the following:
http://www.nuget.org/packages/WebApi.PartialResponse/ - installing this package caused an assembly version error.
Adding ShouldSerialize methods on the Product fields. For reasons I won't go into here, this method is a little cumbersome.
Looked at ASP.NET Web API partial response Json serialization but there doesn't seem to be a conclusive answer there.
ASP.NET WebApi and Partial Responses suggests using a product class with all nullable fields. I'm not sure I understand exactly what to do there.
Is there any simple way to do what I'm trying to do?
Otherwise could you suggest a better API design than what I'm doing?
You could also use WebApi.PartialResponse (http://www.nuget.org/packages/WebApi.PartialResponse/). It's a package I wrote which uses LINQ to JSON (Json.NET) to manipulate the returned objects. It uses the fields syntax used by Google in their API's, eg.:
fields=items/id,playlistItems/snippet/title,playlistItems/snippet/position
fields=items(id,snippet/title,snippet/position)
fields=items(id,snippet(title,position))
You can find more information on the GitHub project page: https://github.com/dotarj/PartialResponse.
I'd recommend using separate classes to map to when returning a list of entities.
Particularly as the problem is not just what you return to the user, but also what you select from the database.
So, make getting and entity return a Product object, and getting a list of entities return a ProductLink object or something similar.
Edit
As per jtlowe's comment, if you have many different methods returning slight variations of product properties, use anonymous classes (though I'd question whether this is necessarily a good design).
Consider something like this in your action
return from p in this.context.Products
select new
{
p.Id,
p.Name,
p.SKU
};
This:
Only selects the columns you need from the database.
Needs no additional classes defined for new variations of the product
This doesn't make it easy to pass the result of this statement around to other methods because you can only return it as IEnumerable, object or dynamic. If you are putting this in the controller then it may be good enough. If you are implementing a repository pattern, you'll be unable to return strongly typed lists if you use anonymous types.
Stumpled over this topic and just want to share my feelings - maybe it helps others :) I recommend to use something like OData.
You can implement it so that you can write /api/products?$select=Id,Name,Price
some advantages:
with OData you can use further functions, like $filter, $orderby to work with filters and sort it
$skip, $top, $count to get a nice paging
more $-functions :)
you can directly apply it to a IQueryable<T>. Why is this great? You reduce the result not just in the response of your API, but you even reduce the result your database generates, which makes your application much faster. - and you don't even have to change your query
some disadvantages:
you can't filter directly on columns that are calculated
setting it up will take a little time
hint: sometimes it's better to just use ODataQueryOptions<T> in the parameter instead of complete implementation.

Apple's Key Value Coding - can somebody explain to a C# developer why I would need this and what it does?

Before I switched to iOS development via Monotouch I played around a bit with ObjectiveC. Ever since one thing has been on my mind "Key Value Coding" (KVC). I have never understood what it is good for and what the magic behind it is.
For my understanding it is just a collections of names and values, like .NET's NameValueCollection: Instead of setting anObject.Address = "An address Value" you would write anObject.Properties["Address"] = "An address value".
Great. So what? Because this appears to be too easy to me I'm sure that can't be it.
Or is it because .NET has reflection and therefore has no need for something like Key-Value-Coding? I can grab the type of "anObject" and use reflection to loop all of its properties and look for the one called "Address" and then use reflection to set the value.
Is that maybe the analogy of KVC?
I'm hoping there is somebody out there who's a pro in ObjC and C#/.NET who can explain to me what the benefits are and how it would translate into .NET.
Please don't just point me to Apple's documentation. I know all that. I'm trying to find out if something has been missing in my coding-life so far by not knowing KVC? Or have I maybe been using something similar in .NET not being aware that it would translate into KVC if I was using ObjC?
From somebody who uses both every day for probably 3 years now:
As you figured out, there's nothing amazingly complex in KVC that can't be done with dictionaries and NameValueCollections in C#.
The big difference is that KVC is built in the language. An object in Obj-C IS a NameValueCollection. You don't have to change the way you develop (from classes and properties to dictionaries) to use it. You can create your object with the properties you want, and then later on call a valueForKey:#"name", and everything still works.
Now you can say: "yeah cool, but I can do that with reflection!". Sure you can, but just as before, you'll have to change the way you develop again, not counting the fact that reflection is a lot slower in general.
Another cool feature of KVC it it allows you to use KVO, which basically allows you to register to receive notifications about changes in any object without having to write a single line of code in those objects. So, in any object in your application, you can call "addObserver:forKeyPath:", and receive a callback if anybody else in your application changes that property. This is really useful for live apps, like iOS apps.
Again, you can implement KVO in C# (MVVM frameworks for example do this all the time), but you have to write extra code for that. In Obj-C, it's built in the language.
I blogged about this in the context of MonoMac, the peer project to MonoTouch but used for building Mac applications:
http://tirania.org/monomac/archive/2010/Dec-07.html
Key-Value Coding is a set of practices that allow applications to access object properties using strings. This is similar to Binding Expressions in Silverlight. In both cases the purpose is to allow tooling that does not directly have access to your native code to access properties from your program.
In particular, this is useful because some APIs can take advantage of this. For example CoreAnimation can animate properties given their "path" to the object. For example, you can do:
var animateX = CAKeyFrameAnimation.FromKeyPath ("position.x");
pos.Values = new NSNumber [] { 0, 10, 60 };
layer.AddAnimation (animateX, "move");
The "position.x" in this case references the layer's position, and within that position it's X component.
The blog post above goes into more detail about how you can actually expose your own objects to participate in this protocol (registering your own properties to make them visible to the Key-Value-Coding system).
Kenneth, another one of the MonoMac developers blogged about this extensively here:
http://cocoa-mono.org/archives/153/kvc-kvo-and-cocoa-bindings-oh-my-part-1/
In particular he deals with the similarities with Reflection and he shows you how to use [Export] to turn your C# code into KVC compliant code as well.
If you access a property like this
anObject.Address = "An address Value"
The code will be very "static". It will always access Address
You can create a more dynamic code like this
void SetProperty (string propertyName, string value)
{
anObject.Properties[propertyName] = value;
}
You would do this if you do not know at compile time which property will be accessed.
In c# you would typically use a Dictionary<TKey,TValue> for storing key/value pairs. Automatically accessing properties via KVC as in Objective-C is not supported in c#. You would either declare the property as
public Dictionary<string,string> Properties { get; private set; }
and instantiate it in the class constructor with
Properties = new Dictionary<string,string>();
then you could access it like this
anObject.Properties[propertyName] = value;
Or you would have to use Reflection to access the property
Type type = anObject.GetType();
// Or Type type = typeof(TypeOfAnObject);
PropertyInfo prop = type.GetProperty(propertyName);
prop.SetValue(anObject, propertyValue, null);
However, this is not very efficient.

Linq2SQL inherited types and OfType query

I have a setup where I used Linq2SQL inheritance. To make queries easier, I expose the derived types in the DataContext as well, like the following:
public IQueryable<Derived> Derivations
{
get { return Bases.OfType<Derived>(); } // filter list on type
}
Calling this works perfectly, and I can see the SQL being correctly generated. The backing type is DataQuery<T>.
The problem comes in when I assigning this IEnumerable to a datasource (either a control or a BindingSource).
From what I can see, the DataQuery object is queried for an IListSource. And it happily supplies this. Then it proceeds to make a BindingList, which fails as the type parameter of the 2 arguments supplied (IEnumerable<Derived> and Table<Base>) does not match. It raises an exception of MissingMethod as the constructor cannot be found.
The simple workaround is just to call ToList() on the IQueryable<Derived> before assigning to the datasource and then it works, but this is quite tiring.
Any suggestions to handle this without 'loosing' the IQueryable?
Thanks
leppie
UPDATE:
The bug has now been reported to MS. More details here. Thanks Marc!
Confirmed. Looks like a bug to me; you should log it on Connect. The team are fixing LINQ-to-SQL bugs, so it might not be ignored. For now, use .ToList() etc.
Sample code:
using (var ctx = new MyDataContext())
{
var qry = ctx.BaseEntities.OfType<DerivedEntity>();
IListSource ls = (IListSource)qry;
IList list = ls.GetList(); // boom
/* Constructor on type
'System.Data.Linq.Provider.DataBindingList`1[snip]'
not found.*/
}
I had the same issue (still not fixed MS guys!).
To keep the IQueryable I did a .Cast<object>() when assigning to the datasource (i use it to output a xls file from any L2S table i want in a DynamicData website).

Categories