I cant seem to figure out why the method "sometimes" cause this null reference exception. I run the code on my localhost and it works fine when this appears for some users. When I restart the site it also goes away on the server.
My question is how can I debug this? Its taking a .NET object and trying to serialize it but I cant tell which property is causing this issue.
Method
public static string ToJSON(this object o)
{
return JsonConvert.SerializeObject(o, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
Exception
at System.Text.StringBuilder.Append(Char value)
at Newtonsoft.Json.JsonTextWriter.WriteEnd(JsonToken token)
at Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type)
at Newtonsoft.Json.JsonWriter.WriteEndObject()
at Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type)
at Newtonsoft.Json.JsonWriter.AutoCompleteAll()
at Newtonsoft.Json.JsonTextWriter.Close()
at Newtonsoft.Json.JsonWriter.Dispose(Boolean disposing)
at Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose()
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, JsonSerializerSettings settings)
at Tournaments.Common.Extensions.ObjectExtensions.ToJSON(Object o)
Try/Catch
I tried the below and the JavascriptSerializer throws the error A circular reference was detected while serializing an object of type 'Tournaments.Models.Events.EventModel'.
However I dont know what object has this EventModel, which could be multiple.
<script type="text/javascript">
@{
string model = null;
try
{
model = Model.Designer.ToJSON();
}
catch (Exception ex )
{
model = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.Designer);
}
}
app.viewModel.members.bracket.init(@Html.Raw(model));
</script>
So I was able to narrow it down by using ToJSON on the complex properties. For some reason entity framework is storing a child list on the property in cache when it shouldn’t at all as the query never pulls it before storing in cache. I basically told automapper to ignore those properties on map.