Advanced query range - x++

How to make a query in Ax with advanced filtering (with x++):
I want to make such filter criteria On SalesTable form to show SalesTable.SalesId == "001" || SalesLine.LineAmount == 100.
So result should show SalesOrder 001 AND other salesOrders which has at least one SalesLine with LineAmount = 100?

Jan's solution works fine if sales order '001' should only be selected if it has sales lines. If it doesn't have lines it won't appear in the output.
If it is important to you that sales order '001' should always appear in the output even if it doesn't have sales lines, you can do it via union as follows:
static void AdvancedFiltering(Args _args)
{
Query q;
QueryRun qr;
QueryBuildDataSource qbds;
SalesTable salesTable;
;
q = new Query();
q.queryType(QueryType::Union);
qbds = q.addDataSource(tablenum(SalesTable), identifierstr(SalesTable_1));
qbds.fields().dynamic(false);
qbds.fields().clearFieldList();
qbds.fields().addField(fieldnum(SalesTable, SalesId));
qbds.addRange(fieldnum(SalesTable, SalesId)).value(queryValue('001'));
qbds = q.addDataSource(tablenum(SalesTable), identifierstr(SalesTable_2), UnionType::Union);
qbds.fields().dynamic(false);
qbds.fields().clearFieldList();
qbds.fields().addField(fieldnum(SalesTable, SalesId));
qbds = qbds.addDataSource(tablenum(SalesLine));
qbds.relations(true);
qbds.joinMode(JoinMode::ExistsJoin);
qbds.addRange(fieldnum(SalesLine, LineAmount )).value(queryValue(100));
qr = new QueryRun(q);
while (qr.next())
{
salesTable = qr.get(tablenum(SalesTable));
info(salesTable.SalesId);
}
}

The AX select statement supports exists join such as:
while select salesTable
exits join salesLine
where salesLine.SalesId == salesTable.SalesId &&
salesLine.LineAmount == 100
X++ does not support exists clause as a subquery in the where clause. Therefore it is not possible to express the exists in combination with or.
However AX supports query expressions in a query.
Therefore your query should be possible to express like this:
static void TestQuery(Args _args)
{
SalesTable st;
QueryRun qr = new QueryRun(new Query());
QueryBuildDataSource qst = qr.query().addDataSource(tableNum(SalesTable));
QueryBuildDataSource qsl = qst.addDataSource(tableNum(SalesLine));
str qstr = strFmt('((%1.SalesId == "%2") || (%3.LineAmount == %4))',
qst.name(), queryValue("001"),
qsl.name(), queryValue(100));
qsl.relations(true); // Link on SalesId
qsl.joinMode(JoinMode::ExistsJoin);
qsl.addRange(fieldNum(SalesLine,RecId)).value(qstr);
info(qstr); // This is the query expression
info(qst.toString()); // This is the full query
while (qr.next())
{
st = qr.get(tableNum(SalesTable));
info(st.SalesId);
}
}
However, if sales order 001 does not contain lines, it will not be selected.
Other than that the output is as you requested:
((SalesTable_1.SalesId == "001") || (SalesLine_1.LineAmount == 100))
SELECT FIRSTFAST * FROM SalesTable
EXISTS JOIN FIRSTFAST * FROM SalesLine WHERE SalesTable.SalesId =
SalesLine.SalesId AND ((((SalesTable_1.SalesId == "001") ||
(SalesLine_1.LineAmount == 100))))
001
125
175

Related

Update Elements in table without changing table order Lua

I'd like to maintain the order of a table when updating table values in Lua.
Example
tbl = {
messageId = 0,
timestamp = currentTime,
responseStatus = {
status = "FAILED",
errorCode = "599",
errorMessage = "problem"
}
}
meaning tbl.messageId = 12345 leaves the elements ordered
Like #moteus said, your premise is incorrect: non-numeric entries in Lua tables are not sorted. The order, in which they are defined won't, in general, be the same order as that in which they will be read (e.g., pairs will iterate over those entries in an arbitrary order). Assigning a new value will not affect this in any way.
I suppose you can use table.sort, there is a simple example:
local tbl = {
messageId = 0,
timestamp = currentTime,
responseStatus = {
status = "FAILED",
errorCode = "599",
errorMessage = "problem"
}
}
function fnCompare (e1, e2)
-- you should promise e1 and e2 is tbl struct
-- you can check e1 and e2 first by yourself
return e1.messageId < e2.messageId;
end
-- test
local tbAll = {}
tbl.messageId = 3;
table.insert(tbAll, tbl);
-- add a another
table.insert(tbAll, {messageId = 1});
table.sort(tbAll, fnCompare);
for k, v in ipairs(tbAll) do
print(v.messageId); -- result: 1 3
end

How to compare two column in a spreadsheet

I have 30 columns and 1000 rows, I would like to compare column1 with another column. IF the value dont match then I would like to colour it red. Below is a small dataset in my spreadsheet:
A B C D E F ...
1 name sName email
2
3
.
n
Because I have a large dataset and I want to storing my columns in a array, the first row is heading. This is what I have done, however when testing I get empty result, can someone correct me what I am doing wrong?
var index = [];
var sheet = SpreadsheetApp.getActiveSheet();
function col(){
var data = sheet.getDataRange().getValues();
for (var i = 1; i <= data.length; i++) {
te = index[i] = data[1];
Logger.log(columnIndex[i])
if (data[3] != data[7]){
// column_id.setFontColor('red'); <--- I can set the background like this
}
}
}
From the code you can see I am scanning whole spreadsheet data[1] get the heading and in if loop (data[3] != data[7]) compare two columns. I do have to work on my colour variable but that can be done once I get the data that I need.
Try to check this tutorial if it can help you with your problem. This tutorial use a Google AppsScript to compare the two columns. If differences are found, the script should point these out. If no differences are found at all, the script should put out the text "[id]". Just customize this code for your own function.
Here is the code used to achieve this kind of comparison
function stringComparison(s1, s2) {
// lets test both variables are the same object type if not throw an error
if (Object.prototype.toString.call(s1) !== Object.prototype.toString.call(s2)){
throw("Both values need to be an array of cells or individual cells")
}
// if we are looking at two arrays of cells make sure the sizes match and only one column wide
if( Object.prototype.toString.call(s1) === '[object Array]' ) {
if (s1.length != s2.length || s1[0].length > 1 || s2[0].length > 1){
throw("Arrays of cells need to be same size and 1 column wide");
}
// since we are working with an array intialise the return
var out = [];
for (r in s1){ // loop over the rows and find differences using diff sub function
out.push([diff(s1[r][0], s2[r][0])]);
}
return out; // return response
} else { // we are working with two cells so return diff
return diff(s1, s2)
}
}
function diff (s1, s2){
var out = "[ ";
var notid = false;
// loop to match each character
for (var n = 0; n < s1.length; n++){
if (s1.charAt(n) == s2.charAt(n)){
out += "–";
} else {
out += s2.charAt(n);
notid = true;
}
out += " ";
}
out += " ]"
return (notid) ? out : "[ id. ]"; // if notid(entical) return output or [id.]
}
For more information, just check the tutorial link above and this SO question on how to compare two Spreadsheets.

Filtering IQueryable result set using parameters

I'm getting confused with this and I know there will be a more slick way of starting it off. The 'result' variable has many records and I want to check if IN_SiteId is > 0 and filter on it, same after that for LandownerId and PaymentCategoryId etc. If I can get the right approach for the first 2 I will be ok from there. This should be easier but having a brick wall day. Any comments appreciated
public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{
var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);
if (IN_SiteId > 0)
{
var searchResults = (from s in result
where (s.SiteId == #IN_SiteId)
select s);
return searchResults.AsQueryable();
}
return result.AsQueryable();
}
I'm not a LINQ expert but I think you can do something like this:
public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{
var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);
var searchResults = (from s in result
where (IN_SiteId <= 0 || s.SiteId == IN_SiteId)
&& (IN_LandownerId <= 0 || s.LandownerId == IN_LandownerId)
&& (IN_PaymentCategoryId <= 0 || s.PaymentCategoryId == IN_PaymentCategoryId)
&& (IN_PaymentTypeId <= 0 || s.PaymentTypeId == In_PaymentTypeId)
select s);
return searchResults.AsQueryable();
}
The where clause checks if each filter value is less than or equal to 0, if so then it will return true and will not evaluate the next bit which attempts to filter the actual field on the value provided.

Make good LINQ query with string[]

I have some problems with LINQ and maby someone got answers
string[] roleNames = Roles.GetRolesForUser(currentUserName);
result = context.MenuRoles.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
RoleName = mr.Role.RoleName,
RoleID = mr.RoleID,
MenuID = mr.MenuID
})
.Where(mr => mr.MenuActive == true)
.ToList();
How to take only compare string[] roleNames and return only if match. Problem alwais is when user is in the 2 or more roles.
Tx for answers
If I understand what you are asking for, add a second condition to your Where clause:
.Where(mr => mr.MenuActive && roleNames.Contains(mr.Role.RoleName))
You would be better off switching round your Where clause and Select for the simple reason that then you will not be retrieving from the database records which are not required.
result = context.MenuRoles.Where(mr => mr.MenuActive
&& roleNames.Contains(mr.Role.RoleName))
.Select(mr => ... )
.ToList();
This will generate a sql which only selects the necessary records, instead of selecting the whole lot and then filtering it. Try it and watch SQL profiler to see the difference (useful skill in any case when using EF)
With the help of brilliant people here, reached the target.
string[] roleNames = Roles.GetRolesForUser(currentUserName);
result = context.MenuRoles
.Where(mr => mr.Menu.MenuActive && roleNames.Contains(mr.Role.RoleName))
.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
RoleName = mr.Role.RoleName
})
.ToList();
var userresult = context.MenuUsers
.Where(mr => mr.Menu.MenuActive && mr.User.Username == currentUserName)
.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
Username = mr.User.Username
})
.ToList();
Here, gets all the menu to which you have the right, both through group membership and assigned directly to the menu itself.
// Kick all duplicates
var noduplicates = result.Concat(userresult)
.Distinct(new RoleMenuGenerateComparer());
Because usually we do not want duplicates in the menu so we remove them. For this to work properly we need to implement IEqualityComparer (U can read about this little bit up)
public class RoleMenuGenerateComparer : IEqualityComparer<MenuGenerateViewModel>
{
public bool Equals(MenuGenerateViewModel x, MenuGenerateViewModel y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.MenuNazwa == y.MenuNazwa && x.MenuID == y.MenuID;
}
public int GetHashCode(MenuGenerateViewModel menuGenerateViewModel)
{
if (Object.ReferenceEquals(menuGenerateViewModel, null)) return 0;
int hashMenuName = menuGenerateViewModel.MenuNazwa == null ? 0 : menuGenerateViewModel.MenuNazwa.GetHashCode();
int hashMenuID = menuGenerateViewModel.MenuID == null ? 0 : menuGenerateViewModel.MenuID.GetHashCode();
return hashMenuName ^ hashMenuID;
}
}
Of course I believe that you can optimize this code, but for the moment I have something like this.
Tx all for help.

Propel NestedSet creating Balanced Tree

I'm trying to use Propel's NestedSet feature. However, I'm missing something about inserting such that the tree is balanced as it is created (i.e. fill it in horizontally).
Say I have these elements:
root
r1c1 r1c2
r2c1 r2c2
I want to insert r2c3 as the 1st child of r1c2 (i.e. fill row 2 before starting on row 3).
My first stab at this was to create this function:
function where(User $root,$depth=0)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
foreach($root->getChildren() as $d)
{
if ( $d->getNumberOfChildren() < 2 )
{
return $d;
}
}
foreach($root->getChildren() as $d)
{
return where($d, $depth+1);
}
}
However, this will insert a child on r2c1, rather at r1c2 as I want.
Is there a way to insert an entry into the tree at the next available spot somehow?
TIA
Mike
OK, thanks to http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, I found that this algorithm will do what I want:
function where($root)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
$finder = DbFinder::from('User')->
where('LeftId','>=',$root->getLeftId())->
where('RightId','<=',$root->getRightId())->
whereCustom('user.RightId = user.LeftId + ?',1,'left')->
whereCustom('user.RightId = user.LeftId + ?',3,'right')->
combine(array('left','right'),'or')->
orderBy('ParentId');
return $finder->findOne();
}
It basically executes this SQL:
SELECT u.*
FROM user u
WHERE u.LEFT_ID >= $left AND u.RIGHT_ID <= $right AND
(u.RIGHT_ID = u.LEFT_ID+1 OR u.RIGHT_ID = u.LEFT_ID+3)
ORDER BY u.PARENT_ID
LIMIT 1
A leaf has RIGHT=LEFT+1, A node with 1 child has RIGHT=LEFT+3. By adding the ORDER BY u.PARENT_ID, we find the highest node in the tree available. If you use LEFT_ID or RIGHT_ID, it does not balance the tree.

Resources