Sencha Touch and WCF REST post parameter always null - json

I'm building an application using sencha touch 1.1 in the client side and WCF REST services in the server side. I'm facing some problems when the sencha sore syncs data, the parameter sent to update method is always null. This is the c# definition of the parameter:
namespace HomeInventory.Application.Service.Dto{
[Serializable]
[DataContract(Namespace = "http://xxxxx.xxx.org/shopinglist")]
public class DtoShopingList{
[DataMember]
public long Id { get; set; }
[DataMember]
public string CreationDate { get; set; }
[DataMember]
public string ListName { get; set; }
[DataMember]
public DtoUser User { get; set; }
[DataMember]
public DtoListItem[] Items { get; set; }
[DataMember]
public bool IsDefault { get; set; }
}
This the json posted by sencha to the server:
{"records":"[{\"Id\":0,\"ListName\":\"Default\",\"CreationDate\":\"23/01/2012\",\"IsDefault\":true,\"items\":[]}]"}
It seems to me that WCF JSON serializer is unabled to parse the JSON to the corresponding class. Any help in how to fix it?
Thanks in advance.

Well, in case it serves someone else, I got rid of the backslashes with the following settings in the proxy.
writer: {
encode: false,
type: 'json'
}
Best regards.

Related

How to pass User object into json to send to api endpoint?

I am getting this error 400 when trying to submit a POST.
"$.User": [
"The JSON value could not be converted to WebApi.Models.User. Path: $.User | LineNumber: 5 | BytePositionInLine: 19."
]
}
This is my Order Model in asp.net core 3 api
namespace WebApi.Models
{
public class DispatchRequest
{
[Key]
public int DispatchRequestID { get; set; }
[Required]
[Column(TypeName = "nvarchar(100)")]
public string DispatchRequestNo { get; set; }
[Required]
public string CreatedOn { get; set; }
[Required]
[Column(TypeName = "int(10)")]
[ForeignKey("UserID")]
public User User { get; set; }
public int UserID { get; set; }
public ICollection<DispatchRequestItem> DispatchRequestsItems { get; set; }
}
}
So it seems like the problem is that the value for the json key "User" is not a user object. How do I do that, in order to make the POST request pass?
I am using angular to send the post request, but it didnt work, so I am using Postman now to try and troubleshoot and realized the above.
As a general tip, I would first recommend you to start using Swagger, its a beautiful thing that makes you a page in apiURL/swagger where you can test all your endpoints and have examples of what object each endpoint needs. Also you can scaffold your angular api with the swagger.json and https://www.npmjs.com/package/api-client-generator
Why would you have as Required the object User? having the UserId as required would do just fine. Also if you are attaching the User object , you have to double check not to update the user in the db when EF Core does its magic

Deserialize json invalid Property names

Part of the json read from Mailchimp looks like this.
"interests": {
"5e0344ae18": true,
"545e5bdb01": true,
"33aa542ea0": true,
"f51a5f9716": true,
"31109a4d58": true,
"bf5f946fd4": true,
"563320981e": false
}
So the properties used for deserialize should be this I believe.
public Interests interests { get; set; }
public class Interests
{
public bool 5e0344ae18 { get; set; }
public bool 545e5bdb01 { get; set; }
public bool 33aa542ea0 { get; set; }
public bool f51a5f9716 { get; set; }
public bool 31109a4d58 { get; set; }
public bool bf5f946fd4 { get; set; }
public bool 563320981e { get; set; }
}
However the property names consisting of numbers and letters aren't valid with compile error for each like 'Invalid token '5e0344' in class, struct, or interface member declaration'.
How can the property name match the name in the json data?
While I don't believe you will be able to use property names beginning with numbers, you could possibly prefix these with a character or string and do some manual parsing.
Assuming you're working with C#, http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm may allow you to handle the JSON response and parse properties without using the automatic deserialize I'm guessing you're currently using.
Here's another post I found describing a similar problem and some potential solutions: Parse jsonObject when field names are unknowm
You can use Data Annotations to map your JSON properties to your Model properties
This works both ways (incoming/outgoing):
using Newtonsoft.Json; // or Json.Net (built-in)
[JsonProperty(PropertyName = "5e0344ae18")]
public bool YourPropertyName { get; set; }

JSON deserialization throws circular reference ONLY in live build

I have a strange issue that I can't wrap my head around. I am trying to create an "export to csv" function for my MVC4 application where the relevant JSON is passed via an ajax call to my ActionResult. The ActionResult deserializes the stringify'd JSON (with JSON.Net), writes it to a file in csv format, then returns the server path to the new file. My success callback then receives the path and calls the url to download.
This works fine locally, but on my live test server I get the following exception:
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.
The JSON (and subsequently the objects they are deserialized to) are slightly complex. They come from a grouped subset of a SlickGrid DataView. I was getting circular reference exceptions when I included the aggregate information for column totals (this is only relevant to those that are versed in SlickGrid, I do not believe the data being passed to the server is an issue), but I've removed them before passing the JSON to the server. Here is my JSON to C# class structure:
[Serializable]
public class Row
{
public int id { get; set; }
public DateTime DateCreated { get; set; }
public int RefNo { get; set; }
public string ClientName { get; set; }
public string Plate { get; set; }
public string Address1 { get; set; }
public int? ProductID { get; set; }
public string Product { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
}
[Serializable]
public class RootReportObject
{
public bool __group { get; set; }
public int level { get; set; }
public int count { get; set; }
public string value { get; set; }
public string title { get; set; }
public int collapsed { get; set; }
public List<Row> rows { get; set; }
public object groups { get; set; }
public string groupingKey { get; set; }
}
The only thing that I'm thinking is that, because of the way the data is structured, the List<> of rows in the root object may be throwing the circular references during deserializtion because a group does not necessarily have unique row references.
My question is why does it work fine locally?? I have no idea what I'm missing.
That's great that the [ScriptIgnore] attribute is helping. Also, something to be completely sure of is that all of your URL paths, including in your AJAX code, resolve correctly to the application root. When some of these are wrong, this is a notorious source of problems during the move from development to production.
It doesn't sound like it is necessarily the primary issue but I don't have any understanding of your app's design. It's definitely worth looking over.

How to read this Json to controller object? Kendo UI grid server filtering

I am trying to filter Kendo UI grid server side filter. The developer tools show this in query string
/Home/GetUsmMessage?{"filter":{"logic":"and","filters" [{"field":"MessageId","operator":"eq","value":1}]},"group":[]} GET 200 application/json
I created a object structure so that I read the structure to object
public ActionResult GetUsmMessage(FilterContainer filter)
{
//Code to read the filter container
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Object structure for filter container:
public class FilterContainer
{
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
public class FilterDescription
{
public string #operator { get; set; }
public string field { get; set; }
public string value { get; set; }
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
It still gives me a null object when I debug controller function. Please help
Got the answer...I forgot to add type of request as Http post ....
In case of WebApi controller, you could use [FromUri] attributes and GET verb:
public HttpResponseMessage Get(
[FromUri]IEnumerable<SortParameter> sort,
[FromUri]FilterContainer filter,
int take = 10, int skip = 0)

OpenRasta Json returning nested classes

Is it possible to return nested classes in json with OpenRasta?
I'm using EF4.1 with code first (which in theory shouldn't make a difference, as they are just POCO classes).
Here is an example:
public class AppUser
{
[Key]
public int AppUserId { get; set; }
public string WinLogin { get; set; }
public string ScreenName { get; set; }
public string AgencyId { get; set; }
public virtual ICollection<UserAppVersion> UserAppVersion { get; set; }
}
public class UserAppVersion
{
[Key]
public int UaVersionId { get; set; }
public int AppUserId { get; set; }
public int AppVersionId { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public virtual AppUser User { get; set; }
public virtual AppVersion Version { get; set; }
}
I try and return an AppUser record in json using this:
ResourceSpace.Has.ResourcesOfType<AppUser>()
.AtUri("/user").HandledBy<UserHandler>().AsJsonDataContract();
But I get an error:
System.Runtime.Serialization.SerializationException: Type 'System.Data.Entity.DynamicProxies.UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D' with data contract name 'UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Unfortunately I don't know how to resolve this. Any suggestions?
That's a data contract issue, not an openrast one.
The DataContract serialzier is seeing a dynamic proxy probably generated by EF code first, and when seeing that cannot render the object.
I'd recommend either swapping for another serialziation codec, or disabling transparent lazy loading, or alternatively marking your property as an ignore for serialziation and have another property typed to a List so the serializer can function.
See DataContractSerializer Error using Entity Framework 4.0 with WCF 4.0