smartgwt listgrid.getRecordList() not give me updated data - smartgwt

I'm on my smartgwt project having issue in listgrid.
my listgrid having data come from server side, and user allow to edit any record from that grid.
searchGrid.setAutoFetchData(true);
searchGrid.setDataSource(searchDS);
searchGrid.setAlwaysShowEditors(true);
When I try to edit any cell in grid and try to loop through all record from grid, it doesn't give me latest updated cell which I edited.
I use below code for fetching all records from my listgrid.
private String getGridDetails() {
RecordList records = searchGrid.getRecordList();
Document doc = XMLParser.createDocument();
Element rootElement = doc.createElement("ROOT");
doc.appendChild(rootElement);
for (int i = 0; i < records.getLength(); i++) {
Record rec = records.get(i);
Element row = doc.createElement("ROW");
for (String str : rec.getAttributes()) {
String propertyVal = rec.getAttributeAsString(str);
if (propertyVal != null
&& propertyVal.equalsIgnoreCase("") != true) {
Element columnElement = doc
.createElement(str.toUpperCase());
columnElement.appendChild(doc.createTextNode(propertyVal));
row.appendChild(columnElement);
}
}
rootElement.appendChild(row);
}
return doc.toString();
}

If you want to get every edited and unedited record, you may loop one by one:
public Record[] getData(ListGrid grid)
{
RecordList data = new RecordList();
for (int i = 0; i < grid.getTotalRows(); i++)
data.add(grid.getEditedRecord(i));
return data.duplicate();
}
But if you just want to retrieve the edited records, try the following snippet:
public static Record[] dameDatosLocalesEditedRows(ListGrid grid)
{
RecordList data = new RecordList();
int[] edited = grid.getAllEditRows();
for (int i = 0; i < edited.length; i++)
data.add(grid.getEditedRecord(edited[i]));
return data.duplicate();
}

Related

How to check if key exists or not using json-path library?

I'm using Json Path library and I want to check if key exists or not and based on that I'll do some actions. Hence I wrote following code -
for(int i = 0; i < keyValues.length; i++) {
List<String> invalidKeys = new ArrayList<>();
if(Objects.isNull(jsonPath.getString(key))) {
invalidKeys.add(key);
continue;
}else {
value = keyValues[i].split("=")[1];
}
}
My intention to get keys which are not present in json but with this code, if key has value as null that is also treated non-existing key. Is there any way I can modify above code to get only keys which are not present in json?
You can use your jsonPath to build a JSONObject:
JSONObject jsonObject = new JSONObject(jsonPath.prettify());
Then you can use this jsonObject to check if the key exists:
for(int i = 0; i < keyValues.length; i++) {
List<String> invalidKeys = new ArrayList<>();
if(!jsonObject.has(key)) {
invalidKeys.add(key);
continue;
}else {
value = keyValues[i].split("=")[1];
}
}

am working on updating a single attribute in the User Model which is the balance attribute,

how I can update a single value for an already existing row in the db by only having a parameters that I want to add it to this attribute
here is my code for a trivial way but didnt work
public bool BuyBook(int BookId, int UserId, int BookPrice){
using (var ctx = new OnlineBooksEntities())
{
User updatedCustomer = (from c in ctx.Users
where c.UserId == UserId
select c).FirstOrDefault();
updatedCustomer.Balance = BookPrice;
ctx.SaveChanges();
}
this.DeleteBook(BookId);
return true;
}
Add an sql query to the method solves the update aim
public bool BuyBook(int BookId, int UserId, int BookPrice)
{
try
{
using (var ctx = new OnlineBooksEntities())
{
User user = ctx.Users.Where(x => x.UserId == UserId).FirstOrDefault();
BookPrice = (int)user.Balance + BookPrice;
int noOfRowUpdated =
ctx.Database.ExecuteSqlCommand("Update Users set Balance = "+BookPrice+ " where UserId ="+UserId);
}
Updating basically means changing an existing row's value. Since you mentioned EF, you can do this by retrieving the object, changing its value, and saving it back. Thus you can do something like this:
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookPrice == bookPrice);
if (result != null)
{
result.SomeValue = "Your new value here";
db.SaveChanges();
}
}

Programmatically create polymer Elements in Dart

Need add polymer paper-dropdown-menu in DOM.
I try this code:
makePapersElements() {
List _items = new List();
for (var i = 0; i < 13; i++) {
PaperItem item = new dom.Element.tag('paper-item');
item.text = i;
_items.add(item);
}
return _items;
}
And add nodes in PaperListbox then in PaperDropdownMenu:
List<PaperItem> items = makePapersElements();
var element = new dom.Element.tag('div');
PaperDropdownMenu dropMenu = new PaperDropdownMenu();
PaperListbox listBox = new dom.Element.tag('paper-listbox');
dropMenu.append(listBox);
listBox.nodes.addAll(items);
element.nodes.add(dropMenu);
$['example'].nodes.add(element);
It's not work currently:
How it can be done?
Update: Added Gist
https://gist.github.com/Rasarts/a0b6710e234ec8b4aa37f90e4cd14839
You can create PaperDropDownMenu and Paperlistbox with new Xxx(), no need for new dom.Element.tag('Xxx') because these elements contain a constructor for convenience where this is done already
https://github.com/dart-lang/polymer_elements/blob/7912e0e6641155505007a89140f11c25db14e3f8/lib/paper_listbox.dart#L61
https://github.com/dart-lang/polymer_elements/blob/7912e0e6641155505007a89140f11c25db14e3f8/lib/paper_dropdown_menu.dart#L69
I guess the issue is because you don't use the Polymer DOM API. See also https://github.com/dart-lang/polymer-dart/wiki/local-dom. Only when you enable full shadow DOM (with full polyfills whithout native support) then you don't need to use this API.
makePapersElements() {
List _items = new List();
for (var i = 0; i < 13; i++) {
PaperItem item = new PaperItem();
item.text = i;
_items.add(item);
}
return _items;
}
List<PaperItem> items = makePapersElements();
var element = new dom.Element.tag('div');
PaperDropdownMenu dropMenu = new PaperDropdownMenu();
PaperListbox listBox = new PaperListbox();
Polymer.dom(dropMenu).append(listBox);
// not sure this will work
Polymer.dom(listBox).childNodes.addAll(items);
// alternatively
var listboxDom = Polymer.dom(listBox);
for(var item in items) {
listboxDom.append(item);
}
Polymer.dom(this)appen(dropMenu);
// ro Polymer.dom(this.root)appen(dropMenu);
Polymer.dom($['example']).append(element);
Yes, I do it wrong. Example helped. Thanks.
https://github.com/bwu-dart-playground/polymer1/blob/12a4bca9c5c5b21c690af0bd4451407b64899a6e/so36689312_programmatically_create_paper_elements/web/pdm_element.dart#L36-L36

How to check a kendo ui treeview child nodes based upon a kendo ui grid data

On an asp.net mvc page, I have a Kendo UI grid and a Kendo UI treeview. The treeview has checkboxes and the treeview has two tier data. Then once the grid is populated, I want to loop through the rows, find the corresponding id, then loop through the treeview and find the node with the same id and make it checked. The following is my code:
Grid code:
dataBound: function () {
var rows = this.tbody.children();
var dataItems = this.dataSource.view();
for (var i = 0; i < dataItems.length; i++) {
kendo.bind(rows[i], dataItems[i]);
bindCheckboxToId(dataItems[i].ID);
}
}
The javascript function to set the treeview node to be checked:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
var children = myNodes[i].children.view();
alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
The problem is that, the children.length always comes as 0, although each parent node has two child nodes.
Thanks
We have to force the tree view to load the child nodes. The following is the updated code:
function bindCheckboxToId(id) {
var treeView = $("#treeview").data("kendoTreeView");
var myNodes = treeView.dataSource.view();
for (var i = 0; i < myNodes.length; i++) {
myNodes[i].load();
var children = myNodes[i].children.view();
//alert(children.length);
if (children) {
for (var j = 0; j < children.length; j++) {
if (children[j].id === id) {
children[j].set("checked", true);
}
}
}
}
}

Error 'cannot be initialized in a query result' when trying to get data with Linq

ISSUE:
I have an asp.net mvc 3 app. I'm using EF 4.1 and trying out jqGrid. I'm trying to get data for my jqGrid using the GridData method below. I get the following error on the group of data starting at 'var jsonData = new...'. Any ideas?
ERROR:
{"The array type 'System.String[]' cannot be initialized in a query result.
Consider using 'System.Collections.Generic.List`1[System.String]' instead."}
GridData Method:
public JsonResult GridData(string sidx, string sord, int page, int rows)
{
var result = from a in db.t_harvest_statistics_elk
where a.year == "2008" && a.unit_number == 1
orderby a.id
select a;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = result.Count(); // context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = result.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
};
return Json(jsonData);
}
HERE IS AN EXAMPLE THAT DOES WORK
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
var context = new HaackOverflowDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = context.Questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.Id,
cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title }
}).ToArray()
};
return Json(jsonData);
}
The easiest way to fix the code will be to use something like the following
// to be able to use ToString() below which is NOT exist in the LINQ to Entity
// so we should get the data from the database and save the result locally before
// the next step. One can use .ToList() or to .AsEnumerable(), but one should
// choose only the fields of questions which we will need later
var queryDetails = (from item in questions
select new { item.id, item.total_rec_days, item.year }).ToList();
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new [] {
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Your current code contain some small problems like the usage of i = question.id instead of id = question.id.
I would recommend you to read the answer and download the demo from the answer which contains more recent and extended code.
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new IComparable[]{
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Can you try modifying your code like :
rows = (
from question in questions.AsEnumerable() //AsEnumerable() is added to switch to LINQ to Entites to eager load the data.
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
Because the MSDN says that : "You cannot call this function directly. This function can only appear within a LINQ to Entities query." (Though the next line is little confusing in documentation)
You can't use custom functions inside direct queries to you database. Instead you can do something like this:
rows = questions.AsEnumerable()
//or select just that you want questions.Select(q=> new {g.Id, q.Votes,q.Title})
.Select(p=> new {
id = p.Id,
cell = new string[] { SqlFunctions.StringConvert((double)p.id), SqlFunctions.StringConvert((double)p.total_rec_days), p.year }
}).ToArray()
That should work.

Resources