JSON.NET Line serialization winrt - serialization

I'm having some trouble with serializing a ObservableCollection of Lines (Shape). I'm developing for Windows RT and I'm using JSON.NET v5.02. I'm getting the following exception for the code below:
ObservableCollection<Line> lines;
//some code
string linesString = JsonConvert.SerializeObjectAsync(lines); // problem
An exception of type Newtonsoft.Json.JsonSerializationException
occurred in mscorlib.dll but was not handled in user code
Additional information: Error getting value from 'X1' on
'Windows.UI.Xaml.Shapes.Line'.
If there is a handler for this exception, the program may be safely
continued.
Is this a bug and is there a possible workaround?

Your problem is a cross thread problem. When using await JsonConvert.SerializeObjectAsync(lines); that function will be executed in another thread (not the UI thread). Since a Windows.UI.Xaml.Shapes.Line is a UIElement and was created in the UI (main) thread you can't access the properties of the object in another thread. The solution would be to convert it to a simpler object that doesn't have this restrictions.
Besides, a Windows.UI.Xaml.Shapes.Line contains a lot of information, Visibility, IsEnabled etc, I think you would only need the X1, X2, Y1 and Y2. So you could just use this:
string s = await JsonConvert.SerializeObjectAsync(lines
.Select(l => new
{
l.X1,
l.X2,
l.Y1,
l.Y2
}).ToArray());
In this way, you get the properties you need in your UI (main) thread. Then pass that array to the serialize function. This way it works.
string s would now contain:
[{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0},{"X1":20.0,"X2":20.0,"Y1":40.0,"Y2":40.0}]

I am not sure whether Json.Net allow serializing framework class object. I tried with this.
public class CustomLine
{
public double X1 { get; set; }
public double X2 { get; set; }
public double Y1 { get; set; }
public double Y2 { get; set; }
}
I Changed the Line to CustomLine line. If you want to use Line class then retrieve properties X1, X2, Y1, Y2 and then assign it to CustomLine class properties.

Related

asp.net core api - how to distinguish between `api/cars` and `api/cars?color=red` calls with [FromQuery] object

I am using [FromQuery] atribute in controller's Get method:
//CarsController, etc..
[HttpGet]
public async Task<ActionResult<IEnumerable<CarsDto>>> Get([FromQuery] CarsParameter? carsParam = null)
{
//param is always not null here
}
Inside the method I need to distinguish between api/cars and api/cars?color=red calls. Problem is, that carsParam object is never null, so I cannot say if the Color="" (defailt value) is intended to be empty string or it's because of the call was api/cars
CarsParameter is a simple class:
public class CarsParameter
{
public string Color {get; set;} = "";
//more params here
}
Yes, I can use different path, like api/cars/withParams?color=red, but i am looking for more subtle solution.
I need to distinguish between api/cars and api/cars?color=red calls. Problem is, that carsParam object is never null
Please note that default model binding starts by looking through the sources for the key carsParam.Color. If that isn't found, it looks for Color without a prefix, which cause the issue.
To achieve your requirement, you can try to specify prefix explicitly, like below.
public async Task<ActionResult<IEnumerable<CarsDto>>> Get([FromQuery][Bind(Prefix = "carsParam")] CarsParameter? carsParam = null)
{
Request to api/cars?color=red&carsParam.color=yellow&carsParam.brand=test and following is test result

How to support C# dynamic types in an gRPC proto file

We have a POST action in our asp.net core application that accepts a dynamic object.
[HttpPost]
public Task<ActionResult> SubmitAsync(dynamic unitOfWork)
We'd like to transform this POST action to a gRPC server and we'd like to continue receiving dynamic objects in the gRPC service. What is the equivalent of C# dynamic definition in gRPC protobuf file definition? Or if that cannot be achieved what's the best way to receive a dynamic object?
That isn't really a thing right now. In protobuf terms, Any is the closest thing, but I have not yet implemented that in protobuf-net (it is on my short term additions list). The legacy "dynamic types" feature in protobuf-net (that sends type metadata) is actively being phased out, with Any being the preferred route since it allows cross-platform usage and doesn't have the same metadata dependencies.
Frankly, though, I'd probably say "just don't do this"; instead, prefer oneof; it isn't likely that you actually mean "anything" - you probably just mean "one of these things that I expect, but I don't know which", and oneof expresses that intent. More: protobuf-net implements inheritance via oneof, so a good option is something like:
[ProtoContract]
[ProtoInclude(1, typeof(FooRequest))]
[ProtoInclude(2, typeof(BarRequest))]
public abstract class RequestBase {}
[ProtoContract]
public class FooRequest {}
[ProtoContract]
public class BarRequest {}
You can pass messages with fields whose type was not known in advance. You can also pass messages with fields that are not typed, such as dynamic objects that can take any scalar values, and collections null values are allowed.
To do so, import the proto file "google/protobuf/struct.proto" and declare the
dynamic type as google.protobuf.Value.
So, first add bellow line at the top of your proto file:
import "google/protobuf/struct.proto";
Here my sample message with two dynamic fields:
message BranchResponse {
google.protobuf.Value BranchId = 1;
google.protobuf.Value BranchLevel = 2;
}
Note that: the generated type in C# is Value and belongs to the Google.Protobuf.WellKnownTypes namespace, which belongs itself to the Google.Protobuf assembly. This type inherits from the IMessage, IMessage, IEquatable, IDeepCloneable, and IBufferMessage interfaces that all belong to the Google.Protobuf assembly, except for IEquatable, which comes from the .NET System.Runtime assembly. To write and read dynamic values, we have a set of methods available that shown bellow: (these are write static functions)
We can fill BranchResponse model like this:
var branch = new BranchResponse();
branch.BranchId = Value.ForNumber(1);
branch.BranchLevel = Value.ForStruct(new Struct
{
Fields = {
["LevelId"] = Value.ForNumber(1),
["LevelName"] = Value.ForString("Gold"),
["IsProfessional"] = Value.ForBool(true)}
});
The read Value type is straightforward. The Value type has a set of properties that exposes its value in the wanted type. (these are read static functions)
At the end, you need to read data from your response model like this:
Here my c# classes that my response model is supposed to bind to them.
public class BranchModel
{
public int BranchId { get; set; }
public LevelModel Level { get; set; }
}
public class LevelModel
{
public int LevelId{ get; set; }
public string LevelName{ get; set; }
public bool IsProfessional { get; set; }
}
Finally:
var branch = new BranchResponse(); // Received filled from a gRPC call
// Read
var branchModel = new BranchModel
{
BranchId = Convert.ToInt32(branch.BranchId.NumberValue),
Level= new LevelModel
{
LevelId = Convert.ToInt32(branchModel.Level.StructValue.
Fields["LevelId"].NumberValue),
LevelName = branchModel.Level.StructValue.
Fields["LevelName"].StringValue,
IsProfessional = branchModel.Level.StructValue.
Fields["IsProfessional"].BoolValue,
}
};

AutoFixture sometimes failing to generate a value for a property marked with RangeAttribute

I have a very strange behaviour in my testing code at the moment... It all started with decorating a string property with the RangeAttribute. I'm unit testing model validation in ASP.NET Core using the Validator class, so in the example below MyClass is a request object.
As i've understood AutoFixture will take into consideration the attribute a property is marked with. This is what the (pseudo) code looks like:
private void RunTest()
{
var sut = Fixture.Freeze<MyClass>();
sut.MyPropery = "12345";
// all tests from here on fails randomly
}
private class MyClass
{
[Required]
[Range(10000, 99999)]
public string MyPropery { get; set; }
}
Sometimes, the value generated is 10000 (woho!), and sometimes I get the following error, and i'm not sure why:
AutoFixture was unable to create an instance from
Ploeh.AutoFixture.Kernel.RangedNumberRequest, most likely because it
has no public constructor, is an abstract or non-public type.
I'm writing a unit test using "AutoFixture.AutoNSubstitute": "3.49.0"
Any ideas what might be wrong here?

deserialize a class whose assembly and namespace has changed

I have the problem described here:
http://social.msdn.microsoft.com/Forums/en-AU/csharplanguage/thread/b310c71a-2479-4a93-888a-29294cecbe09
They give a solution using a SerializationBinder. Is there another alternative?? Like decorating my classes with a different namespace and assembly?? The reason is that I have some classes with this problem used many times, and I have to add the line "formatter.Binder = ..." in each part of the code. It would be easier to apply my hipothetic second solution.
Thanks.
If the assembly version changes, serialized objects become invalid. I once made changes to the source code of Protobuf-Net to avoid the version check, and it was fairly easy to do so. However, it can lead to unexpected results (data ending up in the wrong fields), unless you avoid the implicit fields, and set an index to each field manually using annotations. That's the advantage or Protobuf-Net, that you have control over the order of the fields in the serialized stream.
Another solution is to use custom serialization? Something like:
[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;
public MyObject()
{
}
protected MyObject(SerializationInfo info, StreamingContext context)
{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter =true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}

Is it OK to call virtual properties from the constructor of a NHibernate entity?

take a look at this example code:
public class Comment
{
private Comment()
{ }
public Comment(string text, DateTime creationDate, string authorEmail)
{
Text = text;
CreationDate = creationDate;
AuthorEmail = authorEmail;
}
public virtual string Text { get; private set; }
public virtual DateTime CreationDate { get; set; }
public virtual string AuthorEmail { get; private set; }
}
i know it's considered bad practice to call virtual member functions from the constructor, however in NHibernate i need the properties to be virtual to support lazy loading. Is it considered OK in this case?
I'm pretty sure this is fine, but if your worried you could always just assign the properties after a parameter less constructor call.
To expand on Paco's answer:
In most cases it doesn't hurt. But if the class is inherited, virtual allows the properties get/set to be overriden, so the behavior is no longer fully encapsulated and controlled, so it can break, in theory. FxCop warns about this because it's a potential problem.
The point of FxCop is to help warn you about potential problems though. It is not wrong to use properties in a constructor if you know you who/what is ever going to inherit from the class, but it isn't officially 'best practice'.
So, the answer is that it's fine as long as you control any inheritence of the class. Otherwise, don't use it and set the field values directly. (Which means you can't use C# 3.0 automatic get/set properties--you'll have to write properties wrapping fields yourself.)
Side note: Personally, all of my projects are web sites that we host for clients. So assuming this setup stays the same for a project, than it's worth the trade-off of having to duplicate the various null/argument checking. But, in any other case where I am not sure that we'll maintain complete control of the project and use of the class, I wouldn't take this shortcut.
It's OK in this sample, but it might cause problems when you inherit the class and override the properties. Generally, you can better create fields for the virtual properties.
IMHO the best-practice is to use properties with backing fields:
public class Comment
{
private DateTime _creationDate;
private string _text;
private string _authorEmail;
private Comment() { }
public Comment(string text, DateTime creationDate, string authorEmail)
{
_text = text;
_creationDate = creationDate;
_authorEmail = authorEmail;
}
public virtual string Text
{
get { return _text; }
private set { _text = value; }
}
public virtual string AuthorEmail
{
get { return _authorEmail; }
private set { _authorEmail = value; }
}
public virtual DateTime CreationDate
{
get { return _creationDate; }
set { _creationDate = value; }
}
}
So you can avoid problems on child classes and you don't see any warning anymore
I know that FxCop complains if you call a virtual method in your constructor, but I don't know what FxCop says whether you're calling a virtual property in your constructor ...
I would think that FxCop will complain as well since a property is translated to a method in IL.
You can also create your properties as 'non-virtual', and just specify 'lazy=false' on your 'class mapping' in NHIbernate.
This won't affect the lazy-load behavior of collections.
(I do it all the time, since I do not like that my infrastructure (NHibernate) requires me to have the properties virtual.
I also don't know whether the performance benefit of having dynamic proxies in NHibernate is significant).
I think, you should not call it in the constructor.
You can provide a method Initialize() which you can call after constructing the object.
In Initialize() you can call the required virtual methods