1

I am getting an error trying to move a DataSourceResult from one web service to another... the client calls web service A which resides on our web server. We then make a call to web service B which resides on our db server. The intent is that web service A adds certain sensitive data to the call, that we want hidden behind our firewall... then the call gets handled by web service B, gets a DataSourceResult, and seems to serialize it just fine... note I am using the same set of serilization properties to bot serialize and deserialize, I am just not showing the call to serilize here for brevity. When I go to deserialize this, I get a System.AggregateException - thrown on line "return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;" of my deserialization code... any ideas? anything would be much appreciated :)

Serilize code:

    string Serialize<T>(MediaTypeFormatter formatter, T value)
    {
        // Create a dummy HTTP Content.
        Stream stream = new MemoryStream();
        var content = new StreamContent(stream);
        /// Serialize the object.
        formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
        // Read the serialized string.
        stream.Position = 0;
        return content.ReadAsStringAsync().Result;
    }

Deserialize code:

    T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class
    {
        // Write the serialized string to a memory stream.
        Stream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(str);
        writer.Flush();
        stream.Position = 0;
        // Deserialize to an object of type T
        return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
    }

Json Object / settings being passed into methods:

            var json = GlobalConfiguration.Configuration.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().FirstOrDefault();
            json.SerializerSettings.Formatting = Formatting.None;
            json.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            json.SerializerSettings.NullValueHandling = NullValueHandling.Include;
            json.UseDataContractJsonSerializer = false;

            DataSourceResult result = Deserialize<DataSourceResult>(json, loansJson);

I have this string I try to deserialize and it throws this error:

`System.AggregateException was unhandled by user code
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
       at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Deserialize[T](MediaTypeFormatter formatter, String str) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 54
       at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Get(RelationshipDataSourceRequest request) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 96
       at lambda_method(Closure , Object , Object[] )
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
  InnerException: Newtonsoft.Json.JsonSerializationException
       HResult=-2146233088
System.AggregateException was unhandled by user code
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
       at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Deserialize[T](MediaTypeFormatter formatter, String str) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 54
       at Cavatica35.Web.Api.Controllers.RelationshipsGridController.Get(RelationshipDataSourceRequest request) in c:\dev\Cavatica35\Code\MarginMaximizerInteractive\Cavatica35.Web\Api\Controllers\RelationshipsGridController.cs:line 96
       at lambda_method(Closure , Object , Object[] )
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
       at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
  InnerException: Newtonsoft.Json.JsonSerializationException
       HResult=-2146233088
       Message=Error converting value "{"$id":"1","Data":[{"$id":"2","Relationship_loanOfficerName":"Deva MMi Admin","guidID":"c4327c4a-7aa5-4503-b738-59a9241a5a1c","name":"New Deva","briefDescription":null,"fullDescription":"","autoRenewLOC":0,"numOfLoans":1,"loanBalance":1000000.0,"numOfDeposits":0,"Relationship_depositbalance":0.0,"numOfOtherRels":0,"otherRelBalance":0.0,"targetROE":0.0,"yearsRemaining":5,"ownedBy":"21973a46-c06e-4ddc-8a94-05bb53c949e6","modBy":"00000000-0000-0000-0000-000000000000","createdBy":"00000000-0000-0000-0000-000000000000","modDate":"12/18/2014","createdDate":"1/1/0001","Relationship_netincome":16955.0,"Relationship_relationshiproe":26.48,"Relationship_avgbalance":1000000.0,"monthsUntilFirstRenewal":"1/1/0001","requiresReview":false,"deleted":false,"extIDList":"","overrideOfficer":false,"selected":false,"ni":16954.908394431,"niOverROE":64028.495587965743,"tag":""}],"Total":1,"AggregateResults":[{"$id":"3","Value":1,"Member":"name","FormattedValue":1,"ItemCount":0,"Caption":null,"FunctionName":"Count_name_28477829","AggregateMethodName":"Count"},{"$id":"4","Value":16955.0,"Member":"Relationship_netincome","FormattedValue":16955.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_netincome_244267","AggregateMethodName":"Sum"},{"$id":"5","Value":26.48,"Member":"Relationship_relationshiproe","FormattedValue":26.48,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_relationshiproe_8060817","AggregateMethodName":"Sum"},{"$id":"6","Value":1000000.0,"Member":"Relationship_avgbalance","FormattedValue":1000000.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_avgbalance_64680392","AggregateMethodName":"Sum"},{"$id":"7","Value":1,"Member":"numOfLoans","FormattedValue":1,"ItemCount":0,"Caption":null,"FunctionName":"Sum_numOfLoans_54078176","AggregateMethodName":"Sum"},{"$id":"8","Value":1000000.0,"Member":"loanBalance","FormattedValue":1000000.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_loanBalance_39749352","AggregateMethodName":"Sum"},{"$id":"9","Value":0,"Member":"numOfDeposits","FormattedValue":0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_numOfDeposits_36660208","AggregateMethodName":"Sum"},{"$id":"10","Value":0.0,"Member":"Relationship_depositbalance","FormattedValue":0.0,"ItemCount":0,"Caption":null,"FunctionName":"Sum_Relationship_depositbalance_1827337","AggregateMethodName":"Sum"},{"$id":"11","Value":16954.908394431,"Member":"ni","FormattedValue":16954.908394431,"ItemCount":0,"Caption":null,"FunctionName":"Sum_ni_60302147","AggregateMethodName":"Sum"},{"$id":"12","Value":64028.495587965743,"Member":"niOverROE","FormattedValue":64028.495587965743,"ItemCount":0,"Caption":null,"FunctionName":"Sum_niOverROE_43813805","AggregateMethodName":"Sum"}],"Errors":null}" to type 'Kendo.Mvc.UI.DataSourceResult'. Path '', line 1, position 3087.
       Source=Newtonsoft.Json
       StackTrace:
            at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
            at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
            at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
            at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
            at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
            at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
            at System.Net.Http.Formatting.JsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)
            at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
            at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
       InnerException: System.ArgumentException
            HResult=-2147024809
            Message=Could not cast or convert from System.String to Kendo.Mvc.UI.DataSourceResult.
            Source=Newtonsoft.Json
            StackTrace:
                 at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
                 at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
                 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
            InnerException: `
1
  • Interestingly I get the same error if I try to deserilize the object right after serializing it... DataSourceResult result = results.ToDataSourceResult(requestKendo); string s = Serialize<DataSourceResult>(json, result); DataSourceResult t = Deserialize<DataSourceResult>(json, s); Commented Feb 17, 2015 at 2:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.