About saving data into grails databse - grails

This my project code I want to save my data into database.
def save(){
List<Employee> list = Employee.findAllById(session.getAttribute("empId"))
Milestone milestone = new Milestone()
milestone.setMilestone_Date(params.milestone_Date)
milestone.setMilestone_Name(params.milestone_Name)
milestone.setMilestone_Description(params.milestone_Description)
milestone.save()
EmployeeMilestone employeeMilestone=new EmployeeMilestone()
Employee employee = list.get(0)
employeeMilestone.setEmployee(employee)
employeeMilestone.setMilestone(milestone)
employeeMilestone.save()
[employeeMilestones:employeeMilestone]
}
I am getting this error
Error 500: Internal Server Error URI /ProjectTrackerMain/milestone/save Class java.lang.IndexOutOfBoundsException Message Index: 0, Size: 0

You didn't actually ask a question, so this may be a bit vague!
An IndexOutOfBoundsException happens when you try to access something from a collection in a location where there is no "something". For example, maybe you asked for the tenth element in a list, but there are only two. In your case, you're asking for the zeroth (in plain English, "First") element on this line of code:
Employee employee = list.get(0)
and presumably the list is empty. Your error message says "Size: 0". You can't get the first element from a list that has zero elements in it, so that's an index out of bounds exception.
Why is your list 0? That's a different question. You might try printing out
session.getAttribute("empId")
to see if your employee ID is what you expected. You might also look at the data in your database to see if you actually managed to save an employee! One way or another, you're not getting the data you expected, and then you're trying to use it.
In general, using a debugger to look at your elements, or just using "println" along the way to look at values is helpful in debugging problems like this. That way, you'll find out on line 1 that your list of Employees is not what you expected, instead of several lines later when you try to use it!

Related

Microsoft Graph API remove Check List Item

I have a plannerTask and in its Details it has a CheckList. I use it to programatically insert CheckListItems in it, and it all works like a charm when inserting or retrieving the tasks.
My problem arrives when I am going to insert a new CheckListItem and the CheckList already has 20 items. It returns a MaximumChecklistItemsOnTask (because it is forbidden to insert more than 20 items in a check list).
Solution could be to remove the oldest item, but I am not able to do it. I have tried this:
var elementToRemove = oldDetails.Checklist.Where(c => c.Value.IsChecked).OrderBy(c => c.Value.LastModifiedDateTime).First();
oldDetails.Checklist = oldDetails.Checklist.Where(c => c.Value.LastModifiedDateTime <> elementToRemove.Value.LastModifiedDateTime);
But it throws a casting error in the second line:
Unable to cast object of type
'WhereEnumerableIterator1[System.Collections.Generic.KeyValuePair2[System.String,Microsoft.Graph.PlannerChecklistItem]]'
to type 'Microsoft.Graph.PlannerChecklistItems'.
Which is the right way to remove the oldest element from the ChecklistItem?
UPDATE:
In first place I retrieve a plannerTask from the server. Then I get the details from this plannerTask. So oldDetails is a plannertaskdetails object (https://learn.microsoft.com/en-us/graph/api/resources/plannertaskdetails?view=graph-rest-1.0). Inside the plannertaskdetails object (oldDetails), I have the plannerchecklistitems object (oldDetails.Checklist): https://learn.microsoft.com/en-us/graph/api/resources/plannerchecklistitems?view=graph-rest-1.0.
If plannerchecklistitems were just a List, it would be as easy as list.Remove(item), but it is not a normal list, and that is why I am not able to remove the item.
UPDATE 2:
I have found this way to remove the item from oldDetails:
oldDetails.Checklist.AdditionalData.Remove(elementToRemove.Key)
But, the the way I send the changes to the server is this:
await graphClient.Planner.Tasks(plannerTask.Id).Details.Request().Header("If-Match", oldDetails.GetEtag).UpdateAsync(newDetails)
As it is a PATCH request (not a PUT one), I only have in newDetails the records that have changed, it is, the new records. How could I specify there that a record has been deleted from the list? Sorry if my English is not good enough to express myself properly, but what I mean is that newDetails is not the full list, it only contains the records that must be added and I do not know how to specify in that request that one record must be deleted.

How to find the distinct error messages of model state validation failure in asp.net mvc

I want to filter the Error Messages that gets populated as part of data annotation modelstate validation failure. As in if an array of objects comes as a part of class, and the validation fails for more than one object, I do not want the same message to be added again and again. Instead, I want to find the distinct error messages
string ValidationFailure= string.Join(";", actionContext.ModelState.Values.Distinct().Select(x.ErrorMessage));
But not able to get the required output.
It looks like your attempt is close, but you’re using Distinct on something that’s already unique (Values). Instead, try the following variation:
string ValidationFailure = string.Join(";", actionContext.ModelState.Values.Select(x => x.ErrorMessage).Distinct());
This ensures that you get a distinct list of ErrorMessages.

PagedResultList .size() and .getTotalCount() return different values in grails gorm

I have the following code
PagedResultList res = myService.getPage(paginateParams, ...)
println res.size() // returns 2
println res.getTotalCount() // returns 1
getPage looks like:
def criteria = MyDomain.createCriteria()
criteria.list(max: paginateParams.max, offset: paginateParams.offset) { // max is 10, offset is 0, sortBy is updatedAt and sortOrder is desc
eq('org', org)
order(paginateParams.sortBy, paginateParams.sortOrder)
}
why do the two method return different values? The documentation doesn't explain the difference, but does mention that getTotalCount is for number of records
currently on grails 2.4.5
edits:
println on res prints out:
res: [
com.<hidden>.MyDomain: 41679f98-a7c5-4193-bba8-601725007c1a,
com.<hidden>.MyDomain: 41679f98-a7c5-4193-bba8-601725007c1a]
Yes, res has a SINGLE object twice - that's the bug I'm trying to fix. How do I know that? I have an primary key on MyDomain's ID, and when I inspect the database, it's also showing one record for this particular org (see my criteria)
edit 2: I found this comment (http://docs.grails.org/2.4.5/ref/Domain%20Classes/createCriteria.html)
listDistinct If subqueries or associations are used, one may end up
with the same row multiple times in the result set. In Hibernate one
would do a "CriteriaSpecification.DISTINCT_ROOT_ENTITY". In Grails one
can do it by just using this method.
Which, if I understand correctly, is their way of saying "list" method doesn't work in this scenario, use listDistinct instead but then they go on to warn:
The listDistinct() method does not work well with the pagination
options maxResult and firstResult. If you need distinct results with
pagination, we currently recommend that you use HQL. You can find out
more information from this blog post.
However, the blog post is a dead link.
Related: GORM createCriteria and list do not return the same results : what can I do?
Not related to actual problem after question edited but this quote seems useful
Generally PagedResultList .size() perform size() on resultList property (in-memory object represent database record), while .getTotalCount() do count query against database. If this two value didn't match your list may contain duplicate.
After viewing related issues (GORM createCriteria and list do not return the same results : what can I do?) I determined that there were several approaches:
Use grails projection groupBy('id') - doesn't work b/c i need the entire object
USe HSQL - Domain.executeQuery - actually this didn't work for my scenario very well because this returns a list, whereas criteria.list returns a PagedResultList from which I previously got totalCount. This solution had me learning HSQL and also made me break up my existing logic into two components - one that returned PagedResultList and one that didn't
Simply keep a set of IDs as I process my PagedResultList and make sure that I didn't have any duplicates.
I ended up going with option 3 because it was quick, didn't require me to learn a new language (HSQL) and I felt that I could easily write the code to do it and I'm not limited by the CPU to do such a unique ID check.

CoreData (MagicalRecord) returning the wrong values

To save the primary animal in a zoo I do this:
-(void)makePrimary:(Animal*)animal
Zoo *currentZoo = [Zoo findFirstByAttribute:#"zooId" withValue:self.currentZooId];
currentZoo.primaryAnimalId = animal.animalId;
[[NSManagedObjectContext defaultContext] saveToPersistentStoreAndWait];
DLog(#"primaryAnimalId: %d", currentZoo.primaryAnimalId.intValue); //logs "3"
}
After doing this, the primaryAnimalId for currentZoo logs as 3. I am using the Firefox SQLite Manager to verify this. ZPRIMARYANIMALID is 3 there as well.
Now, I navigate to a different section of the app, where I need to display the primary animal. So I do this:
-(Animal*)getPrimaryAnimalForCurrentZoo
{
Zoo *currentZoo = [Zoo findFirstByAttribute:#"zooId" withValue:self.currentZooId];
DLog(#"primaryAnimalId: %d", currentZoo.primaryAnimalId.intValue); //logs 2
Animal *primaryAnimal = [Animal MR_findFirstByAttribute:#"animalId" withValue:currentZoo.primaryAnimalId];
return primaryAnimal;
}
Much to my chagrin, I get "2" for the primaryAnimalId, and thus the wrong animal is returned. "2" is the previous value of the animal before I change it via makePrimary:. currentZooId is 0 in both methods.
What I don't understand is how I can get the wrong value back from Core Data when I can clearly see the correct value currently in the database (in SQLite Manager). How is this possible and how do I fix it?
Did you update self.currentZooId to reflect your changes?
Update:
So, you're asking for the first record in your data set here. The thing is,you're not specifying an order. That is, findFirst just asks the data store for all, and then just returns the first in the list (have a look at the code for more specifics). Since that list can be in any order, you're going to get whatever the data store gives you in at particular instance. What you want to do is add a sort parameter to findFirst to make sure you always get the item you expect. Look at the headers to find the correct firstFirst method with a sort parameter.

Why does my LINQ to SQL query fail the first time ("Row Not Found or Changed") and succeed the second time?

I'm using LINQ to SQL in ASP.NET MVC. I wrote some new code to update Orders in our system, and as far as I can tell it's exactly like a hundred other similar pieces of code I've written (grab the object, update some fields, submit changes).
This time though, when I try to run the update, I get a "Row not found or changed" LINQ exception on this call stack:
System.Data.Linq.dll!System.Data.Linq.DataContext.SubmitChanges(System.Data.Linq.ConflictMode failureMode) + 0x14c bytes
System.Data.Linq.dll!System.Data.Linq.DataContext.SubmitChanges() + 0x14 bytes
If I just refresh the page after the exception, it just works with no issues.
How can I get it to work correctly the first time?
I've seen answers on the net relating to DateTime precision and Update checks, but nothing about the submission simply working the second time, not the first.
My code is basically like this:
Order order = myDataContext.Orders.SingleOrDefault(order.OrderID == orderID);
order.Field1 = true;
order.Boolean2 = true;
order.Double1 = 300.0;
myDataContext.SubmitChanges();
The issue turned out to be that I was changing a related table in between fetching the Order, editing, and saving it.
When the related table was changed, the Order table was indirectly changed because of the parent-child relationship. That caused the change checking validation to fail.
All I needed to do is pull all the related code (fetch, change, save) into one tight block, with no other code in-between. I'm not having any problems now.
Your code looks fine.
There must be something else in myDataContext that is causing the problem.
Where is myDataContext defined? I am guessing that there is some code in a if is postback block, or something similar, to cause the code that runs to take a different path.
Are you creating a new datacontext when rebinding (after calling SubmitChanges)?
You should never reuse a datacontext for selecting, after performing insert/update/delete actions with it.

Resources