Extension method .ToJsv() from ServiceStack.Text ignores null values in collections - servicestack

My test class:
public class TestA
{
public IEnumerable<string> Collection { get; set; }
}
When I call extension method .ToJsv() from ServiceStack.Text on TestA object with property Collection which is an array with some null values, the result does not contain null values. Even setting JsConfig.IncludeNullValues = true; does not bring the solution.
Test code:
var obj = new TestA { Collection = new[] { "T", null } };
var result = obj.ToJsv(); //here I get {Collection:[T,]} instead of {Collection:[T,null]}
Thanks for any suggestions.

Given its format JSV can’t serialize null values as they’d be indistinguishable from the ‘null’ literal string so it’s lack of a value is what indicates a property is null, but that’s no something that’s you’ll be able to rely on if you want to send null items in a collection in which case you’d need to special casing like maintaining which items are null in a different property or you’d need to use a different serializer.

Related

Check if ListBoxFor selectedValues is null before display in view?

I have a number of ListBoxFor elements on a form in edit mode. If there was data recorded in the field then the previously selected items are displaying correctly when the form opens. If the field is empty though an error is thrown as the items parameter cannot be null. Is there a way to check in the view and if there is data to use the ListBoxFor with the four parameters but if there isn't to only use three parameters, leaving out the selected items?
This is how I'm declaring the ListBoxFor:
#Html.ListBoxFor(model => model.IfQualityPoor, new MultiSelectList(ViewBag.IfPoor, "Value", "Text", ViewBag.IfQualityPoorSelected), new { #class = "chosen", multiple = "multiple" })
I'm using the ViewBag to pass the ICollection which holds the selected items as the controller then joins or splits the strings for binding to the model field. The MultiSelectLists always prove problematic for me.
Your question isn't entirely clear, but you're making it way harder on yourself than it needs to be using ListBoxFor. All you need for either DropDownListFor or ListBoxFor is an IEnumerable<SelectListItem>. Razor will take care of selecting any appropriate values based on the ModelState.
So, assuming ViewBag.IfPoor is IEnumerable<SelectListItem>, all you need in your view is:
#Html.ListBoxFor(m => m.IfQualityPoor, (IEnumerable<SelectListItem>)ViewBag.IfPoor, new { #class = "chosen" })
The correct options will be marked as selected based on the value of IfQualityPoor on your model, as they should be. Also, it's unnecessary to pass multiple = "multiple" in in your htmlAttributes param, as you get that just by using ListBoxFor rather than DropDownListFor.
It's even better if you use a view model and then add your options as a property. Then, you don't have to worry about casting in the view, which is always a good way to introduce runtime exceptions. For example:
public class FooViewModel
{
...
public IEnumerable<SelectListItem> IfQualityPoorOptions { get; set; }
}
Then, you set this in your action, before returning the view (instead of setting ViewBag). Finally, in your view:
#Html.ListBoxFor(m => m.IfQualityPoor, Model.IfQualityPoorOptions, new { #class = "chosen" })
Much simpler, and you'll never have any issues doing it that way.
UPDATE (based on comment)
The best way to handle flattening a list into a string for database storage is to use a special property for that, and then custom getter and setter to map to/from. For example:
public string IfQualityPoor
{
get { return IfQualityPoorList != null ? String.Join(",", IfQualityPoorList) : null; }
set { IfQualityPoorList = !String.IsNullOrWhiteSpace(value) ? value.Split(',').ToList() : null; }
}
[NotMapped]
public List<string> IfQualityPoorList { get; set; }
Then, you post to/interact with IfQualityPoorList, and the correct string will be set in the database automatically when you save.

For use of constructor in c#

I have a class that has 2 properties and a constructor:
public class Card
{
public int CardName {get;set;}
public bool IsActive {get;set;}
public Card (int cardName, bool isActive)
{
CardName = cardName;
IsActive = isActive;
}
}
How do I force the developer to use the constructor instead of doing the following:
var card = new Card{ CardName = "blab", IsActive = true };
On a side note, what is the statement above called? Is that a lazy loading statement?
You already have.
By not having an empty constructor you've removed the ability to use the object initializer method of creating an object.
This:
var card = new Card{ CardName = "blab", IsActive = true };
is the same as this
var card = new Card() { CardName = "blab", IsActive = true };
And in this context new Card() is not valid.
That depends on why you want to prevent the syntax in question.
The object initializer syntax is shorthand for setting a bunch of properties immediately after construction. That is, this:
var c = new Card { CardName = "foo", IsActive = true };
Is semantically identical to this:
var c = new Card();
c.CardName = "foo";
c.IsActive = true;
In both cases, a constructor does run, but its immediately followed by a series of property initializers to apply to the new object.
In your case, since there is no parameterless constructor, you cannot use the object initializer syntax the way you posted. However, it is legal to pass constructor parameters along with the object initializer, so the following would be legal for your class:
var c = new Card("", false) { CardName = "foo", IsActive = true };
(One could argue that this syntax makes the meaning of values more clear than simply passing them to a constructor; one could also argue its just being excessively stubborn :) I could go either way)
You could prevent this second syntax from working by removing the public setters for those properties. If your goal is to prevent the user from changing the values passed into the constructor, making an immutable Card object, for example, that would be the way to go.
I should point out, though, that if one of my juniors asked me this question at work I'd really want to know why they found it necessary to prevent object initialization from being used. There are valid reasons, of course, but they are usually not the source of the question. Object initializers are a good thing -- there are cases where this syntax is very convenient (particularly with LINQ) and I use it all the time.
If you do some kind of setup in the constructor based on the initial values, but those properties are public-settable, you already have to deal with a case where the user changes those values after construction. If your goal is merely to ensure that some "setup" code happens when the object is first constructed, put that code into a default constructor and chain them together:
public class Card
{
public string CardName { get; set; }
public bool IsActive { get; set; }
public Card()
{
// setup code here.
}
public Card ( string name, bool active )
: this()
{
this.CardName = name;
this.IsActive = active;
}
}
Declare the getters of the property as 'Private'.
Something like Public int CardName {private get; set;}.

ServiceStack.Text serializing dictionaries

I was using Json.Net to serialize dictionaries of type Dictionary, and when I added integers or booleans to the dictionary, when deserializing I would get integers and booleans back.
Now I was trying to change my code to use ServiceStack.Text instead because of a problem in other part of the code with the serialization of dates, but now I get the booleans an integers as strings after deserialization. Is there any way to have the same behaviour as Json.Net?
Here's the code to reproduce it: https://gist.github.com/1608951
Test_JsonNet passes, but both Test_ServiceStack_Text_TypeSerializer and Test_ServiceStack_Text_JsonSerializer fail
For untyped dynamic payloads it's better to use the JSON Utils in ServiceStack.Common which lets you parse dynamic payloads whilst preserving their type, e.g:
var obj = JSON.parse(json);
if (obj is new Dictionary<string, object> jsonObj)
{
int b = (int)jsonObj["b"];
bool c = (bool)jsonObj["c"];
}
It's a purposeful design decision in ServiceStack.Text JSON Serializer that no type information is emitted for primitive value types which is why the values are left as strings.
You either have to deserialize into a strong typed POCO that holds the type info:
public class MixType
{
public string a { get; set; }
public int b { get; set; }
public bool c{ get; set; }
}
var mixedMap = new Dictionary<string, object> {
{ "a", "text" },
{ "b", 32 },
{ "c", false },
};
var json = JsonSerializer.SerializeToString(mixedMap);
Console.WriteLine("JSON:\n" + json);
var mixedType = json.FromJson<MixType>();
Assert.AreEqual("text", mixedType.a);
Assert.AreEqual(32, mixedType.b);
Assert.AreEqual(false, mixedType.c);
Or deserialize into a Dictionary<string,string> and parse into specific types yourself.
Or deserialize using ServiceStack's dynamic API. See ServiceStack's Dynamic JSON Test folder for examples on how to do this.
You can now do this:
JsConfig.TryToParsePrimitiveTypeValues = true;
Which will make the JSON deserialiser try to determine what the types should be, and you will get your integers back as integers, booleans back as booleans, etc.

'Unexpected element: XX' during deserialization MongoDB C#

I'm trying to persist an object into a MongoDB, using the following bit of code:
public class myClass
{
public string Heading { get; set; }
public string Body { get; set; }
}
static void Main(string[] args)
{
var mongo = MongoServer.Create();
var db = mongo.GetDatabase("myDb");
var col = db.GetCollection<BsonDocument>("myCollection");
var myinstance = new myClass();
col.Insert(myinstance);
var query = Query.And(Query.EQ("_id", new ObjectId("4df06c23f0e7e51f087611f7)));
var res = col.Find(query);
foreach (var doc in res)
{
var obj = BsonSerializer.Deserialize<myClass>(doc);
}
}
However I get the following exception 'Unexpected element: _id' when trying to Deserialize the document.
So do I need to Deserialize in another way?? What is the preferred way of doing this?
TIA
Søren
You are searching for a given document using an ObjectId but when you save an instance of MyClass you aren't providing an Id property so the driver will create one for you (you can make any property the id by adding the [BsonId] attribute to it), when you retrieve that document you don't have an Id so you get the deserialization error.
You can add the BsonIgnorExtraElements attribute to the class as Chris said, but you should really add an Id property of type ObjectId to your class, you obviously need the Id (as you are using it in your query). As the _id property is reserved for the primary key, you are only ever going to retrieve a single document so you would be better off writing your query like this:
col.FindOneById(new ObjectId("4df06c23f0e7e51f087611f7"));
The fact that you are deserializing to an instance of MyClass once you retrieve the document lends itself to strongly typing the collection, so where you create an instance of the collection you can do this
var col = db.GetCollection<MyClass>("myCollection");
so that when you retrieve the document using the FindOneById method the driver will take care of the deserialization for you putting it all together (provided you add the Id property to the class) you could write
var col = db.GetCollection<MyClass>("myCollection");
MyClass myClass = col.FindOneById(new ObjectId("4df06c23f0e7e51f087611f7"));
One final thing to note, as the _id property is created for you on save by the driver, if you were to leave it off your MyClass instance, every time you saved that document you would get a new Id and hence a new document, so if you saved it n times you would have n documents, which probably isn't what you want.
A slight variation of Projapati's answer. First Mongo will deserialize the id value happily to a property named Id which is more chsarp-ish. But you don't necessarily need to do this if you are just retrieving data.
You can add [BsonIgnoreExtraElements] to your class and it should work. This will allow you to return a subset of the data, great for queries and view-models.
Try adding _id to your class.
This usually happens when your class doesn't have members for all fields in your document.
public class myClass
{
public ObjectId _id { get; set; }
public string Heading { get; set; }
public string Body { get; set; }
}

Adding different object types to a c# 4.0 collection

I have a function that returns objects of different types based on the parameter passed to this function.
Is it possible to add these different object types to a collection based on some identifier in C# 4.0?
Usually we do something like this
List or List
but i want one collection which can add object of any type.
Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.
Yes, it is called object. Eg:
var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");
You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.
Really your collection should be as specific as you can make it. When you say
objects of different types
Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>
Otherwise List<object> will do what you want.
Update
No, not really.
I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.
You also have have a similar switch statement in your factory method that creates the object.
One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".
Can I ask, why are you putting different objects into the same collection? What's the benefit to you?
If you want a collection which can add objects of any type then List<object> is the most appropriate type.
Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object.
When you need to use them, you can just cast it to the original type.
You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().
Also check out Dynamic type.
http://msdn.microsoft.com/en-us/library/dd264736.aspx
It will basically do the same thing.
My Suggestion:
public class ParamValue
{
object value = null;
public ParamValue(object val)
{
value = val;
}
public string AsString()
{
return value.ToString();
}
public int AsInt()
{
return int.Parse(value.ToString());
}
public int? AsNullableInt()
{
int n;
if (int.TryParse(value.ToString(), out n))
{
return n;
}
return null;
}
public bool AsBool()
{
return bool.Parse(value.ToString());
}
public bool? AsNullableBool()
{
bool b;
if (bool.TryParse(value.ToString(), out b))
{
return b;
}
return null;
}
}
public class Params
{
Dictionary<string, object> paramCol = new Dictionary<string, object>();
public void Add(string paramName, object value)
{
paramCol.Add(paramName, value);
}
public ParamValue this[string paramName]
{
get
{
object v;
if (paramCol.TryGetValue(paramName, out v))
{
return new ParamValue(v);
}
return null;
}
}
}
Use param class as a collectio to your values, you can convert the return to every type you want.
You could use a Tuple of Genric Types
public Tuple<T, T> MySuperMethod()
{
int number = 1;
string text = "Batman";
return new Tuple<int, string>(number, text);
}
The .NET Framework directly supports tuples with one to seven
elements. In addition, you can create tuples of eight or more elements
by nesting tuple objects in the Rest property of a Tuple object.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx

Resources