I have a problem with my date. I do the insert with the postman and no matter what I enter I always get back "0001-01-01T00:00:00".
Would also like to limit the output to just the date.
I am very grateful for any help
thank you
Model:
public class BusinessTripDocument
{
public long Id { get; set; }
public string StartLocation { get; set; }
[JsonPropertyName("startDateTime")]
public DateTime StartDate { get; set; }
public string Destination { get; set; }
public DateTime DestinationDate { get; set; }
public string Transportation { get; set; }
public string SuperiorsApproval { get; set; }
// POST: api/Businesstripdocuments
[HttpPost("new/{eId}")]
public async Task<ActionResult<BusinessTripDocument>> PostBusinesstripdocuments(long eId, BusinessTripDocument businesstripdocuments)
{
Employee employee = await _context.Employees.FindAsync(eId);
// businesstripdocuments.Employee = employee;
// _context.Businesstripdocuments.Add(businesstripdocuments);
employee.addDocument(businesstripdocuments);
await _context.SaveChangesAsync();
return CreatedAtAction("GetBusinesstripdocuments", new { id = businesstripdocuments.Id }, businesstripdocuments);
}
Postman
Just from the code you've shown- to me it looks like you should just need to supply the DataType attribute to your Model?
//using System.ComponentModel.DataAnnotations;
public class BusinessTripDocument
{
...
[DataType(DataType.Date)]
[JsonPropertyName("startDateTime")]
public DateTime StartDate { get; set; }
...
}
I suggest that you could do two ways:
1.- The date could be inside the method PostBusinesstripdocuments
2.- The date could be string in class BusinessTripDocument and after conver to datetime.
her is the example:
Related
Is it possible to point DateTimeOffset custom format for object's property? This object will be serialized/deserialized (JSON) in ASP.NET controller's action.
I thought it can be done through attribute, like `[Required], but I didn't find it.
public abstract class EventDto
{
public EventDto(EventTypes eventType)
{
EventType = eventType;
}
[Required]
public EventTypes EventType { get; }
[Required]
public Guid SessionId { get; set; }
[Required]
// Something like this: [JsonFormat("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz")]
public DateTimeOffset Timestamp { get; set; }
}
Try something like this
public class Test
{
public DateTime date { get; set; }
public string Timestamp
{
get { return date.ToString("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz");}
set { date = DateTime.ParseExact(value, "YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz", System.Globalization.CultureInfo.InvariantCulture)}
}
}
I am giving up on this.
I've got the following Json that I need to deserialize:
json = "{
"2018-05-21": {
"lastUpdate": "2018-05-21 01:00:05",
"stops": [
{
"stopId": 1838,
"stopCode": "02"
}, {
"stopId": 1839,
"stopCode": "08"
}]}}";
var deserialized = JsonConvert.DeserializeObject<StopDate>(json); // null
and those classes:
public class StopDate
{
public BusStop date { get; set; }
}
public class BusStop
{
public string LastUpdate { get; set; }
public Stop[] Stops { get; set; }
}
public class Stop
{
public int StopId { get; set; }
public string StopName { get; set; }
}
The problem is that deserialized variable is null.
Apart from the overall ugliness when it comes to the names etc, I'd like it to be up and running just for a good start. All help's appreciated.
Convert the JSON to a Dictionary<DateTime, BusStop>
var deserialized = JsonConvert.DeserializeObject<Dictionary<DateTime, BusStop>>(json);
The DateTime key of the dictionary maps to the date in the JSON.
If the DateTime causes any issue then use a string as the key, ie Dictionary<string, BusStop> where the key can be parsed into a DateTime is needed
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, BusStop>>(json);
BusStop busStop = deserialized["2018-05-21"];
And you probably want to make LastUpdate a DateTime rather than a string (as suggested by a commenter)
public class BusStop {
public DateTime LastUpdate { get; set; }
public Stop[] Stops { get; set; }
}
public class Stop {
public int StopId { get; set; }
[JsonProperty("stopCode")]
public string StopName { get; set; }
}
We have this data
models:"[{"timeTableId":5,"startTime":"2016-06-16T00:00:00","endTime":"2016-06-16T17:00:00","userId":31,"customerId":35}]"
being sent to a asp.net webservice using api.
We cannot determine how to extract the data for manipulation, we have tried...
public IHttpActionResult PostTimeTable([FromBody]string models);// models is null
public IHttpActionResult PostTimeTable(string models);// models is null
public IHttpActionResult PostTimeTable([FromBody]List<TimetableView> models);// models is null
public IHttpActionResult PostTimeTable(IEnumerable<TimetableView> models);// models is null
Where TimetableView is
public class TimetableView
{
public TimetableView(TimeTable timetable)
{
this.TimeTableId = timetable.TimeTableId;
this.StartTime = timetable.StartTime;
this.EndTime = timetable.EndTime;
this.UserId = timetable.UserId;
this.CustomerId = timetable.CustomerId ;
}
public TimetableView(){}
public int TimeTableId { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int UserId { get; set; }
public int CustomerId { get; set; }
}
try this
public IHttpActionResult PostTimeTable(
int timeTableId,
DateTiem startTime,
DateTime endTime,
int userId,
int customerId);
I have found out why this was not saving or getting the correct information and have solved this.
here is a link to the pastbin: http://pastebin.com/p8HjFdeu
Many a times i have to do select required fields from a class as in case of selected desired fields from Table in sql.
So i was thinking of making my class and struct as Projectables.
Here is what I want to achieve.
public class Email
{
public string Subject { get; set; }
public string To { get; set; }
public string Cc { get; set; }
public string Bcc { get; set; }
public string Body { get; set; }
public DateTime ReceivedDate { get; set; }
}
public class EmailProjection
{
// instead of this
//public string Subject { get; set; }
//public DateTime ReceivedDate { get; set; }
// I want to do this
Email.Project(Subject,ReceivedDate);
}
public class EntryPoint
{
static void Main()
{
var emailList = new List<Email>();
/* populate emails here from source*/
// I want to do this
List<EmailProjection> emailProjectionList = emailList.Project(EmailProjection).ToList();
// rather than
List<EmailProjection> emailProjectionList= emailList.Select(email=>new {email.Subject,email.ReceivedDate}).ToList();}
}
Can somebody help me as to how to go about this? Hints?? Is it achievable?
You can have a look at Automapper: https://github.com/AutoMapper/AutoMapper.
It is a library to map DTO based on naming conventions and rules.
Take a look in the wiki there is a Projection page, that could be the one you are looking for.
Just for connect with your example, you can eventually write code like this:
Mapper.Map<EMail, EmailProjection>(yourObjects);
I saw few topics but no one looks like my problem.
Here is my class:
namespace Framework.Cielo.Models
{
[XmlRoot("transacao", Namespace = "http://ecommerce.cbmp.com.br")]
public class TransactionResponse
{
[XmlAttribute("id")]
public string ID { get; set; }
[XmlAttribute("versao")]
public string Version { get; set; }
[XmlElement("tid")]
public string tid { get; set; }
[XmlElement("pan")]
public string pan { get; set; }
[XmlElement("dados-pedido")]
public EstablishmentOrder Order { get; set; }
[XmlElement("forma-pagamento")]
public PaymentMethod PaymentMethod { get; set; }
[XmlElement("status")]
public TransactionStatusEnum Status { get; set; }
[XmlElement("url-retorno")]
public string ReturnUrl { get; set; }
[XmlElement("autenticacao")]
public Authentication Authentication { get; set; }
}
}
and here is the authentication class
namespace Framework.Cielo.Models
{
[XmlRoot("autenticacao")]
public class Authentication
{
[XmlElement("codigo")]
public int Code { get; set; }
[XmlElement("mensagem")]
public string Message { get; set; }
[XmlIgnore]
public DateTime Date { get; set; }
[XmlElement("data-hora")]
public string FormattedDate
{
get
{
return Date.ToString("yyyy-MM-ddTHH:mm:ss");
}
set
{
DateTime kdc = DateTime.MinValue;
DateTime.TryParse(value, out kdc);
Date = kdc;
}
}
[XmlElement("valor")]
public int Value { get; set; }
[XmlElement("lr")]
public int SecurityLevel { get; set; }
[XmlElement("arp")]
public object arp { get; set; }
[XmlElement("nsu")]
public object nsu { get; set; }
}
}
Here is how I deserialize:
string serializado = File.ReadAllText("req.xml");
var stringReader = new System.IO.StringReader(serializado);
var serializer = new XmlSerializer(typeof(TransactionResponse));
TransactionResponse preAuthResponse = serializer.Deserialize(stringReader) as TransactionResponse;
and here is my XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<transacao versao="1.3.0" id="100" xmlns="http://ecommerce.cbmp.com.br">
<tid>10069930690A16DF1001</tid>
<pan>b1SQ6jpKCDt3n9C0dgD/ZkPQ1Bh+7aJESqr/CwP64P0=</pan>
<dados-pedido>
<numero>100</numero>
<valor>29900</valor>
<moeda>986</moeda>
<data-hora>2013-10-15T00:57:19.032-03:00</data-hora>
<descricao/>
<idioma>PT</idioma>
<taxa-embarque>0</taxa-embarque>
</dados-pedido>
<forma-pagamento>
<bandeira>mastercard</bandeira>
<produto>1</produto>
<parcelas>1</parcelas>
</forma-pagamento>
<status>4</status>
<autenticacao>
<codigo>4</codigo>
<mensagem>Transacao sem autenticacao</mensagem>
<data-hora>2013-10-15T00:57:19.037-03:00</data-hora>
<valor>29900</valor>
<eci>0</eci>
</autenticacao>
<autorizacao>
<codigo>4</codigo>
<mensagem>Transação autorizada</mensagem>
<data-hora>2013-10-15T00:57:19.041-03:00</data-hora>
<valor>29900</valor>
<lr>00</lr>
<arp>123456</arp>
<nsu>661215</nsu>
</autorizacao>
</transacao>
When I run this code, all the elements get right, but not ARP and NSU elements (the last 2 of autorizacao tag)
I really don't know why. This XML comes from a web service and I can't figure out why my deserialize don't work with the 2 last items but works greater with any other element.
I have tried with your code and updated following and it works.
Commented second last <autenticacao> tag.
Rename last tag <autorizacao> to <autenticacao> . May be you are getting wrong xml & last two tags are confusing so I have tried with only one tag.
In Authentication class I have changed type of ARP and NSU otherwise we are getting XMlNode type while deserializing. You can also use string instead of int.
[XmlElement("arp")]
public int arp { get; set; }
[XmlElement("nsu")]
public int nsu { get; set; }