asp.net MVC 4 webgrid with an IF statement - asp.net

I have a column that needs to check a field of the object, when the field equals 2 then another has to multiply with -1.
The problem is I do not know the syntax to do this inside the creation of my gridview. Could someone give an example how this works?
#(invoice.dc.Equals(2)?String.Format("{0:0.00}", invoice.totv * -1): String.Format("{0:0.00}", invoice.totv))
This code sample i have to accomplish inside the creation of the gridview. So if field: dc equals 2 show invoice.totv * -1 else show invoice.totv.
This is what i have tried:
grid.Column("", "PDF", format:
(item) => if(#item.dc == 2)
{
String.Format("{0:0.00}", #item.totv * -1) ;
}
else
{
String.Format("{0:0.00}", #item.totv) ;
})

How about
grid.Column("", "PDF", (item) => String.Format("{0:0.00}", item.dc == 2 ? item.totv * -1 : item.totv));

Related

Retrieve and compare the style attribute of an element periodically using using cypress

I have a time indicator that travels over a timescale, the indicator's style attribute value keeps on changing for every x milliseconds and I need to get, store and compare that the previously captured value is greater than the latest value.
Initial value:
Latest value:
The logic is, from one point (left 10), every second it moves to the left (left -0, -1, -2, -3 ...)
I tried few ways and one of them is to capture in the same 'cy.then', but in that case, the element will not have the recent value. So far, I tried this. it fetches the value and with some help of regex, I got a 'comparable' value but how I can store/compare those values? Additionally, what is the best way if we need to compare more than 2 values?
const BTN_CONTROL_TIMEINDICATOR = '#currentTimeIndicator'
static verifyTimeLapse() {
//wip
var initialVal, nextVal
initialVal = this.getAnyValueOfAnElement(BTN_CONTROL_TIMEINDICATOR)
cy.wait(500)
nextVal = this.getAnyValueOfAnElement(BTN_CONTROL_TIMEINDICATOR)
cy.log(initialVal > nextVal)
}
static getAnyValueOfAnElement(element) {
//wip
cy.get(element)
.then(($ele) => {
const val=$ele.attr('style').replace(/[^\d.-]/g, '')
cy.log(val)
// return does not work
})
}
cy.log:
Page objects don't work very well with the Cypress command queue, here's what you might do with custom commands.
/* Get the numeric value of CSS left in px */
Cypress.Commands.add('getTimescaleValue', () => {
cy.get('#currentTimeIndicator')
.then($el => +$el[0].style.left.replace('px',''))
})
/* Get a sequence of time scale values */
Cypress.Commands.add('getTimescaleValues', ({numValues, waitBetween}) => {
const values = [];
Cypress._.times(numValues, () => { // repeat inner commands n times
cy.getTimescaleValue()
.then(value => values.push(value)) // save value
.wait(waitBetween)
})
return cy.wrap(values);
})
/* Assert a sequence of values are in descending order */
Cypress.Commands.add('valuesAreDescending', { prevSubject: true }, (values) => {
values.reduce((prev, current) => {
if (prev) { // skip first (no prev to compare)
expect(prev).to.be.gt(current) // assert pairs of values
}
return current
});
})
it('check the timeline', () => {
cy.getTimescaleValues({ numValues: 10, waitBetween: 100 })
.valuesAreDescending()
})
Log
assert
expected 63 to be above 58
assert
expected 58 to be above 48
assert
expected 48 to be above 43
assert
expected 43 to be above 33
assert
expected 33 to be above 23
assert
expected 23 to be above 18
assert
expected 18 to be above 13
assert
expected 13 to be above 3
assert
expected 3 to be above -2
Tested with
<div id="currentTimeIndicator" style="left:63px">Target</div>
<script>
const timer = setInterval(() => {
const div = document.querySelector('#currentTimeIndicator')
const left = +div.style.left.replace('px', '');
if (left < 0) {
clearInterval(timer)
return
}
const next = (left - 5) + 'px';
div.style.left = next;
}, 100)
</script>
If your app uses setInterval() for timing, you should be able to use cy.clock() and cy.tick() instead of .wait(waitBetween) to get more precise sampling and faster test execution.
I don't know where the initial value comes from. But before it changes, maybe on page load, maybe as first job on click, etc you can do something like this:
let item = document.querySelector("#currentTimeIndicator");
item.dataset.left = parseFloat(item.style.left);
console.log(item);
<div id="currentTimeIndicator" style="left:-20px"></div>

How to access final element in Handlebars.js array?

Given the following data structure:
{
"name" : "test",
"assetType" : "Home",
"value" : [
{
"value" : "999",
"date" : "10/03/2018"
},
{
"value" : "1234.56",
"date" : "10/04/2018"
}
]
}
How can I directly access the first and last element of value in Handlebars? My code is:
<td>{{value.[0].value}}</td>
<td>{{value.[value.length - 1].value}}</td>
The first statement works fine, but I cannot figure out how to access the last element. value.length inside the []'s does not return any value, but rendering value.length outside of the array works fine.
I tried using #first and #last in the array but those don't seem to work either.
As already pointed out, you can easily solve this with a template helper:
Template.myTemplate.helpers({
first (arr) {
return arr && arr[0]
},
last (arr) {
return arr && arr[arr.length - 1]
},
atIndex (arr, index) {
return arr && index >= 0 && index <= arr.length - 1 && arr[index]
}
})
You can then create a context using #with where the context object is the result of the helpers. Inside this context you can access properties using this.
Accessing values with the name value would look like the following:
<td>{{#with first value}}{{this.value}}{{/with}}</td>
<td>{{#with last value}}{{this.value}}{{/with}}</td>
<td>{{#with atIndex value 5}}{{this.value}}{{/with}}</td>

ES2015 - updating filtered items in a collection and combining updating the previous collection

So say i have a collection:
const collection = [0,3,2,4];
var r = collection.filter((item) => {
return item > 2;
}).map((item) => {
return item + 2;
});
// I could just `.map()` them back in but that seems ineffective
console.log(r); // 5,6
Is there a functional (fp) way to compose this code to update my previous collection to get the expected result (given the index of the result is important) ?
e.g. expected result: [0,5,2,6]
How about
var r = collection.map(item => item > 2 ? item + 2 : item)
instead?
I.e. .map all items but only modify the ones that match your condition.

NSInterger Max and Minimum Value

in my app I'm taking into account the clicks made ​​on a botton . The number of clicks is displayed in a label and I used this code ... I wish that the number of clicks started not from 0 but from 12 and stop automatically at 30.
How can I give these blocks in my action where I draw the NSInterger ?
Thank you all for the help
# interface FFDettagliEsami () {
    NSInteger FFVariabileNumerica_CFU_Votazione ;   
}
# end
# implementation FFDettagliEsami
   
- ( IBAction ) FFAddVotazione : (id ) sender {
    FFVariabileNumerica_CFU_Votazione + + ;
    [ FFVotazioneLabel setText : [ NSString stringWithFormat : # " % d", FFVariabileNumerica_CFU_Votazione ]] ;
}
You can initialize FFVariabileNumerica_CFU_Votazione to whichever value you want in places like viewDidLoad: or initWith... if it's a view controller.
And for stopping at 30, just add a check :
- (IBAction)FFAddVotazione:(id)sender {
if (FFVariabileNumerica_CFU_Votazione >= 30)
return;
FFVariabileNumerica_CFU_Votazione++ ;
[FFVotazioneLabel setText:[NSString stringWithFormat:#"%d", FFVariabileNumerica_CFU_Votazione]];
}
use
static NSInteger FFVariabileNumerica_CFU_Votazione = 12;
and in - ( IBAction ) FFAddVotazione : (id ) sender
add the condition to check for FFVariabileNumerica_CFU_Votazione < 30
if(FFVariabileNumerica_CFU_Votazione < 30){
FFVariabileNumerica_CFU_Votazione++;
}

How to compute a column value while editing in jqgrid

I have a supposedly common problem to solve (done easily with other grid controls I'm familiar with).
In jqgrid, i'm quite stumped.
I have a jqgrid with inline editing enabled. I would like to add some scripting so that when editing a row (or adding a new row), the value of ColumnC is automatically computed as ColumnA * ColumnB as default. The user can change the values in any column at any time. I want this value to be computed as soon as the user enters it and not wait till the data is saved.
My approach so far has been to attach a dataEvent of type "change" to ColumnA and ColumnB -
dataEvents: [
{ type: 'change', fn: function(e) {
var rowid = $("#myGrid").jqGrid('getGridParam','selrow');
var rowData = $("#myGrid").getRowData(rowid);
var cell1 = rowData['ColumnA'];
var cell2 = rowData['ColumnB'];
var newValue = cell1 * cell2;
$("#myGrid").jqGrid('setCell', rowid, 'ColumnC', newValue);
}
},
]
Obviously, cell1 & cell2 don't actually return the value but the whole cell content as already discovered by other users here How to get a jqGrid cell value. The only way to get a cell value seems to be to use a custom regex user function that strips out that value.
Apart from that, is there a better/alternate way to achieve what I need? Something as simple as jqGrid - How to calculated column to jqgrid? though obviously that won't cut it for me since it will only displaying data and user cannot update it.
Any help would be appreciated.
UPDATE: After guidance from Oleg, I was able to extend getTextFromCell to support what I need.
function getTextFromCell(cellNode) {
var cellValue;
//check for all INPUT types
if (cellNode.childNodes[0].nodeName == "INPUT") {
//special case for handling checkbox
if (cellNode.childNodes[0].type == "checkbox") {
cellValue = cellNode.childNodes[0].checked.toString();
}
else {
//catch-all for all other inputs - text/integer/amount etc
cellValue = cellNode.childNodes[0].value;
}
}
//check for dropdown list
else if (cellNode.childNodes[0].nodeName == "SELECT") {
var newCell = $("select option:selected", cellNode);
cellValue = newCell[0].value;
}
return cellValue;
}
function getCellNodeFromRow(grid,rowId,cellName) {
var i = getColumnIndexByName(grid, cellName);
var cellValue;
//find the row first
$("tbody > tr.jqgrow", grid[0]).each(function() {
//The "Id" column in my grid is at index 2...
var idcell = $("td:nth-child(2)", this);
var currRowId = getTextFromCell(idcell[0])
if (currRowId == rowId) {
cellValue = getTextFromCell($("td:nth-child(" + (i + 1) + ")", this)[0]);
return false;
}
});
return cellValue;
}
The code in getCellNodeFromRow is not the most efficient. There is a .each() loop for find the matching row node. I can see this being slow when the grid has thousands of rows. Is there a better/more efficient way to find the row node? I have the row Id already.
Look at the demo from the answer. It uses cell editing, but the same technique work for inline editing too. Just click on any cell in the "Amount" column and modify the numerical value. You will see that the value in the "Total" row (footer) will be changed dynamically during the cell is still in the editing mode. I think it is what you need.
you can achieve this using onCellSelect event of jqgrid as below
//global section
var columnA;
var ColumnB;
var ColumnC;
var currentRow;
//
onCellSelect: function (rowid, iCol, aData) {
currentRow = rowid;
var ColumnA = $('#grid').getCell(rowid, 'MyCol');
var ColumnB = $('#grid').getCell(rowid, 'MyCol');
$("#grid").jqGrid('editRow', rowid, true );
$("#myMenu").hide();
if (rowid && rowid !== lastsel) {
if (lastsel) jQuery('#grid').jqGrid('restoreRow', lastsel);
$("#grid").jqGrid('editRow', rowid, true );
lastsel = rowid;
}
else if (rowid && rowid === lastsel)
{ $("#grid").jqGrid('editRow', rowid, true ); }
//if it is in editable mode
// when you view the html using firebug it will be like the cell id change to
//format like "rowid_ColumnName"
$('#' + currentRow + '_ColumnC').val(ColumnA*ColumnB);
// or you can use achieve this using following jqgrid method at
//appropriate place
$("#myGrid").jqGrid('setCell', rowid, 'ColumnC', ColumnA*ColumnB);
}

Resources