Recursion Limit Exceeded in javascriptSerializer.serialize - c#

I'm using JavascriptSerializer to convert the list into string, but its not working and its throwing an error as Recursion Limit Exceeded. I have searched a lot but i didn't found any solutions to overcome this issue.
My conversion is like below
List<CustomType> _customValues= serializer.ConvertToType<List<CustomType>>(dictionary["CustomValues"]);
string CustomString = new JavaScriptSerializer().Serialize(_customValues);
EDIT
My custom type is below
public class CustomType
{
private string _name;
public string Name
{
get
{ return _name; }
set
{
if (this._name != value)
{
this._name= value;
}
}
}
private double _mark;
public double Mark
{
get
{ return _mark; }
set
{
if (this._mark!= value)
{
this._mark= value;
}
}
}
private int _id;
public int Id
{
get
{ return _id; }
set
{
if (this._id!= value)
{
this._id= value;
}
}
}
}
How can i convert that list into string?.
How can i overcome this issue?.
Thanks,
Karthik

Use a JSON Serializer that ignores circular references. System.Web.Script.Serialization.JavaScriptSerializer can't ignore circular references and will easily get stuck in recursion and reach recursion limit.

Related

Get and Set String Property returning Empty Property

I'm trying to get and set a property using the following code.
But the when trying to print the property using Console,it returns an empty string.Why is the property not getting set?
using System;
public class Program
{
public static void Main()
{
myclass x=new myclass();
x.myproperty="test";
Console.WriteLine(x.myproperty);
}
class myclass{
string sample;
public string myproperty
{
get { return sample;}
set {sample=myproperty;}
}
}
}
In setter you should use value to assign new value to underlying field
use this instead
public string myproperty
{
get { return sample; }
set { sample = value; }
}
or in C#7
public string myproperty
{
get => sample;
set => sample = value;
}
Edit
As #bradbury9 mentioned, you can also use auto-implemented properties, of course this is the case if you don't want any other logic in getter and setter than just getting and setting the field, if this is the case you can use below snippet
public string myproperty { get; set; }
value keyword is important for setting the value. In Visual Studio you can use propfull + double tab to avoid such common mistakes. It will create full property through shortcuts.
Here is the solution
public static void Main()
{
myclass x = new myclass();
x.myproperty = "test";
Console.WriteLine(x.myproperty);
}
class myclass
{
string sample;
public string myproperty
{
get { return sample; }
set { sample = value; }
}
}
If you just want to return null instead of empty string. This works even when you deserialize your Json:
class myclass
{
string sample;
[JsonProperty("my_property")]
public string My_property
{
get { return sample; }
set { sample = string.IsNullOrEmpty(value) ? null : value; }
}
}

List of objects in C# / Unity and yearly check

I've been working on this app about trees and have found myself stuck. What I have is a Tree class with some attributes to it, like ID, type and others. I need to be able to make a List or some other structure of a user-entered number of trees and have each tree be separately modified (in terms of its attributes). Now a problem I ran into is the fact that I need to have separate attributes for each tree each year (2017, 2018 and so on) since the installation of the app. I seem to not be able to think of a viable solution for this to work. How would I set separate attributes for each year? Hell, how would I even check when a new year is and update the list accordingly? I need the yearly attributes because I need to label a tree that hasn't had problems the past five years as "strong".
Here's the code for my simple Tree class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tree : MonoBehaviour {
public string leafType { get { return leafType; } set { } }
public string leafGender { get { return leafGender; } set { } }
public string fruitType { get { return fruitType; } set { } }
public string fruitProblems { get { return fruitProblems; } set { } }
public string bloomingStart { get { return bloomingStart; } set { } }
public string bloomingEnd { get { return bloomingEnd; } set { } }
public string kgHazelnutPerYear { get { return kgHazelnutPerYear; } set { } }
public string problemsInLeaf { get { return problemsInLeaf; } set { } }
public string pests { get { return pests; } set { } }
public string usedPesticides { get { return usedPesticides; } set { } }
public string altitude { get { return altitude; } set { } }
public string region { get { return region; } set { } }
}
Thanks in advance!
you can use Dictionary to manipulate it like bellow
void addYear(string year, Dictionary<string, List<YourTreeClass>> data)
{
if (!data.ContainsKey(year)) data.Add(year, new List<YourTreeClass>());
}
void addTree(string year,YourTreeClass tree, Dictionary<string, List<YourTreeClass>> data)
{
data[year].Add(tree);
}
Dictionary<string, List<YourTreeClass>> data = new Dictionary<string, List<YourTreeClass>>();
addYear("2017", data);
addTree("2017", tree1, data);
addTree("2017", tree2, data);
addYear("2018", data);
addTree("2018", tree3, data);

How to add edges by unwind using neo4jclient?

The nodes have existed.
I tried to add edges by unwind,but my function importBuyConnectionIntoNeo4j didn't work,
Is there any one can help me?
the data structure:
class Connection
{
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
private string source;
public string Source
{
get { return source; }
set { source = value; }
}
private string target;
public string Target
{
get { return target; }
set { target = value; }
}
}
class BuyConnection:Connection
{
}
myFunction:
public void importBuyConnectionIntoNeo4j(List<BuyConnection> connectionList)
{
GraphClient client = createConnectionToNeo4j();
client.Cypher
.Unwind(connectionList, "connection")
.Match("(source:Person),(target:Vegetable)")
.Where("source.Name=connection.Source AND target.Type=connection.Target")
.Create("(source)-[:Buy]->(target)")
.ExecuteWithoutResults();
}
I think the issue is with your .where text:
.Where("source.Name=connection.Source AND target.Type=connection.Target")
is the Source and Target the right way around?

Updating an object from another objects property history in C# for implementing a PATCH

I'm trying to implement a PATCH on Web API for an object that will be stored in a DB. The input object from the controller has all of the properties that can be modified but we allow the client to choose which fields to send back. We only want to update the MongoDB representation if some of the fields have changed or been set. We started using a Dirty object pattern (not sure this is a pattern) whereby when you set a property you also record that it is dirty. for instance
public class Example
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
TitleWasSet = true;
}
}
public bool TitleWasSet {get;set;}
}
This could work but is kind of tedious and I feel it exposes lots of logic that could be contained.
So a solution I came up with was to store the update Actions in the inbound object then reapply them to the Mongo Object in a Try Update fashion.
like this:
public class Data
{
public string Header { get; set; }
public int Rating { get; set; }
}
public class EditDataRequest
{
private readonly List<Action<Data>> _updates;
public EditDataRequest()
{
_updates = new List<Action<Data>>();
}
public string Header
{
set
{
_updates.Add(data => {data.Header = value;});
}
}
public int Rating
{
set
{
_updates.Add(data => {data.Rating = value;});
}
}
public bool TryUpdateFromMe(Data original)
{
if (_updates.Count == 0)
return false;
foreach (var update in _updates)
{
update.Invoke(original);
}
return true;
}
}
Now this would work great but it doesn't take account of the values being the same. So i then looked at changing the list of actions to a list of functions that would return a bool if there was a difference in the value.
private readonly List<Func<Data, bool>> _updates;
And then the properties would look like this:
public int Rating
{
set
{
_updates.Add(data => {
if (data.Rating != value)
{
data.Rating = value;
return true;
}
return false;
});
}
}
And the try update method...
public bool TryUpdateFromMe(Data original)
{
if (_updates.Count == 0)
return false;
bool changesRequired = false;
foreach (var update in _updates)
{
changesRequired |= update.Invoke(original);
}
return changesRequired;
}
As you can see that property set implementation is rather clunky and would make the code nasty to read.
I'd like a way of extracting the check this property value then update it to another method that I can reuse in each property - I assume this is possibly somehow but it might not be.
Of course, if you have better suggestions for how to handle the PATCH situation then I'd be happy to hear them as well.
Thanks for reading this far.

ASMX webservice doesn't return any result

I'm trying to send an object of a custom class through my asmx webservice running on .net 4.0, but all i get is an empty response. See below:
<soap:Body>
<ActivateResponse xmlns="http://tempuri.org/">
<ActivateResult /> <!-- why is this empty -->
</ActivateResponse>
</soap:Body>
However, if i modify my method and change the return type for example from class A to B, then it returns all the properties of object B correctly. See below:
<ActivateResponse xmlns="http://tempuri.org/">
<ActivateResult>
<BtAddress>string</BtAddress>
<Name>string</Name>
<Number>string</Number>
</ActivateResult>
</ActivateResponse>
I'm wondering why its happening? I could blame to improper Serialization of class A but there's nothing fancy I'm involving in my class files. Both class files are almost similar in terms of contents and does not contain any Serialize attribute.
So, why does the webservice return one type, but not the other?
Class A:
public class A
{
private string code;
private bool isValid;
private int maxUniqueActivations;
private DateTime dateAdded;
private Customer customer = null;
private bool _initAsEmpty = false;
public License()
{
_initAsEmpty = true;
}
public string LicenseCode
{
get { return code; }
//set { code = String.IsNullOrWhiteSpace(value)? null : value.Trim(); }
}
//If i change return type to Customer, it works too
//so i dont think it should be blamed
public Customer Customer
{
get { return customer; }
}
public bool IsValid
{
get { return isValid; }
}
public int MaxUniqueActivations
{
get { return maxUniqueActivations; }
}
public DateTime DateAdded
{
get { return dateAdded; }
}
}
Class B:
public class Phone
{
private string btAddress, name, number;
private bool isValid;
private DateTime dateAdded;
private bool _initAsEmtpy = false;
public Phone()
{
_initAsEmtpy = true;
}
public string BtAddress
{
get { return btAddress; }
set { btAddress = string.IsNullOrWhiteSpace(value) ? null : value.Replace(":", "").Trim(); }
}
public string Name
{
get { return name; }
set { name = string.IsNullOrWhiteSpace(value) ? null : value.Trim(); }
}
public string Number
{
get { return number; }
set { number = string.IsNullOrWhiteSpace(value) ? null : value.Trim(); }
}
public bool IsValid
{
get { return isValid; }
}
public DateTime DateAdded
{
get { return dateAdded; }
}
}
some methods are suppressed
In order to be serializable, a class must have public setters on its properties. That's the difference between classes A and B, and the reason why A won't serialize.
Probably :)
I think the problem may be with the Customer class. Maybe it is private or something. Try checking it out.

Categories