How to handle date binding in Nancy? - nancy

Upgrading from Nancy 1 to Nancy 2 I am facing a problem with binding date parameters. I am sending the following json payload from an angularjs app:
{
date=2018-04-30T22:00:00.000Z
}
When binding the object with Nancy 2 it is converted to 30.04.2018 22:00:00. and not to 01.05.2018 00:00:00. How do I convert to the local (Croatian) time zone?

Related

ASP.NET MVC 5 'DateTime' cannot be saved on sql server 'datetime' format on Release (published) mode but works on Debug mode

So I have an ASP.NET MV5 app, I'm using Entity Framework 6 and a SQL Server database. I also use this: datepicker
I have bootstrap-datepicker input with this format: 'dd.mm.yyyy'. With jQuery I get this field's value, which is exactly like this "29.01.2022" and I send it to an ASP.NET MVC action method which expects a DateTime parameter.
On my action that parameter is converted automatically to DateTime format but keeps the correct date.
Datepicker configuration:
$(".input-daterange") {
language: 'ro',
format: 'dd.mm.yyyy',// this gives 29.01.2022
//format: 'dd.MM.yyyy',// this gives 29.Jan.2022
autoclose: true,
calendarWeeks: true,
clearbtn: true,
disableTouchKeyboard: true
}
I'm using Entity Framework 6 for database access, so my code looks something like this:
public Action SaveField(int rowId, DateTime fieldDateValue)
{
var itemToUpdate = _context.TableName.Single(i => i.id = rowId); // this is not null
itemToUpdate.StartDate = fieldDateValue;
try
{
_context.SaveChanges()
}
catch
{ ... }
}
This code works well in debug mode but when I publish the app all gets crazy, I get an error
String was not recognized as a valid DateTime
What I've tried so far (because of datepicker format: dd.mm.yyyy):
itemToUpdate.StartDate = fieldDateValue
itemToUpdate.StartDate = Convert.ToDateTime(fieldDateValue.ToString("yyyy-MM-dd HH:mm:ss")) --> this worked for a few times but the saved date in the database was from 29.01.2022 to 2022-29-01 so something like yyyy-MM-dd, but gives be error too
itemToUpdate.StartDate = DateTime.ParseExact(fieldDateValue.ToString(), "dd.mm.yyyy", CultureInfo.InvariantCulture);
itemToUpdate.StartDate = DateTime.ParseExact(fieldDateValue.ToShortDateString(), "dd.mm.yyyy", CultureInfo.InvariantCulture);
I simply cannot understand what am I doing wrong giving the fact that the published version of the app I'm running on a remote server (which might explain issues) but also on the same machine (IIS wwroot).
Can someone tell how to correctly manage the date format so there will be no more problems and differences between debug and release versions?
So, finally, what actually worked for published version of my app was this:
date format in SQL Server database (datetime not working)
made my filed in ViewModel as 'string' instead of DateTime
DateTime.ParseExact(fieldDateValue, "dd.MM.yyyy", CultureInfo.InvariantCulture)
Build -> Clean project then Publish it (just for safety, when you do a lot of publishing) -> this also solves publish failures with Visual Studio 2015 (first time fail than second get's published)
Also for failed publishing, last solution is to delete obj folder from project
For some reason DateTime.ParseExact(fieldDateValue.ToShortDateString(), "dd.MM.yyyy", CultureInfo.InvariantCulture) didn't work in release mode

Get error when I try to pass date value in URL to web api method

I create this date variable in client side:
this.latestDate = new Date(2001, 1, 1,1,1,1,1);
Here how it looks in client watch:
self.latestDate: Thu Feb 01 2001 01:01:01 GMT+0200 (Jerusalem Standard Time)
here is angularjs service that I use to asyncroniusly call my web api method:
$http.get(serviceUrl + "?date=" + self.latestDate);
And here is the web api method that I call from cilent:
[HttpGet]
public HttpResponseMessage GetByDate(DateTime date){}
But each time I call for web api method above, I get this error on cilent:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'date' of non-nullable type 'System.DateTime' for method 'System.Net.Http.HttpResponseMessage GetByDate(System.DateTime)' in 'SensorObservation.Web.SensorsDataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
Any idea why I get the error above?
First, doing this is a really bad idea:
$http.get(serviceUrl + "?date=" + self.latestDate);
A URL is a structured text format; it has formatting rules that must be followed. When you dump unstructured text into a structured format by using simple string concatenation, you are likely to be breaking some of those rules. I would recommend using the jQuery param function for this.
Second, you are serializing the date to a string using the default format, which is the one you see in the client watch. This may or may not work on the server. A better bet is to serialize using a well known format such as ISO 8601. I would recommend using the JavaScript date toISOString function for this.
Applying these changes, your API call code would look something like this:
var query = jQuery.param({ date: self.latestDate.toISOString() });
$http.get(serviceUrl + "?" + query);
Update
I ran a quick test since I was in my WebAPI code already, and you can create and use an endpoint with a DateTime parameter as long as the URL is formatted correctly.
My test endpoint looks like this:
[HttpGet]
[Route("test/datetest")]
public HttpResponseMessage DateTest(DateTime d)
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent(d.ToString(), Encoding.UTF8, "text/plain");
return response;
}
It echoes the date back as expected.

Extjs 5 model id' is not concatenating with REST URL - working in Extjs 4.2

Sorry!! may be i was not clear, I modified the question, Actual problem is that 'I am setting the id on the model and it is working fine in Extjs 4.2' and i am able to print the id from within the model object on console but this 'id' is not concatenating with REST URL like 'rest/update/user/123'
I really need your help.
In Extjs 4.2, I am posting a form data to a rest url (update using proxy in model class ), it was working fine and send the request to the server as:
rest/update/user/123
but in Extjs 5 same request is being interpreted as:
rest/update/user //without he id of the object
it does not send the id of the object in the REST CALL URL (id has value inside the object)
//here is proxy in the model
proxy: {
type: 'rest',
url: ' rest/update/user'
}
//controller
var model = Ext.create('MyApp.model.User');
model.set('id', "123"); // please see here, i am adding the Id so it is not phantom
model.set('userName', "john");
model.save();
Please help!!
Thanks.
Model seems to be phantom (new). Call model.commit() before save.

Can I customize my AngularJS application to display local times?

I am using an ASP.NET MVC / ASP.NET Web API back-end for my application. When a user updates data the time is recorded like this:
public HttpResponseMessage PutContent(int id, Content content)
{
if (id != content.ContentId)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
content.ModifiedDate = DateTime.Now;
content.ModifiedBy = User.Identity.GetUserId();
_uow.Contents.Update(content);
_uow.Commit();
return Request.CreateResponse(HttpStatusCode.OK, content);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
When the user looks at the modified time they see what I assume is the server time. Is there a way that I can allow them to see the local time that the change was made?
Note that already I do some formatting but I am not sure if there is a way that I can convert the date and have this matched up with my local users who could be in any location:
<input disabled="disabled" type="text"
value="{{modal.data.modifiedDate | date:'MM/dd/yy HH:mm'}}" />
To start with it is always better to save the dates on server in UTC. So on the server use the method DateTime.UtcNow.
And while sending the data to client, if you are not custom formatting the date, i believe the date send contains the timezone information as well. AngularJS can handle that correct using date filter. See this fiddle http://jsfiddle.net/jHSLe/1/
Assuming the date you are getting is in UTC, you can use the excellent Moment.js to easily convert it to local time as described here:
http://momentjs.com/docs/#/manipulating/local/

What ObjectMapper config / annotations required for successful JSON / JSON array exhange using Jackson 2.2

Using Jackson 2.2.2 and Apache CXF web services client and server API.
I'm finding it impossible to serialize / deserialize JSON without failure.
Java class:
MyPojo
{
..... various properties
}
JSON produced from Jackson:
{
"MyPojo":
{
..... various properties
}
}
When I send the exact same JSON back to Jackson for it to consume, it fails with:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "MyPojo" (class app.model.MyPojo), not marked as ignorable (17 known properties: ,.....
Ideally, Jackson would not wrap the MyPojo object with {"MyPojo":} because I only ever exchange MyPojo objects, so it is implied.
To that end, how can I get Jackson to produce:
{
..... various properties
}
Then, how do I get jackson to consume the same JSON without failing? i.e. what ObjectMapper configuration or annotations or combination of both do I have to use?
If this is impossible, then how do I configure / annotate to get Jackson to consume the "wrapped" JSON without failing?
ALSO,
I have the same issues when producing / consuming an array of MyPojo objects:
JSON produced from Jackson:
{
"MyPojo":
[
{
..... various properties
},
{
..... various properties
}
]
}
..when consumed fails with:
com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of app.model.MyPojo[] out of START_OBJECT token
Again, ideally (but not essential) Jackson would produce / consume:
[
{
..... various properties
},
{
..... various properties
}
]
Note, the Apache CXF WS appears to perform some magic via its #GET, #POST, etc, annotations as when used in conjuntion with a RESTful WS resource method which returns a MyPojo object, i.e. it appears that after my method returns the object, it is transformed into JSON.
To that end, I am unsure if a local or even global ObjectMapper will influence the output, so this should also be considered when answering.
Another note, I also need the same POJO to be produced and consumed in XML via JAXB.
EDIT:
I am now quite certain that TomEE/CXF is not using Jackson and that this is the cause of my issues. I'll update when I get it to work.
RESOLVED:
Further investigation revealed that whilst the JSON was being deserailized by Jackson, the default Jettison provider was not being overriden with Jackson when serializing due to misconfiguration of default JSON provider in CXF/TomEE. This resulted in a Jackson - Jettison formatting mismatch.
On stackOverflow are more than many answered questions like yours.
This is a solution:
objectMapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
You can see similar questions:
Use class name as root key for JSON Jackson serialization
Enable Jackson to not output the class name when serializing (using Spring MVC)

Resources