set max date value in database model - c#

Hi all I am trying to set max date below
But Modified always returns a null value instant of return max value between ModifiedDate and OfferProductsModified.
public DateTime? Modified { get { return _FinalDate; } set { _FinalDate = value; } }
/// <summary>
/// this are not in offer view model
/// </summary>
[JsonIgnore] public DateTime? _FinalDate;
[JsonIgnore]
public DateTime? FinalDate
{
get
{
if (ModifiedDate < OfferProductsModified)
{
return OfferProductsModified;
}
else
{
return ModifiedDate;
}
}
set
{
if (ModifiedDate < OfferProductsModified)
{
_FinalDate = OfferProductsModified;
}
else
{
//DEFAULT Value.
_FinalDate = value;
}
}
}
How can I return the max value between ModifiedDate and OfferProductsModified ?
Note :- Both ModifiedDate and OfferProductsModified having values (confirm by debugging )

Related

comparing start date with in the same list using C#

I have class called LaborRate as below. It has Id, start date, end date column.
user can see existing records from database table in a grid and he can edit them and/or he can add new records to the grid.
while saving existing modified records or new records I need to do below validation.
If the Start Date or End Date falls within Start Date & End Date on other record for then I need to through some error. I cannot depend on Id column because for newly added record the id value is -1. What is the best method to do this comparison.
public class LaborRate
{
private int _id;
private decimal _laborRate;
private DateTime _StartDate;
private DateTime _EndDate;
public int Id
{ get { return _id; } set { _id = value; } }
public Decimal Rate
{ get { return _laborRate; } set { _laborRate = value; } }
public DateTime StartDate
{ get { return _StartDate; } set { _StartDate = value; } }
public DateTime EndDate
{ get { return _EndDate; } set { _EndDate = value; } }
}

how do i check if DateTime is null

if (string.IsNullOrEmpty(value)) is for string, but what is the code to check if Datetime is null?
private DateTime? _ReleaseDate;
public DateTime? ReleaseDate
{
get
{
return _ReleaseDate;
}
set
{
if ()
{
}
else
{
_ReleaseDate = value;
}
}
}
The ValueType? pattern is shorthand for Nullable<ValueType>. In your case you have Nullable<DateTime>.
As you can see from the docs, Nullable<ValueType> implements a HasValue property, so you can simply check it like so:
if (value.HasValue)
{
}
else
{
}
If you simply want to set a default value you can use the GetValueOrDefault method of Nullable<T> and do away with the if statement:
_ReleaseDate = value.GetValueOrDefault(DateTime.MinValue); // or whatever default value you want.
For nullbale types you can use HasValue or != null
However for your example (with the code shown), you have more options
public DateTime? ReleaseDate
{
get
{
return _ReleaseDate;
}
set
{
// if value is null, then that's all good, _ReleaseDate will be null as well
_ReleaseDate = value;
}
}
Or
public DateTime? ReleaseDate {get;set}
The only reason you would need to do something like below, is when you have some specific behaviour on null or otherwise
public DateTime? ReleaseDate
{
get
{
return _ReleaseDate;
}
set
{
if (value.HasValue)
{
// has a value
}
else
{
// doesnt
}
}
}

InnerException:When converting a string to DateTime. parse the string to date the date before putting each variable into the DateTime object

I am trying to deserialize XML returned from an API call but am getting "InnerException:When converting a string to DateTime. parse the string to date the date before putting each variable into the DateTime object"
The XML looks like this
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<agentInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:N1="demo.org.uk/demo/CustomsStatus" xmlns:N2="demo.org.uk/demo/UnLocation" xmlns:N3="demo.org.uk/demo/AirCarrier" xmlns="demo.org.uk/demo/AgentInventory">
<shed>ADX</shed>
<arrivalPort>
<N2:iataPortCode>LHR</N2:iataPortCode>
</arrivalPort>
<masterAirwayBillPrefix>125</masterAirwayBillPrefix>
<masterAirwayBillNumber>28121101</masterAirwayBillNumber>
<nominatedAgent>DRB</nominatedAgent>
<originPort>
<N2:iataPortCode>BOS</N2:iataPortCode>
</originPort>
<destinationPort>
<N2:iataPortCode>LHR</N2:iataPortCode>
</destinationPort>
<airCarrier>
<N3:carrierCode>BA</N3:carrierCode>
</airCarrier>
<flightNumber>235</flightNumber>
<flightDate>2012-02-09T00:00:00Z</flightDate>
<npx>10</npx>
<npr>0</npr>
<grossWeight>123.0</grossWeight>
<goodsDescription>BOOKS</goodsDescription>
<sdc>T</sdc>
<status1Set></status1Set>
<status2Set>false</status2Set>
<ccsCreationTime></ccsCreationTime>
<customsSummaryText />
<customsSummaryTime></customsSummaryTime>
<agentReference />
<isErtsPreArrival>false</isErtsPreArrival>
<isAgentPreArrival>false</isAgentPreArrival>
<isDeleted>false</isDeleted>
<finalised></finalised>
<createdOn>2012-01-24T11:50:40.86Z</createdOn>
<modifiedOn>2012-02-09T09:51:26.617Z</modifiedOn>
</agentInventory>
The code used to deserialize the XML is
if (storeXmlInventoryReturnData != null)
{
//DeSerialize XML from storeXmlInventoryReturnData variable
agentInventory myInventoryResponse = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(agentInventory));
myInventoryResponse = (
agentInventory)xmlSerializer.Deserialize(new StringReader(storeXmlInventoryReturnData)
);
Console.WriteLine(
#"\n\n\n INVENTORY RETURN DATA FOR AWB: {0}-{1} \n\n
Destination Port: {2} \n
Arrival Port: {3} \n
Carrier: {4} \n
Flight No: {5} \n
Flight Date: {6} \n
Customers Status: {7} \n
NPX: {8} \n
NPR {9} \n
SDC Code: {10}
\n\n Hit any key to exit...."
,
myInventoryResponse.masterAirwayBillPrefix,
myInventoryResponse.masterAirwayBillNumber,
myInventoryResponse.destinationPort,
myInventoryResponse.arrivalPort,
myInventoryResponse.airCarrier,
myInventoryResponse.flightNumber,
myInventoryResponse.flightDate,
myInventoryResponse.customsStatus,
myInventoryResponse.npx,
myInventoryResponse.npr,
myInventoryResponse.sdc,
myInventoryResponse.grossWeight,
myInventoryResponse.goodsDescription
);
Console.ReadLine();
}
else
{
Console.Write("No data returned");
}
}
The exception is thrown at;
myInventoryResponse = (
agentInventory)xmlSerializer.Deserialize(new StringReader(storeXmlInventoryReturnData));
I guess I need to convert the myInventoryResponse.flightDate to a DateTime object but I am at a loss how to achieve this?
namespace FreightSolutions {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="asm.org.uk/Sequoia/AgentInventory")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="demo.org.uk/demo/AgentInventory", IsNullable=false)]
public partial class agentInventory {
private string shedField;
private unLocation arrivalPortField;
private string masterAirwayBillPrefixField;
private string masterAirwayBillNumberField;
private string houseAirwayBillNumberField;
private string splitReferenceNumberField;
private string nominatedAgentField;
private unLocation originPortField;
private unLocation destinationPortField;
private airCarrier airCarrierField;
private string flightNumberField;
private System.DateTime flightDateField;
private bool flightDateFieldSpecified;
private string npxField;
private string nprField;
private float grossWeightField;
private bool grossWeightFieldSpecified;
private string goodsDescriptionField;
private string sdcField;
private System.DateTime status1SetField;
private bool status1SetFieldSpecified;
private bool status2SetField;
private bool status2SetFieldSpecified;
private System.DateTime ccsCreationTimeField;
private bool ccsCreationTimeFieldSpecified;
private customsStatus customsStatusField;
private string customsSummaryTextField;
private System.DateTime customsSummaryTimeField;
private bool customsSummaryTimeFieldSpecified;
private string agentReferenceField;
private bool isErtsPreArrivalField;
private bool isErtsPreArrivalFieldSpecified;
private bool isAgentPreArrivalField;
private bool isAgentPreArrivalFieldSpecified;
private bool isDeletedField;
private bool isDeletedFieldSpecified;
private System.DateTime finalisedField;
private bool finalisedFieldSpecified;
private System.DateTime createdOnField;
private System.DateTime modifiedOnField;
private bool modifiedOnFieldSpecified;
public agentInventory() {
this.customsStatusField = new customsStatus();
this.airCarrierField = new airCarrier();
this.destinationPortField = new unLocation();
this.originPortField = new unLocation();
this.arrivalPortField = new unLocation();
}
public string shed {
get {
return this.shedField;
}
set {
this.shedField = value;
}
}
public unLocation arrivalPort {
get {
return this.arrivalPortField;
}
set {
this.arrivalPortField = value;
}
}
public string masterAirwayBillPrefix {
get {
return this.masterAirwayBillPrefixField;
}
set {
this.masterAirwayBillPrefixField = value;
}
}
public string masterAirwayBillNumber {
get {
return this.masterAirwayBillNumberField;
}
set {
this.masterAirwayBillNumberField = value;
}
}
public string houseAirwayBillNumber {
get {
return this.houseAirwayBillNumberField;
}
set {
this.houseAirwayBillNumberField = value;
}
}
public string splitReferenceNumber {
get {
return this.splitReferenceNumberField;
}
set {
this.splitReferenceNumberField = value;
}
}
public string nominatedAgent {
get {
return this.nominatedAgentField;
}
set {
this.nominatedAgentField = value;
}
}
public unLocation originPort {
get {
return this.originPortField;
}
set {
this.originPortField = value;
}
}
public unLocation destinationPort {
get {
return this.destinationPortField;
}
set {
this.destinationPortField = value;
}
}
public airCarrier airCarrier {
get {
return this.airCarrierField;
}
set {
this.airCarrierField = value;
}
}
public string flightNumber {
get {
return this.flightNumberField;
}
set {
this.flightNumberField = value;
}
}
public System.DateTime flightDate {
get {
return this.flightDateField;
}
set {
this.flightDateField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool flightDateSpecified {
get {
return this.flightDateFieldSpecified;
}
set {
this.flightDateFieldSpecified = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]
public string npx {
get {
return this.npxField;
}
set {
this.npxField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]
public string npr {
get {
return this.nprField;
}
set {
this.nprField = value;
}
}
public float grossWeight {
get {
return this.grossWeightField;
}
set {
this.grossWeightField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool grossWeightSpecified {
get {
return this.grossWeightFieldSpecified;
}
set {
this.grossWeightFieldSpecified = value;
}
}
public string goodsDescription {
get {
return this.goodsDescriptionField;
}
set {
this.goodsDescriptionField = value;
}
}
public string sdc {
get {
return this.sdcField;
}
set {
this.sdcField = value;
}
}
public System.DateTime status1Set {
get {
return this.status1SetField;
}
set {
this.status1SetField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool status1SetSpecified {
get {
return this.status1SetFieldSpecified;
}
set {
this.status1SetFieldSpecified = value;
}
}
public bool status2Set {
get {
return this.status2SetField;
}
set {
this.status2SetField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool status2SetSpecified {
get {
return this.status2SetFieldSpecified;
}
set {
this.status2SetFieldSpecified = value;
}
}
public System.DateTime ccsCreationTime {
get {
return this.ccsCreationTimeField;
}
set {
this.ccsCreationTimeField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ccsCreationTimeSpecified {
get {
return this.ccsCreationTimeFieldSpecified;
}
set {
this.ccsCreationTimeFieldSpecified = value;
}
}
public customsStatus customsStatus {
get {
return this.customsStatusField;
}
set {
this.customsStatusField = value;
}
}
public string customsSummaryText {
get {
return this.customsSummaryTextField;
}
set {
this.customsSummaryTextField = value;
}
}
public System.DateTime customsSummaryTime {
get {
return this.customsSummaryTimeField;
}
set {
this.customsSummaryTimeField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool customsSummaryTimeSpecified {
get {
return this.customsSummaryTimeFieldSpecified;
}
set {
this.customsSummaryTimeFieldSpecified = value;
}
}
public string agentReference {
get {
return this.agentReferenceField;
}
set {
this.agentReferenceField = value;
}
}
public bool isErtsPreArrival {
get {
return this.isErtsPreArrivalField;
}
set {
this.isErtsPreArrivalField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isErtsPreArrivalSpecified {
get {
return this.isErtsPreArrivalFieldSpecified;
}
set {
this.isErtsPreArrivalFieldSpecified = value;
}
}
public bool isAgentPreArrival {
get {
return this.isAgentPreArrivalField;
}
set {
this.isAgentPreArrivalField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isAgentPreArrivalSpecified {
get {
return this.isAgentPreArrivalFieldSpecified;
}
set {
this.isAgentPreArrivalFieldSpecified = value;
}
}
public bool isDeleted {
get {
return this.isDeletedField;
}
set {
this.isDeletedField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool isDeletedSpecified {
get {
return this.isDeletedFieldSpecified;
}
set {
this.isDeletedFieldSpecified = value;
}
}
public System.DateTime finalised {
get {
return this.finalisedField;
}
set {
this.finalisedField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool finalisedSpecified {
get {
return this.finalisedFieldSpecified;
}
set {
this.finalisedFieldSpecified = value;
}
}
public System.DateTime createdOn {
get {
return this.createdOnField;
}
set {
this.createdOnField = value;
}
}
public System.DateTime modifiedOn {
get {
return this.modifiedOnField;
}
set {
this.modifiedOnField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool modifiedOnSpecified {
get {
return this.modifiedOnFieldSpecified;
}
set {
this.modifiedOnFieldSpecified = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/UnLocation")]
public partial class unLocation {
private string itemField;
private ItemChoiceType itemElementNameField;
[System.Xml.Serialization.XmlElementAttribute("iataPortCode", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("oceanPortCode", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public string Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType ItemElementName {
get {
return this.itemElementNameField;
}
set {
this.itemElementNameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/UnLocation", IncludeInSchema=false)]
public enum ItemChoiceType {
/// <remarks/>
iataPortCode,
/// <remarks/>
oceanPortCode,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/CustomsStatus")]
public partial class customsStatus {
private string codeField;
private string statusTextField;
public string code {
get {
return this.codeField;
}
set {
this.codeField = value;
}
}
public string statusText {
get {
return this.statusTextField;
}
set {
this.statusTextField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="demo.org.uk/demo/AirCarrier")]
public partial class airCarrier {
private string carrierCodeField;
public string carrierCode {
get {
return this.carrierCodeField;
}
set {
this.carrierCodeField = value;
}
}
}
}
For my own sanity sake, I tried getting the provided XML to work with your classes and the nullable DateTime fields.
For them to work, replace the below properties with those linked below.
The default value for a DateTime object is DateTime.MinDate, so if the incoming value is null or empty, then the property will have a value of DateTime.MinDate anyway, for this you might need to additional validation/changes if your code needs to cater for this.
#region XML Nullable helper properties
[XmlElement(ElementName = "status1Set")]
public object status1SetXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return status1Set;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out status1SetField);
}
}
}
[XmlElement(ElementName="ccsCreationTime")]
public object ccsCreationTimeXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return ccsCreationTime;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out ccsCreationTimeField);
}
}
}
[XmlElement(ElementName = "customsSummaryTime")]
public object customsSummaryTimeXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return customsSummaryTime;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out customsSummaryTimeField);
}
}
}
[XmlElement(ElementName = "finalised")]
public object finalisedXml
{
get
{
// Return the main property itself here and not the field to ensure that if there are changes made to the getter,
// the resulting XML will always have the right value
return finalised;
}
set
{
// value passed in is of type XmlNode[], so convert and get the XmlNode text, which should be the DateTime we want
// !!ASSUMPTION!! That it will alwas be XmlNode[1] type
XmlNode[] inputValue = value as XmlNode[];
if (inputValue != null)
{
DateTime.TryParse(Convert.ToString(inputValue[0].InnerText), out finalisedField);
}
}
}
#endregion
#region Non XML properties
[XmlIgnore]
public System.DateTime status1Set
{
get { return this.status1SetField; }
set { this.status1SetField = value; }
}
[XmlIgnore]
public System.DateTime ccsCreationTime
{
get { return this.ccsCreationTimeField; }
set { this.ccsCreationTimeField = value; }
}
[XmlIgnore]
public System.DateTime customsSummaryTime
{
get { return this.customsSummaryTimeField; }
set { this.customsSummaryTimeField = value; }
}
[XmlIgnore]
public System.DateTime finalised
{
get { return this.finalisedField; }
set { this.finalisedField = value; }
}
#endregion

Validation inside a class property

The code is as follows:
public class MyEvent
{
public string EventTitle { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool IsInsideSameMonth
{
get
{
// No code is bug-free, so we assume this situation may occur somehow.
if (StartDate > EndDate)
{
// And when this occurs, we want to halt the application by throwing exception to prevent further potential damage.
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
return (StartDate.Year == EndDate.Year && StartDate.Month == EndDate.Month);
}
}
public void Validate()
{
if (StartDate > EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
if (String.IsNullOrWhiteSpace(EventTitle))
{
throw new MyEventException("Title cannot be empty.");
}
}
}
public class MyEventException : Exception
{
public MyEventException(string message)
: base(message)
{
}
}
It might seem redundant that I perform StartDate > EndDate validation inside the IsInsideSameMonth property. I just prefer being on the safe side. But it feels as if I am doing something wrong but I cannot describe it.
Is this a good practice? Please share your valuable experience and thoughts.
You shouldn't use Auto-implemented property. You should instead use a backing private field and then check while setting the property like:
private DateTime _StartDate;
public DateTime StartDate
{
get { return _StartDate; }
set
{
if (value > _EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
else
{
_StartDate = value;
}
}
}
private DateTime _EndDate;
public DateTime EndDate
{
get { return _EndDate; }
set { _EndDate = value; }
}
Your current code would allow the user to set StartDate to any value and you will only realize if you check your property IsInsideSameMonth.
For the EventTitle you could declare a backing field and make the validation inside the setter of the property. Something like this:
string eventTitle;
public string EventTitle
{
get
{
return eventTitle;
}
set
{
if(!IsNullOrWhiteSpace(value))
eventTitle = value;
else
throw new MyEventException("Title cannot be empty.");
}
}
As for the DateTime objects you could follow the same path:
private DateTime startDate;
public DateTime StartDate
{
get
{
return startDate;
}
set
{
if (value > EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
else
{
startDate = value;
}
}
}
private DateTime endDate;
public DateTime EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
}
}
It's better to control values when the properties are set, so you need to convert your automatic properties to old style (properties with private field) and put your checking there.
Here is the Microsoft property design guide.
Here is an example checking the values when setting, throwing if invalid. I've also defined functions for validation to reduce redundant code (in case you want to change your validation or error messaging- it will be in one location).
public class MyEvent
{
public bool IsInsideSameMonth
{
get
{
return (StartDate.Year == EndDate.Year && StartDate.Month == EndDate.Month);
}
}
private string _EventTile;
public string EventTitle
{
get { return _EventTile; }
set
{
ValidateTitle(value); // this will throw if invalid and leave the value of _EventTitle unchanged
_EventTile = value;
}
}
private DateTime _StartDate = DateTime.MinValue;;
public DateTime StartDate
{
get { return _StartDate; }
set
{
ValidateDates(value, EndDate); // this will throw if invalid and leave the value of _StartDate unchanged
_StartDate = value;
}
}
private DateTime _EndDate = DateTime.MaxValue;;
public DateTime EndDate
{
get { return _EndDate; }
set
{
ValidateDates(StartDate, value); // this will throw if invalid and leave the value of _EndDate unchanged
_EndDate = value;
}
}
private void ValidateDates(DateTime start, DateTime end)
{
if (start > end)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
}
private void ValidateTitle(string title)
{
if (String.IsNullOrWhiteSpace(title))
{
throw new MyEventException("Title cannot be empty.");
}
}
public void Validate()
{
ValidateDates(StartDate, EndDate);
ValidateTitle(EventTitle);
}
}
public class MyEventException : Exception
{
public MyEventException(string message)
: base(message)
{
}
}

Web service not returning integer data in an object [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
VS2003 Web Reference for a WCF Service has Extra "IdSpecified" Parameter
Thanks everyone. I totally missed that. Yes, the class name is awful.
I have a web service (ASMX) that returns an object which contains an array.
I first define my response object:
APIResponse response = new APIResponse();
Fill a datatable:
dtHolder = SqlHelper.ExecuteDatatable(connstring, CommandType.StoredProcedure, strSelect, aParams);
Create a holder for the results of my query:
API036RsBkgDetRec[] BkgDetRec_Array = new API036RsBkgDetRec[dtHolder.Rows.Count];
int i = 0;
foreach (DataRow row in dtHolder.Rows)
{
BkgDetRec_Array[i] = new API036RsBkgDetRec();
BkgDetRec_Array[i].eqoEqszId = row[0].ToString();
BkgDetRec_Array[i].eqoEqtpId = row[1].ToString();
BkgDetRec_Array[i].eqoEqhtId = row[2].ToString();
BkgDetRec_Array[i].qty = Convert.ToInt32(row[3]);
BkgDetRec_Array[i].receiveQty = Convert.ToInt32(row[4]);
BkgDetRec_Array[i].emptyTally = Convert.ToInt32(row[5]);
BkgDetRec_Array[i].maxEmpty = Convert.ToInt32(row[6]);
BkgDetRec_Array[i].chsQty = Convert.ToInt32(row[7]);
BkgDetRec_Array[i].chsTally = Convert.ToInt32(row[8]);
i++;
}
and populate the array I am returning (bkgDetTable) with the holder array I just populated above:
response.bkgDetTable = BkgDetRec_Array;
When I capture the output, I see that none of the integer fields are being created even though when I step through the code, they are being populated with real numbers. The object API036RsBkgDetRec also has them defined as integer values. Only the ones defined as string are coming across.
<bkgDetTable xmlns="http://sdfsd/xsd">
<eqoEqhtId>96</eqoEqhtId>
<eqoEqszId>40</eqoEqszId>
<eqoEqtpId>DR</eqoEqtpId>
</bkgDetTable>
Here is the definition of API036RsBkgDetRec:
public partial class API036RsBkgDetRec
{
private int chsQtyField;
private bool chsQtyFieldSpecified;
private int chsTallyField;
private bool chsTallyFieldSpecified;
private int emptyTallyField;
private bool emptyTallyFieldSpecified;
private string eqoEqhtIdField;
private string eqoEqszIdField;
private string eqoEqtpIdField;
private int maxEmptyField;
private bool maxEmptyFieldSpecified;
private int qtyField;
private bool qtyFieldSpecified;
private int receiveQtyField;
private bool receiveQtyFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public int chsQty
{
get
{
return this.chsQtyField;
}
set
{
this.chsQtyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool chsQtySpecified
{
get
{
return this.chsQtyFieldSpecified;
}
set
{
this.chsQtyFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=1)]
public int chsTally
{
get
{
return this.chsTallyField;
}
set
{
this.chsTallyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool chsTallySpecified
{
get
{
return this.chsTallyFieldSpecified;
}
set
{
this.chsTallyFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=2)]
public int emptyTally
{
get
{
return this.emptyTallyField;
}
set
{
this.emptyTallyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool emptyTallySpecified
{
get
{
return this.emptyTallyFieldSpecified;
}
set
{
this.emptyTallyFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=3)]
public string eqoEqhtId
{
get
{
return this.eqoEqhtIdField;
}
set
{
this.eqoEqhtIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=4)]
public string eqoEqszId
{
get
{
return this.eqoEqszIdField;
}
set
{
this.eqoEqszIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=5)]
public string eqoEqtpId
{
get
{
return this.eqoEqtpIdField;
}
set
{
this.eqoEqtpIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=6)]
public int maxEmpty
{
get
{
return this.maxEmptyField;
}
set
{
this.maxEmptyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool maxEmptySpecified
{
get
{
return this.maxEmptyFieldSpecified;
}
set
{
this.maxEmptyFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=7)]
public int qty
{
get
{
return this.qtyField;
}
set
{
this.qtyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool qtySpecified
{
get
{
return this.qtyFieldSpecified;
}
set
{
this.qtyFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=8)]
public int receiveQty
{
get
{
return this.receiveQtyField;
}
set
{
this.receiveQtyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool receiveQtySpecified
{
get
{
return this.receiveQtyFieldSpecified;
}
set
{
this.receiveQtyFieldSpecified = value;
}
}
}
Any ideas?
For all the INT fields, you have two fields:
the actual int field which I'm sure you're already setting to the proper value (private int emptyTallyField;)
but you also have a field called private bool emptyTallyFieldSpecified; which must be set to true - otherwise that int value you set will not be serialized out
The reason for this is because for a reference-type field like a string field, you can have NULL to represent the "there is no value" aspect, and you can have an empty string or any other string in there.
For value types, like int - how else would you represent the "there is no value specified" case? If you set the int field to 0 - is that 0 because you want that "zero" as the value, or is that "0" because you really want to say "there is no value". For this reason, all value types have this additional (fieldname)specified property which indicates whether or not an actual value is present. If that specified-flag is not set (and it's not set by default), then you have no value - thus nothing gets serialized out.
You will notice that for each property value type (integer, double, DateTime, ...) you have a XXXSpecified boolean property. For example you have:
public int maxEmpty
and
public bool maxEmptySpecified
Those properties are generated when you import a WCF web service using wsdl.exe (or Add Web Reference in Visual Studio). You need to set them to true every-time you set their corresponding value type property value.
I agree that this is total crap but, that's how it is. ASMX is deprecated now.

Categories

Resources