I am trying to insert a data in my local database (SQLited Database) using InsertAsync. But I keep getting this error.
sqlite.sqliteexception: constraint at sqlite.preparedsqlliteinsertcommand.executenonquery
How can I fix and avoid this in the future? Below is my sample code.
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
try
{
var caf_insert = new CAFTable
{
CAFNo = caf,
EmployeeID = employeenumber,
CAFDate = DateTime.Parse(date),
CustomerID = retailercode,
StartTime = DateTime.Parse(starttime),
EndTime = DateTime.Parse(endtime),
Photo1 = photo1url,
Photo2 = photo2url,
Photo3 = photo3url,
Video = videourl,
GPSCoordinates = actlocation,
Remarks = remarks,
OtherConcern = otherconcern,
RecordLog = recordlog,
LastUpdated = DateTime.Parse(current_datetime)
};
await conn.InsertOrReplaceAsync(caf_insert);
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
Here is the CAF Table
[Table("tblCaf")]
public class CAFTable
{
[PrimaryKey, MaxLength(50)]
public string CAFNo { get; set; }
[MaxLength(50)]
public string EmployeeID { get; set; }
public DateTime CAFDate { get; set; }
[MaxLength(50)]
public string CustomerID { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Photo1 { get; set; }
public string Photo2 { get; set; }
public string Photo3 { get; set; }
public string Video { get; set; }
public string MobilePhoto1 { get; set; }
public string MobilePhoto2 { get; set; }
public string MobilePhoto3 { get; set; }
public string MobileVideo { get; set; }
[MaxLength(2000)]
public string Remarks { get; set; }
[MaxLength(2000)]
public string OtherConcern { get; set; }
[MaxLength(2000)]
public string GPSCoordinates { get; set; }
[MaxLength(100)]
public string RecordLog { get; set; }
public DateTime LastSync { get; set; }
public DateTime LastUpdated { get; set; }
public int Existed { get; set; }
public int Deleted { get; set; }
public int ThisSynced { get; set; }
public int Media1Synced { get; set; }
public int Media2Synced { get; set; }
public int Media3Synced { get; set; }
public int Media4Synced { get; set; }
}
Make sure the value of caf in your code, that you're trying to insert, does not already exist in the table.
Related
i have this Json
{
"queryresult":{
"responseMessage":"success",
"customer":{
"accountNumber":"8292829222",
"meterNumber":"",
"phoneNumber":"",
"lastName":"CHRISTIAN ",
"address":"2 OSISIOMA NGWA, ABIA",
"city":null,
"district":"Damata",
"userCategory":"NON-MD",
"customerType":"unmetered",
"paymentPlan":"Postpaid",
"vat":463.8525,
"tariffCode":"R2SC-NMD",
"tariffRate":53.78,
"arrearsBalance":129324.8435,
"billedAmount":6184.7,
"billedDate":"08-2022",
"lastPayDate":null,
"lastpayment":{
}
},
"responseCode":200,
"status":"true"
},
"status":true
}
When i deserialize with
var data = JsonConvert.DeserializeObject<Data>(readTask);
it throws and error saying
Input String '463.8525' is not a valid integer
which is the vat field
How do i solve this issue? below is my model
public class customer
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public object city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public double vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public double? arrearsBalance { get; set; }
public double billedAmount { get; set; }
public string? billedDate { get; set; }
public string? lastPayDate { get; set; }
public Lastpayments lastpayment { get; set; }
}
public class Lastpayments
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int? amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresults
{
public string responseMessage { get; set; }
public customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Data
{
public Queryresults queryresult { get; set; }
public bool status { get; set; }
}
The error points to the vat field. I tried using [JsonIgnore] to Ignore the vat field as i dont really need it but it dint work
I want to create a query that will return an AgencyContractData object containing a DocumentDto object, but it may be that the original object does not contain a foreign key on the Document. I can't use ternary operator in an Entity-Framwork LINQ query. How it is possible to implement it (Required that select be converted to sql query)?
var contractList = await query
.Select(contract => new AgencyContractData
{
ContractId = contract.Id,
ContractNumber = contract.ContractNumber,
CustomerId = contract.CustomerId,
CustomerName = contract.CustomerName,
Group = contract.Group,
CommodityType = contract.CommodityType,
SupplierName = contract.SupplierName,
StartDate = contract.StartDate,
EndDate = contract.EndDate,
ExecutionDate = contract.ExecutionDate,
ContractUnit = contract.ContractUnit,
Comment = contract.Comment,
Pricing = contract.Pricing,
SecondaryCustomerName = contract.SecondaryCustomerName,
ContractType = contract.ContractType,
AnnualVolume = contract.AnnualVolume,
Document = new DocumentDto
{
DocumentId = contract.Document.Id,
CounterPartyId = contract.Document.CounterPartyId,
FilePath = contract.Document.FilePath,
DocumentTitle = contract.Document.DocumentTitle,
IsCustomerUpload = contract.Document.IsCustomerUpload,
DocumentBytes = null
},
DocumentName = contract.DocumentName,
ContractNumberInt = contract.ContractNumberInt,
ContractNumberString = contract.ContractNumberString,
MsaBaseNumber = contract.MsaBaseNumber,
NotificationDays = contract.NotificationInDays,
State = contract.State,
CreatedOn = contract.CreatedOn,
CreatedBy = contract.CreatedBy,
ModifiedOn = contract.ModifiedOn,
ModifiedBy = contract.ModifiedBy,
It is the AgencyContract entity:
public class Contract : IEntity<long>
{
public long Id { get; set; }
public string ContractNumber { get; set; }
public long? ContractUnitId { get; set; }
public int? NumPricePeriods { get; set; }
public double? Tolerance { get; set; }
public ContractTypeEnum? ContractType { get; set; }
public ContractTolerancePeriodEnum? ContractTolerancePeriod { get; set; }
public bool IsRelyContract { get; set; }
public int TermsEndNoticeDays { get; set; }
public bool IsProrated { get; set; }
public bool IsContinuation { get; set; }
public long SupplierId { get; set; }
public long? DocumentId { get; set; }
public long? BrokerId { get; set; }
public BillTypeEnum? BillType { get; set; }
public string ExternalId { get; set; }
#region Navigation Properties
public virtual Supplier Supplier { get; set; }
public virtual Broker Broker { get; set; }
public virtual ContractUnit ContractUnit { get; set; }
public virtual Account Account { get; set; }
public virtual List<UsnAccountToContract> UsnAccountToContracts { get; set; }
public virtual List<ProviderLookup> ProviderLookups { get; set; }
public virtual List<ContractNotification> ContractNotifications { get; set; }
public virtual List<ContractVolume> ContractVolumes { get; set; }
public virtual Document Document { get; set; }
#endregion
And I want to make a AgencyContractData object using Select:
public class AgencyContractData
{
public int? AnnualVolume { get; set; }
public string Comment { get; set; }
public AgencyCommodityTypeEnum CommodityType { get; set; }
public long ContractId { get; set; }
public string ContractNumber { get; set; }
public long? ContractNumberInt { get; set; }
public string ContractNumberString { get; set; }
public int? ContractReportLevelByGlobalSearch { get; set; }
public AgencyContractTypeEnum ContractType { get; set; }
public AgencyContractUnitEnum ContractUnit { get; set; }
public Guid? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public string DocumentName { get; set; }
public DocumentDto Document { get; set; }
public DateTime? EndDate { get; set; }
public DateTime ExecutionDate { get; set; }
public string Group { get; set; }
public List<AgencyLocationData> Locations { get; set; }
public Guid? LockedBy { get; set; }
public DateTime? LockedOn { get; set; }
public string Md5Hash { get; set; }
public Guid? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public string MsaBaseNumber { get; set; }
public int? NotificationDays { get; set; }
public DateTime? NotificationSentOn { get; set; }
public string Pricing { get; set; }
public string SecondaryCustomerName { get; set; }
public int Sites { get; set; }
public DateTime StartDate { get; set; }
public string State { get; set; }
public string Status { get; set; }
public string SupplierName { get; set; }
Here is the method where I have the problem:
[HttpPost]
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var fileStream = new FileStream(Path.Combine(uploads, xmlFile.FileName), FileMode.Create))
{
await xmlFile.CopyToAsync(fileStream);
XDocument xDoc = XDocument.Load(fileStream);
List<DmgRegister> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
new DmgRegister
{
Uwyear = dmgReg.Element("UWYear").Value,
ClaimNo = dmgReg.Element("ClaimNo").Value,
PolicyNo = dmgReg.Element("PolicyNo").Value,
PolicyName = dmgReg.Element("PolicyHolder").Value,
Address1 = dmgReg.Element("Address1").Value,
Address2 = dmgReg.Element("Addresstype").Value,
PostalLocation = dmgReg.Element("City").Value,
Country = dmgReg.Element("Country").Value,
PostalCode = dmgReg.Element("Postalzone").Value
}).ToList();
context.SaveXmlToDb(dmgRegistterList);
}
catch
{
//Here where i come when i try to upload and parse the data
ViewBag.Error = "Converting fail";
return View("Export");
}
}
else
{
ViewBag.Error = "Uploading fail";
return View("Index");
}
return View();
}
Im trying to upload an xml file and then parse into a SQL Table(Sql DataTable named DmgRegister), I'm a beginner with ASP.Net so exuse me if the code looks like an italian spaghetti.
// SaveXmlToDb method in context
foreach (var item in dmgRegistterList)
{
DmgRegister.Add(item);
}
SaveChanges();
}
Now the Model that I'm trying to bind data from XML and save it to DataTable
[Serializable]
[XmlRoot("Claims")]
public class Claim
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
[XmlElement("UWYear")]
public string Uwyear { get; set; }
[XmlElement("AgreementNo")]
public string AgreementNo { get; set; }
[XmlElement("BusinessType")]
public string BusinessType { get; set; }
[XmlElement("PeriodStart")]
public DateTime? PeriodStart { get; set; }
[XmlElement("PeriodEnd")]
public DateTime? PeriodEnd { get; set; }
[XmlElement("PolicyNo")]
public string PolicyNo { get; set; }
[XmlElement("PolicyHolder")]
public string PolicyName { get; set; }
[XmlElement("DateOfLoss")]
public DateTime? DateOfLoss { get; set; }
[XmlElement("ClaimNo")]
public string ClaimNo { get; set; }
[XmlElement("ClaimantName")]
public string ClaimantName { get; set; }
[XmlElement("ClaimedInsured")]
public string ClaimedInsured { get; set; }
[XmlElement("ReportDate")]
public DateTime? ReportDate { get; set; }
[XmlElement("CountryOfRisk")]
public string CountryOfRisk { get; set; }
[XmlElement("CountryOfLoss")]
public string CountryOfLoss { get; set; }
[XmlElement("TypeOfLoss")]
public string TypeOfLoss { get; set; }
[XmlElement("InsuranceCoverage")]
public string InsuranceCoverage { get; set; }
[XmlElement("LineOfBuisnessNo")]
public int? LineOfBuisnessNo { get; set; }
[XmlElement("LineOfBuisnessName")]
public string LineOfBuisnessName { get; set; }
[XmlElement("ClassOfBuisnessNo")]
public int? ClassOfBuisnessNo { get; set; }
[XmlElement("ClassOfBuisnessName")]
public string ClassOfBuisnessName { get; set; }
[XmlElement("CaptiveShare")]
public int? CaptiveShare { get; set; }
[XmlElement("OriginalCurrency")]
public string OriginalCurrency { get; set; }
[XmlElement("PaymentCurrency")]
public string PaidInCurrency { get; set; }
[XmlElement("TotalIncurredCaptiveShare")]
public decimal? TotalIncurredCaptiveShare { get; set; }
[XmlElement("PaidThisPeriod")]
public decimal? PaidThisPeriod { get; set; }
[XmlElement("PeriodDate")]
public DateTime? PeriodDate { get; set; }
[XmlElement("PaymentDate")]
public DateTime? PaymentDate { get; set; }
[XmlElement("TotalPaidCaptiveShare")]
public decimal? TotalPaidCaptiveShare { get; set; }
[XmlElement("RemainingReserveCaptiveShare")]
public decimal? RemainingReserveCaptiveShare { get; set; }
[XmlElement("Deductible")]
public string Deductible { get; set; }
[XmlElement("Recovery")]
public string Recovery { get; set; }
[XmlElement("LocationAdress")]
public string LocationAdress { get; set; }
[XmlElement("Address1")]
public string Address1 { get; set; }
[XmlElement("Addresstype")]
public string Address2 { get; set; }
[XmlElement("Postalzone")]
public string PostalCode { get; set; }
[XmlElement("City")]
public string PostalLocation { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("GeograficalDiversification")]
public string GeograficalDiversification { get; set; }
[XmlElement("Cause")]
public string Cause { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("CloseDate")]
public DateTime? CloseDate { get; set; }
[XmlElement("DevelopmentYear")]
public string DevelopmentYear { get; set; }
[XmlElement("TotalIncurredInsurerShare")]
public decimal? TotalIncurredInsurerShare { get; set; }
[XmlElement("TotalPaidInsurerShare")]
public decimal? TotalPaidInsurerShare { get; set; }
[XmlElement("RemainingReserveInsurerShare")]
public decimal? RemainingReserveInsurerShare { get; set; }
}
[Serializable()]
[XmlRoot("Claims")]
public class Claims
{
[XmlArray("Claims")]
[XmlArrayItem("Claim", typeof(Claim))]
public Claim[] Claim { get; set; }
}
Here is the Xml example that im try upload
<ns0:Claims>
<Claim>
<ClaimNo>LL0000110262</ClaimNo>
<PolicyNo>LP0000004481</PolicyNo>
<PolicyHolder>NCC Rakennus Oy</PolicyHolder>
<AddressId>1</AddressId>
<Address1>Example Street 1</Address1>
<Addresstype>LocationOfLoss</Addresstype>
<City>Helsinki</City>
<Country>FI</Country>
<Postalzone>12345</Postalzone>
<UWYear>2015</UWYear>
<PeriodStart>2015-01-01</PeriodStart>
<PeriodEnd>2015-12-31</PeriodEnd>
<DateOfLoss>2015-07-15</DateOfLoss>
<ReportDate/>
<StatusAsPer>2015-12-31</StatusAsPer>
<Coverage>?</Coverage>
<TypeOfLoss>Leakage</TypeOfLoss>
<OriginalCurrency>EUR</OriginalCurrency>
<PaymentCurrency>EUR</PaymentCurrency>
<TotalReservesOrigCurr>0.00</TotalReservesOrigCurr>
<TotalPaymentOrigCurr>0.00</TotalPaymentOrigCurr>
<DeductibleOrigCurr>85000.00</DeductibleOrigCurr>
<TotalAmountOfClaimOrigCurr>3680.00</TotalAmountOfClaimOrigCurr>
<Status>Active</Status>
</Claim>
</ns0:Claims>
I try it even to convert from XML to JSON, but it jumps to catch
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
var filePath = Path.Combine(uploads, xmlFile.FileName);
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var xReader = XmlReader.Create(new StringReader(filePath)))
{
// This line skips the XML declaration, eg "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - you can skip this if you don't have declaration as in your case
xReader.MoveToContent();
// Gets the actual XMLElement, if any
xReader.Read();
// Convert the xReader to an XNode for the Json serializer
XNode node = XNode.ReadFrom(xReader);
// Json output
string jsonText = JsonConvert.SerializeXNode(node);
}
}
catch
{
ViewBag.Error = "Converting fail";
return View("Export");
}
}
else
{
ViewBag.Error = "Uploading fail";
return View();
}
return View("Index");
}
Thx a lot CountZero, really gratefull after my first question here, still had issues but now is everything working,
The method in controller
public async Task<IActionResult> XmlPage(IFormFile xmlFile)
{
var uploads = hostingEnvironment.WebRootPath;
var filePath = Path.Combine(uploads, xmlFile.FileName).ToString();
if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
{
try
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await xmlFile.CopyToAsync(fileStream);
fileStream.Dispose();
XDocument xDoc = XDocument.Load(filePath);
List<DmgRegisterVM> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
new DmgRegisterVM
{
Uwyear = dmgReg.Element("UWYear").Value,
ClaimNo = dmgReg.Element("ClaimNo").Value,
PolicyNo = dmgReg.Element("PolicyNo").Value,
PolicyName = dmgReg.Element("PolicyHolder").Value,
Address1 = dmgReg.Element("Address1").Value,
Address2 = dmgReg.Element("Addresstype").Value,
PostalLocation = dmgReg.Element("City").Value,
Country = dmgReg.Element("Country").Value,
PostalCode = dmgReg.Element("Postalzone").Value
}).ToList();
context.SaveXmlToDb(dmgRegistterList);
}
}
catch(Exception e)
{
ViewBag.Error = "Converting fail";
}
}
else
{
ViewBag.Error = "Uploading fail";
}
return View("Index");
}
SaveXmlToDb method in context
public void SaveXmlToDb(List<DmgRegisterVM> dmgRegList)
{
//from list to database
foreach (var item in dmgRegList)
{
var model = Mapper.Map<DmgRegister>(item);
DmgRegister.Add(model);
SaveChanges();
}
}
And finally the Claim class (where i have XML elements)
[Serializable]
[XmlRoot("ns0:Claims")]
public class Claim
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
[XmlElement("UWYear")]
public string Uwyear { get; set; }
[XmlElement("AgreementNo")]
public string AgreementNo { get; set; }
[XmlElement("BusinessType")]
public string BusinessType { get; set; }
[XmlElement("PeriodStart")]
public DateTime? PeriodStart { get; set; }
[XmlElement("PeriodEnd")]
public DateTime? PeriodEnd { get; set; }
[XmlElement("PolicyNo")]
public string PolicyNo { get; set; }
[XmlElement("PolicyHolder")]
public string PolicyName { get; set; }
[XmlElement("DateOfLoss")]
public DateTime? DateOfLoss { get; set; }
[XmlElement("ClaimNo")]
public string ClaimNo { get; set; }
[XmlElement("ClaimantName")]
public string ClaimantName { get; set; }
[XmlElement("ClaimedInsured")]
public string ClaimedInsured { get; set; }
[XmlElement("ReportDate")]
public DateTime? ReportDate { get; set; }
[XmlElement("CountryOfRisk")]
public string CountryOfRisk { get; set; }
[XmlElement("CountryOfLoss")]
public string CountryOfLoss { get; set; }
[XmlElement("TypeOfLoss")]
public string TypeOfLoss { get; set; }
[XmlElement("InsuranceCoverage")]
public string InsuranceCoverage { get; set; }
[XmlElement("LineOfBuisnessNo")]
public int? LineOfBuisnessNo { get; set; }
[XmlElement("LineOfBuisnessName")]
public string LineOfBuisnessName { get; set; }
[XmlElement("ClassOfBuisnessNo")]
public int? ClassOfBuisnessNo { get; set; }
[XmlElement("ClassOfBuisnessName")]
public string ClassOfBuisnessName { get; set; }
[XmlElement("CaptiveShare")]
public int? CaptiveShare { get; set; }
[XmlElement("OriginalCurrency")]
public string OriginalCurrency { get; set; }
[XmlElement("PaymentCurrency")]
public string PaidInCurrency { get; set; }
[XmlElement("TotalIncurredCaptiveShare")]
public decimal? TotalIncurredCaptiveShare { get; set; }
[XmlElement("PaidThisPeriod")]
public decimal? PaidThisPeriod { get; set; }
[XmlElement("PeriodDate")]
public DateTime? PeriodDate { get; set; }
[XmlElement("PaymentDate")]
public DateTime? PaymentDate { get; set; }
[XmlElement("TotalPaidCaptiveShare")]
public decimal? TotalPaidCaptiveShare { get; set; }
[XmlElement("RemainingReserveCaptiveShare")]
public decimal? RemainingReserveCaptiveShare { get; set; }
[XmlElement("Deductible")]
public string Deductible { get; set; }
[XmlElement("Recovery")]
public string Recovery { get; set; }
[XmlElement("LocationAdress")]
public string LocationAdress { get; set; }
[XmlElement("Address1")]
public string Address1 { get; set; }
[XmlElement("Addresstype")]
public string Address2 { get; set; }
[XmlElement("Postalzone")]
public string PostalCode { get; set; }
[XmlElement("City")]
public string PostalLocation { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
[XmlElement("GeograficalDiversification")]
public string GeograficalDiversification { get; set; }
[XmlElement("Cause")]
public string Cause { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
[XmlElement("CloseDate")]
public DateTime? CloseDate { get; set; }
[XmlElement("DevelopmentYear")]
public string DevelopmentYear { get; set; }
[XmlElement("TotalIncurredInsurerShare")]
public decimal? TotalIncurredInsurerShare { get; set; }
[XmlElement("TotalPaidInsurerShare")]
public decimal? TotalPaidInsurerShare { get; set; }
[XmlElement("RemainingReserveInsurerShare")]
public decimal? RemainingReserveInsurerShare { get; set; }
}
//[ModelMetadataType(typeof(DmgRegisterMetaData))]
[Serializable()]
[XmlRoot("ns0:Claims")]
public class ClaimsCollection
{
[XmlArray("Claims")]
[XmlArrayItem("Claim", typeof(Claim))]
public Claim[] Claim { get; set; }
}
Given you are getting a "Root element is missing" this looks like an issue with your mapping.
[XmlRoot("Claims")] will not map onto <ns0:Claims>.
Try updating your XML so the roots element is set to <Claims></Claims> rather than
<ns0:Claims></ns0:Claims>.
If this fixes it then you can either change your XML or update your attribute in the class so it looks like this.
[XmlRoot("ns0:Claims")].
I am stuck with an error i can't figure out. I have a complex model with several circular references. I have tried everything i know to handle them but i am still getting a internal server error (code 500) when i attempt saving.
Below are the models and controllers:
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public Event Event { get; set; }
public RecurrenceType RecurrenceType { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
[StringLength(256)]
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
[Required]
[StringLength(256)]
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public class EventDTO
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public int EventTypeId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int RecurrenceTypeId { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public List<string> UserId { get; set; }
}
public async Task<IHttpActionResult> PostEvent(EventDTO #event)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Event newEvent = new Event();
newEvent.Title = #event.Title;
newEvent.EventTypeId = #event.EventTypeId;
newEvent.CreateDate = #event.CreateDate;
newEvent.UpdateDate = #event.UpdateDate;
newEvent.CreatedBy = #event.CreatedBy;
newEvent.UpdatedBy = #event.CreatedBy;
if (newEvent == null) {
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating Event"));
}
Recurrence recurrence = new Recurrence();
recurrence.StartDate = #event.StartDate;
recurrence.EndDate = #event.EndDate;
recurrence.AllDay = #event.AllDay;
recurrence.StartTime = #event.StartTime;
recurrence.EndTime = #event.EndTime;
recurrence.Venue = #event.Venue;
recurrence.Longitude = #event.Longitude;
recurrence.Latitude = #event.Latitude;
recurrence.RecurrenceTypeId = #event.RecurrenceTypeId;
recurrence.RecurrenceInterval = #event.RecurrenceInterval;
recurrence.ExcludeWeekends = #event.ExcludeWeekends;
recurrence.CreateDate = #event.CreateDate;
recurrence.UpdateDate = #event.UpdateDate;
recurrence.CreatedBy = #event.CreatedBy;
recurrence.UpdatedBy = #event.CreatedBy;
if (recurrence == null)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating recurrence"));
}
var users = db.AspNetUsers.Where(u => #event.UserId.Contains(u.Id));
foreach (var u in users)
recurrence.AspNetUsers.Add(u);
newEvent.Recurrences.Add(recurrence);
db.Events.Add(newEvent);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = #event.Id }, newEvent);
}
When i call the post method i get an internal error code 500 and an error message of "{$id=1, Message=An error has occurred}".
I am developing online aircraft sales system.
But I have a problem..
A URL address have:
string urlFlightSearch = "https://api.iati.com/rest/flightSearch/" + ado.iatiKod + "";
A have class "iati.cs" in codes
public class iati
{
public class flightSearch
{
public string fromAirport { get; set; }
public bool allinFromCity { get; set; }
public string toAirport { get; set; }
public string fromDate { get; set; }
public string returnDate { get; set; }
public string adult { get; set; }
public string currency { get; set; }
}
public class Leg
{
public string flightNo { get; set; }
public string aircraft { get; set; }
public string operatorCode { get; set; }
public string operatorName { get; set; }
public string departureAirport { get; set; }
public string departureTime { get; set; }
public string departureAirportName { get; set; }
public string departureCityName { get; set; }
public string arrivalAirport { get; set; }
public string arrivalTime { get; set; }
public string arrivalAirportName { get; set; }
public string arrivalCityName { get; set; }
}
public class Detail
{
public double price { get; set; }
public double serviceFee { get; set; }
public double tax { get; set; }
public int suplement { get; set; }
}
public class Fare
{
public double totalSingleAdultFare { get; set; }
public string currency { get; set; }
public string type { get; set; }
public List<string> segmentNames { get; set; }
public int freeSeatCount { get; set; }
public Detail detail { get; set; }
}
public class Flight
{
public string id { get; set; }
public string providerKey { get; set; }
public string pricingType { get; set; }
public int packageId { get; set; }
public List<Leg> legs { get; set; }
public List<Fare> fares { get; set; }
public int segmentCount { get; set; }
public int baggage { get; set; }
public int flightTimeHour { get; set; }
public int flightTimeMinute { get; set; }
public int layoverTime { get; set; }
public bool hasCip { get; set; }
public bool canBook { get; set; }
public bool canRezerve { get; set; }
public bool dayCross { get; set; }
public bool returnFlight { get; set; }
}
public class Result
{
public string searchId { get; set; }
public List<Flight> flights { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
}
And posting...
WebClient wc = new WebClient();
var serializer = new JavaScriptSerializer();
iati.flightSearch search = new iati.flightSearch()
{
fromAirport = "IST",
allinFromCity = true,
toAirport = "AYT",
fromDate = "2013-12-23",
returnDate = "2013-12-30",
adult = "1",
currency = "EUR"
};
var serializedResult = serializer.Serialize(search);
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
string result = wc.UploadString(urlFlightSearch, serializedResult);
iati.Flight flight = serializer.Deserialize<iati.Flight>(result);
But the result returned is always coming up empty.
Regards.
use Newtonsoft
JsonConvert.DeserializeObject(result);