property is null when using xml serialization in webapi - asp.net

I'm trying to send the below xml
<dataset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.uisol.com/model">
<extAlert SendFrom="SendFrom" Target="Target" OID="0" UrgentFlag="0" />
</dataset>
as a post to a webapi request
HttpResponseMessage Post([FromBody]SendNotificationRequest dataset)
with the classes defined as below
[XmlRoot(Namespace = "http://www.uisol.com/model",
ElementName = "dataset",
DataType = "string",
IsNullable = true)]
public class SendNotificationRequest
{
[XmlElement(
ElementName = "extAlert",
Namespace = "http://www.uisol.com/model")]
public DRMSAlertRequest ExtAlert { get; set; }
}
}
and
public class DRMSAlertRequest : IDRMSAlert
{
[XmlAttribute]
public string SendFrom { get; set; }
[XmlAttribute]
public string Target { get; set; }
[XmlAttribute]
public string SendTo { get; set; }
[XmlAttribute]
public string BlindTo { get; set; }
[XmlAttribute]
public string ReplyTo { get; set; }
[XmlAttribute]
public string FailureTo { get; set; }
[XmlAttribute]
public int OID { get; set; }
[XmlAttribute]
public string Subject { get; set; }
[XmlAttribute]
public string Message { get; set; }
[XmlAttribute]
public char UrgentFlag { get; set; }
}
i have also made the xmlmedia formatter as below
var formatter = new XmlMediaTypeFormatter {UseXmlSerializer = true};
config.Formatters.Add(formatter);
var xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xmlFormatter.UseXmlSerializer = true;
xmlFormatter.SetSerializer<SendNotificationRequest>(new XmlSerializer(typeof(SendNotificationRequest)));
xmlFormatter.SetSerializer<DRMSAlertRequest>(new XmlSerializer(typeof(DRMSAlertRequest)));
}
I'm receiving the ExtAlert as null on the webapi controller. What might be the reason?

httpRequest.ContentType = "application/x-www-form-urlencoded";
changed this to
httpRequest.ContentType = "application/xml";

Related

DataContractSerializer could not de-serialize all properties in Net Core 2

i am trying to de-serialize xml into known object using DataContractSerializer in .NET Core 2.
Here is my xml. ( I do not have control over xml. This is how i get the XML as response to some api method). For testing purpose i have captured the xml and put in xml file.
<Response>
<ClientID>TestClient</ClientID>
<FileName>E:\MyData\20180223084535390PM.xml</FileName>
<UploadStatus>Succeeded</UploadStatus>
<UploadMessage>Imported Successfully</UploadMessage>
<ConfirmationNumber>0abcb25f2675</ConfirmationNumber>
<ImportTime>2018-02-23T15:48:01.887</ImportTime>
<StartTime>2018-02-23T15:48:03.113</StartTime>
<EndTime>2018-02-23T15:53:14.76</EndTime>
<Count>6</Count>
<Amount>3446.3500</Amount>
<Messages />
</Response>
My corresponding C# object
[DataContract(Name = "Response", Namespace = "")]
public class MyResponse
{
[DataMember]
public string ClientID { get; set; }
[DataMember]
public string FileName { get; set; }
[DataMember]
public string UploadStatus { get; set; }
[DataMember]
public string UploadMessage { get; set; }
[DataMember]
public string ConfirmationNumber { get; set; }
[DataMember]
public DateTime? ImportTime { get; set; }
[DataMember]
public DateTime? StartTime { get; set; }
[DataMember]
public DateTime? EndTime { get; set; }
[DataMember]
public int? Count { get; set; }
[DataMember]
public decimal? Amount { get; set; }
[DataMember]
public string Messages { get; set; }
}
De-serialization code
[Fact]
public void TestDeSerialize()
{
var file = AppDomain.CurrentDomain.BaseDirectory + "Data\\test.xml";
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(MyResponse));
MyResponse result = null;
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
result = (MyResponse)serializer.ReadObject(fs);
}
}
However when it de-serializes the xml into object, most of the object properties are NULL even though they have corresponding values in XML file. See quickwatch below.
I am not sure what i am missing here??
Update 1
Note that, When i replace DataContract and DataMember attributes with XmlRoot and XmlElement respectively, and then de-serialize the xml using XmlSerializer then the resultant object has all the properties populated.
So it works with XmlSerializer but not with DataContractSerializer.
I would like to use DataContractSerializer
For DataContractSerializer, it is default to use Alphabetical ordering; and expects XML elements to arrive in that order; Out of order elements are discarded usually.
It seems the XML is received, and you could not change the XML elements order, you could use Order property like below.
[DataContract(Name = "Response", Namespace = "")]
public class MyResponse
{
[DataMember(Order =1)]
public string ClientID { get; set; }
[DataMember(Order = 2)]
public string FileName { get; set; }
[DataMember(Order = 3)]
public string UploadStatus { get; set; }
[DataMember(Order = 4)]
public string UploadMessage { get; set; }
[DataMember(Order = 5)]
public string ConfirmationNumber { get; set; }
[DataMember(Order = 6)]
public DateTime? ImportTime { get; set; }
[DataMember(Order = 7)]
public DateTime? StartTime { get; set; }
[DataMember(Order = 8)]
public DateTime? EndTime { get; set; }
[DataMember(Order = 9)]
public int? Count { get; set; }
[DataMember(Order = 10)]
public decimal? Amount { get; set; }
[DataMember(Order = 11)]
public string Messages { get; set; }
}

"System.Xml.XmlAttribute cannot be used as: 'xml element'." while running my asmx service

I am trying to create a small asmx service with a method which will return some dummy data. I get the following error when I run the service:
"System.InvalidOperationException: System.Xml.XmlAttribute cannot be used as: 'xml element'."
My web method is as follows:
[WebMethod]
public SubmitCaseRequestResponse1 SubmitCaseRequest(SubmitCaseRequestRequest1 request)
{
var response = new SubmitCaseRequestResponse1
{
ResponseID = "456325898",
Success = true,
ValidationErrors = null
};
return response;
}
My SubmitCaseRequestResponse1 class:
public class SubmitCaseRequestResponse1
{
public string ResponseId { get; set; }
public bool Success { get; set; }
public ValidationError[] ValidationErrors { get; set; }
}
and the request class is :
public class SubmitCaseRequestRequest1
{
public AuthHeader AuthHeader { get; set; }
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}
I was supposed to serialize the complex type SubmitCaseRequestRequest1 and SubmitCaseRequestResponse1 . Needed to add [XmlElement] for the complex types and [XmlAttribute] for simple types
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://tempuri.org/")]
[Serializable]
public class SubmitCaseRequestRequest1
{
[XmlElement]
public AuthHeader AuthHeader { get; set; }
[XmlElement]
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}
[Serializable]
public class SubmitCaseRequestRequest
{
[XmlElement]
public Guid? RequestId { get; set; }
[XmlAttribute]
public string LCICourtNumber { get; set; }
[XmlAttribute]
public string CaseNumber { get; set; }
[XmlAttribute]
public string DebtorLastName { get; set; }
[XmlAttribute]
public string DateType { get; set; }
}

Parse Complex JSON to ASP.NET MVC 3 using jQuery

I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,

How to match entities with stored procedure results(ASP.Net MVC with entity framework)

I am calling one stored procedure which will takes 5 inputs and will returns a set of table data. I have created the class to match with the stored procedure results. How to map this stored procedure result with class?
My stored procedure will takes 6 parameters like below
PROC_REZ_GETCHNAVL 7012,3,20130816,20130817,1,'INR'
and it will gives the table set which will exactly same as below table.
public class AvailableRooms
{
[Required]
[Key]
public int CUSTCODE { get; set; }
public int CHANNID { get; set; }
public string RATECODE { get; set; }
public int RUNSRLNUB { get; set; }
public string ROOMTYPE { get; set; }
[Display(Name = "Room Name")]
public string ROOMNAME { get; set; }
public string ROOMSHTDESC { get; set; }
public string ROOMLNGDESC { get; set; }
public string ROOMFEATURES { get; set; }
public int MAXADT { get; set; }
public int MAXCHD { get; set; }
public int TOTROM { get; set; }
public char AVLFLG { get; set; }
public int AVLROM { get; set; }
public decimal OCCPER { get; set; }
public string RATETYPE { get; set; }
public string RATEPLAN { get; set; }
public string RATEDESCRP { get; set; }
public string RUNDAT { get; set; }
[Display(Name = "Room Rate")]
public decimal SGLRAT { get; set; }
public decimal DBLRAT { get; set; }
public decimal TRPRAT { get; set; }
public decimal QUDRAT { get; set; }
public decimal ADTRAT { get; set; }
public decimal CHDRAT { get; set; }
public decimal PLNSGLRAT { get; set; }
public decimal PLNDBLRAT { get; set; }
public decimal PLNTRPRAT { get; set; }
public decimal PLNQUDRAT { get; set; }
public decimal PLNEXTADTRAT { get; set; }
public decimal PLNEXTCHDRAT { get; set; }
public string ROOMIMG { get; set; }
public string PRPSHORTDESC { get; set; }
public string PRPLONGDESC { get; set; }
public string PRPFEATURES { get; set; }
public string TERMSCOND { get; set; }
public string CACELPOLICY { get; set; }
public string ROOMVID { get; set; }
public string CHANNELDESC { get; set; }
public int MAXPER { get; set; }
public int EXTPER { get; set; }
public int SEASONCODE { get; set; }
private decimal _SGLTOTRATE;
[DisplayFormat(DataFormatString = "{0:##,###}")]
public decimal SGLTOTRATE
{
get
{
return makeFormat(_SGLTOTRATE);
}
set
{
_SGLTOTRATE = value;
}
}
/// <summary>
/// Room Rate Currency Format
/// </summary>
/// <param name="_sglTotRate"></param>
/// <returns></returns>
private decimal makeFormat(decimal _sglTotRate)
{
if (_sglTotRate.ToString().Contains('.'))
_sglTotRate = Convert.ToDecimal(_sglTotRate.ToString("G29"));
return _sglTotRate;
}
public decimal DBLTOTRATE { get; set; }
public decimal EXTADTTOT { get; set; }
public decimal EXTCHDTOT { get; set; }
public decimal RACKSGL { get; set; }
public decimal RACKDBL { get; set; }
public decimal RACKADT { get; set; }
public decimal RACKCHD { get; set; }
public string MEALTYPE { get; set; }
public int DISSEQ { get; set; }
}
Please let me know how to map this class with stored procedure with DbContext?????
Awaiting for your resply.
Below is the solution for this.
namespace WBE.Repository
{
public class WBERepository : WBEContext,IWBERepository
{
/// <summary>
/// Get All the available rooms with respect to input parameters
/// </summary>
/// <param name="roomAvailInputs"></param>
/// <returns></returns>
public List<RoomInventory> GetRoomInventory(List<InventoryInputs> roomAvailInputs)
{
using (var context = new WBEContext())
{
var CustCode = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "CSTCOD",
Value = roomAvailInputs[0].CUSTCODE
};
var ChnlCode = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "CHNCOD",
Value = roomAvailInputs[0].CHNCOD
};
var ArrDate = new SqlParameter
{
DbType = DbType.String,
ParameterName = "ARRDAT",
Value = roomAvailInputs[0].ARRDAT
};
var DepDate = new SqlParameter
{
DbType = DbType.String,
ParameterName = "DEPDAT",
Value = roomAvailInputs[0].DEPDAT
};
var NoRooms = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "NBROOM",
Value = roomAvailInputs[0].NBROOM
};
var CurType = new SqlParameter
{
DbType = DbType.String,
ParameterName = "CURTYP",
Value = roomAvailInputs[0].CURTYP
};
return context.Database.SqlQuery<RoomInventory>
("PROC_REZ_GETCHNAVL #CSTCOD, #CHNCOD, #ARRDAT, #DEPDAT, #NBROOM, #CURTYP",
CustCode, ChnlCode, ArrDate, DepDate, NoRooms, CurType).ToList<RoomInventory>();
}

Metro Style App: JSON Object Deserialization Error, REST Services

Element ':item' contains data from a type that maps to the name
"http://schemas.microsoft.com/search/local/ws/rest/v1:Route.' The
deserializer has no knowledge of any type that maps to this name.
Consider using a DataContractResolver or add the type corresponding to
'Route' to the list of known types - for example, by using
KnownTypeAttribute attribute or by adding it to the list of known
types passed to DataContractSerializer.
After adding [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1", Name = "Location")] ro Resource class, I got this exception:
Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''
Likn: http://dev.virtualearth.net/REST/V1/Routes?wp.0=37.779160067439079,-122.42004945874214&wp.1=32.715685218572617,-117.16172486543655&key=BingMapsKey
[KnownType(typeof(double[]))]
[DataContract]
public class ActualEnd
{
[DataMember(Name = "type")]
public string type { get; set; }
[DataMember(Name = "coordinates")]
public List<double> coordinates { get; set; }
}
[KnownType(typeof(double[]))]
[DataContract]
public class ActualStart
{
[DataMember(Name = "type")]
public string type { get; set; }
[DataMember(Name = "coordinates")]
public List<double> coordinates { get; set; }
}
[KnownType(typeof(int[]))]
[KnownType(typeof(string[]))]
[DataContract]
public class Detail
{
[DataMember(Name = "compassDegrees")]
public int compassDegrees { get; set; }
[DataMember(Name = "endPathIndices")]
public List<int> endPathIndices { get; set; }
[DataMember(Name = "maneuverType")]
public string maneuverType { get; set; }
[DataMember(Name = "mode")]
public string mode { get; set; }
[DataMember(Name = "roadType")]
public string roadType { get; set; }
[DataMember(Name = "startPathIndices")]
public List<int> startPathIndices { get; set; }
[DataMember(Name = "names")]
public List<string> names { get; set; }
}
[DataContract]
public class Instruction
{
[DataMember(Name = "maneuverType")]
public string maneuverType { get; set; }
[DataMember(Name = "text")]
public string text { get; set; }
}
[KnownType(typeof(double[]))]
[DataContract]
public class ManeuverPoint
{
[DataMember(Name = "type")]
public string type { get; set; }
[DataMember(Name = "coordinates")]
public List<double> coordinates { get; set; }
}
[DataContract]
public class Hint
{
[DataMember(Name = "hintType")]
public object hintType { get; set; }
[DataMember(Name = "text")]
public string text { get; set; }
}
[KnownType(typeof(Detail[]))]
[KnownType(typeof(Instruction))]
[KnownType(typeof(Hint[]))]
[KnownType(typeof(ManeuverPoint))]
[KnownType(typeof(string[]))]
[DataContract]
public class ItineraryItem
{
[DataMember(Name = "compassDirection")]
public string compassDirection { get; set; }
[DataMember(Name = "details")]
public List<Detail> details { get; set; }
[DataMember(Name = "exit")]
public string exit { get; set; }
[DataMember(Name = "iconType")]
public string iconType { get; set; }
[DataMember(Name = "instruction")]
public Instruction instruction { get; set; }
[DataMember(Name = "maneuverPoint")]
public ManeuverPoint maneuverPoint { get; set; }
[DataMember(Name = "sideOfStreet")]
public string sideOfStreet { get; set; }
[DataMember(Name = "tollZone")]
public string tollZone { get; set; }
[DataMember(Name = "towardsRoadName")]
public string towardsRoadName { get; set; }
[DataMember(Name = "transitTerminus")]
public string transitTerminus { get; set; }
[DataMember(Name = "travelDistance")]
public double travelDistance { get; set; }
[DataMember(Name = "travelDuration")]
public int travelDuration { get; set; }
[DataMember(Name = "travelMode")]
public string travelMode { get; set; }
[DataMember(Name = "signs")]
public List<string> signs { get; set; }
[DataMember(Name = "hints")]
public List<Hint> hints { get; set; }
}
[KnownType(typeof(ActualEnd))]
[KnownType(typeof(ActualStart))]
[KnownType(typeof(ItineraryItem[]))]
[DataContract]
public class RouteLeg
{
[DataMember(Name = "actualEnd")]
public ActualEnd actualEnd { get; set; }
[DataMember(Name = "actualStart")]
public ActualStart actualStart { get; set; }
[DataMember(Name = "itineraryItems")]
public List<ItineraryItem> itineraryItems { get; set; }
[DataMember(Name = "travelDistance")]
public double travelDistance { get; set; }
[DataMember(Name = "travelDuration")]
public int travelDuration { get; set; }
}
[KnownType(typeof(RouteLeg[]))]
[KnownType(typeof(double[]))]
[DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1", Name = "Location")]
public class Resource
{
[DataMember(Name = "__type")]
public string __type { get; set; }
[DataMember(Name = "id")]
public List<double> bbox { get; set; }
public string id { get; set; }
[DataMember(Name = "distanceUnit")]
public string distanceUnit { get; set; }
[DataMember(Name = "durationUnit")]
public string durationUnit { get; set; }
[DataMember(Name = "routeLegs")]
public List<RouteLeg> routeLegs { get; set; }
[DataMember(Name = "travelDistance")]
public double travelDistance { get; set; }
[DataMember(Name = "travelDuration")]
public int travelDuration { get; set; }
}
[KnownType(typeof(Resource[]))]
[DataContract]
public class ResourceSet
{
[DataMember(Name = "estimatedTotal")]
public int estimatedTotal { get; set; }
[DataMember(Name = "resources")]
public List<Resource> resources { get; set; }
}
[KnownType(typeof(ResourceSet[]))]
[DataContract]
public class RootObject
{
[DataMember(Name = "authenticationResultCode")]
public string authenticationResultCode { get; set; }
[DataMember(Name = "brandLogoUri")]
public string brandLogoUri { get; set; }
[DataMember(Name = "copyright")]
public string copyright { get; set; }
[DataMember(Name = "resourceSets")]
public List<ResourceSet> resourceSets { get; set; }
[DataMember(Name = "statusCode")]
public int statusCode { get; set; }
[DataMember(Name = "statusDescription")]
public string statusDescription { get; set; }
[DataMember(Name = "traceId")]
public string traceId { get; set; }
}
public async void MakeRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(string.Format(
"Server error(HTTP {0}:{1}.",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
root = (RootObject)objResponse;
}
}
catch (Exception ex)
{
ThrowException(ex);
}
}
The problem is here:
"estimatedTotal": 1,
"resources": [
{
"__type": "Route:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox": [
32.715692,
-122.420697,
37.827532,
-117.161052
],
Take a look at this blog post: http://rbrundritt.wordpress.com/2012/01/06/bing-maps-rest-service-net-libraries/
It has all the libraries you need for serializing the REST services. For the error you are seeing you need to create a class called Route and mark it as a known type on the resource class.
For Example:
[DataContract]
[KnownType(typeof(Location))]
[KnownType(typeof(Route))]
public class Resource

Resources