asp.net mvc: SQLDateTimeOverflow problem with Entity Framework - asp.net-mvc

I'm trying to update an object, and getting:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
There are two fields in the object that are DateTime objects, and they're set with:
obj.created_date = DateTime.Now;
obj.modified_date = DateTime.Now;
Except that everything looks reasonable when I view the object:
>? obj.created_date
{1/13/2010 4:02:47 PM}
Date: {1/13/2010 12:00:00 AM}
Day: 13
DayOfWeek: Wednesday
DayOfYear: 13
Hour: 16
Kind: Unspecified
Millisecond: 817
Minute: 2
Month: 1
Second: 47
Ticks: 633989953678170000
TimeOfDay: {16:02:47.8170000}
Year: 2010
>? obj.modified_date
{1/19/2010 12:20:50 PM}
Date: {1/19/2010 12:00:00 AM}
Day: 19
DayOfWeek: Tuesday
DayOfYear: 19
Hour: 12
Kind: Local
Millisecond: 333
Minute: 20
Month: 1
Second: 50
Ticks: 633995004503331818
TimeOfDay: {12:20:50.3331818}
Year: 2010
Any idea what's going on? Even reading the fields from the database, then trying to save them back without changes, causes the error. Other classes have no problems, and I can't see any differences that would account for this error.
I've added
<globalization culture="en-US" />
to my web.config, with no changes.
These problems are on my local dev

OK, here's what was happening. marc_s had the right idea.
There's was binder handling the updates:
TryUpdateModel(editItem, new string[] { "LookupTable", "TextField1", "TextField2" });
I removed the "LookupTable" from the call to TryUpdateModel, and instead handle the value in the binder with:
var fkid = Convert.ToInt32(controllerContext.HttpContext.Request.Form["LookupTable.ID"]);
EntityKey ek = new EntityKey("entities.LookupTable", "ID", fkid);
obj.LookupTableReference.EntityKey = ek;
Apparently, the EF was trying to update the LookupTable value for some reason.

Related

Grails accessing data where dates equal in database first mode

I'm returning to Grails after a year hiatus while I worked for .Net shop. I had always programmed Grails in code first mode. My newest project is database first, and I thought I was ready. I have a simple calendar table in my MySql database:
commit;CREATE TABLE `Calendar` (
`ID` bigint(20) NOT NULL,
`Title` varchar(200) NOT NULL,
`EventDate` date NOT NULL,
`StartTime` time DEFAULT NULL,
`EndTime` time DEFAULT NULL,
`Location` varchar(500) NOT NULL,
`version` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
With the following data in the table:
insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('Summer 2016 Garage Sale', '2016-07-23', '7:00 ', '19:00', 'Lodge', 0);
insert into Calendar (Title, EventDate, StartTime, EndTime, Location, version)
values ('August 2016 Member Meeting', '2016-08-03', '19:00', '20:00', 'Lodge', 0);
commit;
My calendar class in Grails looks like:
package plaquemineelks
import java.sql.Time
import grails.validation.Validateable
#Validateable
class Calendar {
Long id
Integer version
String title
Date eventDate
Time startTime
Time endTime
String location
static constraints = {
title (blank: false)
eventDate (blank: false)
location (blank: false)
}
static mapping = {
table "Calendar"
id column: "ID"
version column: "version"
eventDate column: "EventDate"
startTime column: "StartTime"
endTime column: "EndTime"
location column: "Location"
}
}
My controller looks like:
package plaquemineelks
class CalendarController {
def index() { }
def getByDate(String EventDate) {
def Date newDate = Date.parse("mm/dd/yyyy", EventDate)
def results = Calendar.findAllByEventDate(newDate)
render(contentType: 'text/json') {[
'results': results,
'status': results ? "OK" : "Nothing present"
]}
}
}
When I run the app and open the URI
http://localhost:8080/PlaquemineElks/Calendar/getByDate?EventDate=07/23/2016
My Json looks like:
{"results":[],"status":"Nothing present"}
I have tried a variety of formats, etc. for the date, keeping it groovy. I'm sure I'm missing something simple.
Thanks for any assistance.
You are inserting data to your table using sql query which means by default the StartDate contains date only and 00:00:00 for timestamp. Otherwise it will consider the timezone also if you insert into it using GORM.
First thing that you need to do is set the time zone to UTC for your application. In Bootstrap.grooy:
TimeZone.setDefault(TimeZone.getTimeZone('UTC'))
Secondly the format mm/dd/yyyy that you are using to parse the date is wrong, it should be: MM/dd/yyyy.
println Date.parse("mm/dd/yyyy", "07/23/2016")
Sat Jan 23 00:07:00 UTC 2016 //wrong
println Date.parse("MM/dd/yyyy", "07/23/2016")
Sat Jul 23 00:00:00 UTC 2016 //correct

How to sort by multiple fields in Grails?

I have a list that need to be sorted by 3 different fields. If it were a query I could do something like:
and {
invoiceTicketDetail {
order('date', 'asc')
order('xrefCode', 'asc')
}
order('lineType')
}
But I already have the list like the following:
List<InvoiceDetail> invoiceDetailList = invoiceHeader.invoiceDetails.findAll {it.deleted==Boolean.FALSE && it.amount!=0} as List
How can I order to get the same result from the first one? The thing is we have two different ways to display the information. One to print on screen and one to generate a report. Both of them must show the information in the same sort.
You can do like this in your criteria:
{
order('date,xrefCode,lineType','asc')
}
or write query:
Clazz.find("from Clazz order by date,xrefCode,lineType asc")
Clazz is your domain
You can sort by multiple conditions (fields, properties, etc) by...
Comparing the first property
If the first property comparison results in 0 (which means they're equal) continue to the next property. Otherwise, consider the two items sorted.
Here's a closure that can be curry'ed with a list of property names and then passed to Iterable.sort(boolean, Closure) or Iterable.toSorted(Closure).
def sortByProperties = { List propertyNames, Object a, Object b ->
propertyNames
.collect { a[it] <=> b[it] }
.find { it != 0 }
}
Example
Here's how to use the closure.
def date1 = new Date() + 3
def date2 = new Date() - 2
def list = [
[date: date1, xrefCode: 2, lineType: 'b'],
[date: date2, xrefCode: 2, lineType: 'c'],
[date: date2, xrefCode: 1, lineType: 'c'],
[date: date1, xrefCode: 2, lineType: 'a']
]
def sortByProperties = { List propertyNames, Object a, Object b ->
propertyNames
.collect { a[it] <=> b[it] }
.find { it != 0 }
}
// This form requires Groovy >= 2.4
def sortedList = list.toSorted(sortByProperties.curry(['date', 'xrefCode', 'lineType']))
// An alternative.
def sortedList = list.sort(false, sortByProperties.curry(['date', 'xrefCode', 'lineType']))
The output looks like this.
[
[date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:1, lineType:c],
[date:Tue Oct 06 20:13:13 EDT 2015, xrefCode:2, lineType:c],
[date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:a],
[date:Sun Oct 11 20:13:13 EDT 2015, xrefCode:2, lineType:b]
]
Well,
What I've done to solve this problem:
Created my own comparator and when I got the list I called something like:
Collections.sort(list, new MyComparator());
Before displaying in the screen and before generating the report.
That solved my problem.

How to Convert .NET DateTime to JSON?

createdBy: "f201b814-34c2-4948-9ab2-36a2293d7098"
eventID: 5
forumDescription: "Android Forum 01 Description"
forumID: 1
forumStatus: 3
forumTitle: "Android Forum 01"
lastModifiedDateTime: "/Date(1413427128000+0530)/"
version: 3
}
1: {
createdBy: "f201b814-34c2-4948-9ab2-36a2293d7098"
eventID: 5
forumDescription: "Android sdasdasd 02"
forumID: 2
forumStatus: 3
forumTitle: "Android Forum 02"
lastModifiedDateTime: "/Date(1413427135000+0530)/"
version: 3
Create Unix timestamp and then use that. Unix timestamp is count of millisecond from 1/1/1970.
For creating timestamp in C# use this:
public string ToUnixEpoch(DateTime dateTime)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dateTime.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds.ToString("#");
}
For more info see this. Hope this helps... :)

Edit Data Table Value adds extra row

<p:column headerText="Cancel" width="60">
<p:commandLink actionListener="#{userLeaveBean.cancelForLeave}" title="Cancel Request" process="#this" update="leaveDataTable" disabled="false">
<h:graphicImage url="resources/images/cancel.gif"/>
<f:attribute name="userId" value="#{employee.name}"/>
<f:attribute name="leaveId" value="#{leaveDetails.strLeaveId}"/>
</p:commandLink></p:column>
Hi I have written this code to modify a row value of a data table. The method that invoked named 'cancelForLeave' modifies the detail of the row value of the data table.The method is as follows:
public void cancelForLeave(ActionEvent actionEvent){
String userId = (String)actionEvent.getComponent().getAttributes().get("userId");
String leaveId = (String)actionEvent.getComponent().getAttributes().get("leaveId");
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
ConnectLdap connectLdap = new ConnectLdap();
UserTotalLeaveInfoBean userTotalLeaveInfoBean = connectLdap.getUserLeaveBean(""+currentYear, userId);
if(userTotalLeaveInfoBean != null){
UserGeneralLeaveDetailsBean[] userGeneralLeaveDetailsBean = userTotalLeaveInfoBean.getArrUserGeneralLeaveDetailsBean();
if(userGeneralLeaveDetailsBean != null){
for(int i=0;i<userGeneralLeaveDetailsBean.length;i++){
String beanLeaveId = userGeneralLeaveDetailsBean[i].getStrLeaveId();
if(leaveId.trim().equalsIgnoreCase(beanLeaveId)){
if(userGeneralLeaveDetailsBean[i].getStrLeaveStatus().trim().equalsIgnoreCase(LeaveStatus.LVST_APPLIED)){
userGeneralLeaveDetailsBean[i].setStrLeaveStatus(LeaveStatus.LVST_CANCELED);
}if(userGeneralLeaveDetailsBean[i].getStrLeaveStatus().trim().equalsIgnoreCase(LeaveStatus.LVST_APPROVED)){
userGeneralLeaveDetailsBean[i].setStrLeaveStatus(LeaveStatus.LVST_CANCELREQ);
}
userTotalLeaveInfoBean.setArrUserGeneralLeaveDetailsBean(userGeneralLeaveDetailsBean);
connectLdap.addAppliedLeaveInLdap(userTotalLeaveInfoBean, ""+currentYear, userId);
leaveDetails.add(userGeneralLeaveDetailsBean[i]);
}
}
}
}
}
private List<UserGeneralLeaveDetailsBean> leaveDetails;
//Getter and Setter
Now the problem is that, When I click on the image button it modifies the value for the row, but adds an extra row in the data table with the modified value. But when I Logout and then Again login,it shows there is no extra row, and the row I attempted to modify shows nicesly with the modified value.
what should be done to prevent the extra row addition at run time, while attempting for the value change of the data table row?Please Help!!
I get the following Log Details: If I put a Log in the page:
Monday, June 03, 2013 3:59:55 PM : Initiating ajax request.
Monday, June 03, 2013 3:59:55 PM : Form to post applyLeaveForm.
Monday, June 03, 2013 3:59:55 PM : URL to post /DemoApplication/applyLeave.xhtml.
Monday, June 03, 2013 3:59:55 PM : Post Data:javax.faces.partial.ajax=true&javax.faces.source=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&javax.faces.partial.execute=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&javax.faces.partial.render=applyLeaveForm%3AleaveDataTable&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90=applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt90&applyLeaveForm=applyLeaveForm&applyLeaveForm%3AfromDate_input=&applyLeaveForm%3AtoDate_input=&applyLeaveForm%3Aj_idt59=morning&applyLeaveForm%3Aj_idt60=endofday&applyLeaveForm%3AleaveDataTable%3A0%3AeditFrom_input=03-Jun-2013&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt68=morning&applyLeaveForm%3AleaveDataTable%3A0%3AeditTo_input=04-Jun-2013&applyLeaveForm%3AleaveDataTable%3A0%3Aj_idt72=endofday&javax.faces.ViewState=-3803632482959899224%3A-5634910090194656061
Monday, June 03, 2013 3:59:55 PM : Response received succesfully.
Monday, June 03, 2013 3:59:56 PM : DOM is updated.
Monday, June 03, 2013 3:59:56 PM : Response completed.
You don't need to add the modified item back to your list :
leaveDetails.add(userGeneralLeaveDetailsBean[i]);
You must remove this line and it should fix your problem. You are updating your source the line just before, and the add only apply in the current view, that's why refreshing get the right data.
Also your bean must be at least in #ViewScoped or #SessionScoped.

inputText and convertDateTime error

I have an h:inputText field which I use to enter a date. I am using the f:convertDateTime but I get errors.
Here is the situation:
<h:inputText value="#{listModel.creationDate}" valueChangeListener="#{listController.filterFieldChanged}">
<f:convertDateTime type="date" pattern="yyyy-MM-dd"/>
</h:inputText>
If I enter "2011-11-23" I get the following error:
"...[exec] sourceId=j_idt3[severity=(ERROR 2), summary=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. ), detail=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. )]|#]" (besides, where does 01:00:00 come from??)
If I remove the type="date" and leave only pattern="yyyy-MM-dd" and enter the same date, I get the same error.
If I remove the pattern and leave only type="date" and enter the same date, I get the following error:
"[exec] sourceId=searchForm:j_idt72[severity=(ERROR 2), summary=(searchForm:j_idt72: '2011-11-23' could not be understood as a date.), detail=(searchForm:j_idt72: '2011-11-23' could not be understood as a date. Example: 23.11.2011 )]|#]"
I am a little confused. If I define the pattern yyyy-MM-dd why "2011-11-23" isn't accepted?
Info added:
value="#{listModel.creationDate}"
public Date getCreationDate()
{
return creationDate;
}
This is the getter for creationDate in the class ListModel. (it is a java.Util.Date)
valueChangeListener="#{listController.filterFieldChanged}"
public void filterFieldChanged( ValueChangeEvent event )
{
// Note: value change events are handled in the PROCESS_VALIDATIONS
// phase by default. The problem is that the model values are not
// updated until later, so any changes we make here would normally be
// overwritten.
// By requeueing the event and targeting it to the UPDATE_MODEL_VALUES
// phase we can make the model changes without them being overwritten.
if ( event.getPhaseId().equals( PhaseId.ANY_PHASE ) )
{
event.setPhaseId( PhaseId.UPDATE_MODEL_VALUES );
event.queue();
}
else
{
// reset the paging any time a filter field was changed
listModel.setFirstResult( 0 );
}
}
I hope this is useful...

Resources