How to use 'LIKE' in queryBuilder in AX 2012 - sql-like

I am new to QueryBuilder and was trying to convert the below select statement which contains like into a query, but I am not able to do that.
Can anyone please help me with the same?
while select * from dummyTable
where dummyTable.Field1 Like 10* || dummyTable.Field2 Like 10*
Below is my queryBuilder code:
qbr = qbds.addRange(fieldNum(dummyTable, Field1);
qbr.value('10*');
qbr = qbds.addRange(fieldNum(dummyTable, Field2);
qbr.value('20*');
The above piece of code is returning:
SELECT * FROM DummyTable(DummyTable_1)
WHERE ((Field1 LIKE N'10*')) AND ((Field2 LIKE N'20*'))
I need OR operator instead of AND in the above statement. Any suggestions would be appreciated.
Thank you in advance.

I hope I have understood correctly. Following our community contributor, please, could you check and stydy the code below.
static void Job1(Args _args)
{
Query query;
QueryRun queryRun;
QueryBuildDataSource dataSource;
QueryBuildDataSource dataSource2;
QueryBuildDataSource dataSource3;
str textDesc = "";
query = new Query();
dataSource = query.addDataSource(tableNum(LogisticsAddressCountryRegionTranslation));
dataSource2 = dataSource.addDataSource(tableNum(Currency));
dataSource2.relations(true);
dataSource3 = dataSource2.addDataSource(tableNum(LogisticsAddressCountryRegion));
dataSource3.relations(true);
SysQuery::findOrCreateRange(dataSource, fieldNum(LogisticsAddressCountryRegionTranslation, LanguageId)).value("EN-US");
if (textDesc != "")
{
SysQuery::findOrCreateRange(dataSource, fieldNum(LogisticsAddressCountryRegionTranslation, ShortName)).value(SysQuery::valueLike(textDesc));
}
info(query.dataSourceNo(1).toString());
queryRun = new QueryRun(query);
}
LIKE command
SysQuery::findOrCreateRange(dataSource, fieldNum(LogisticsAddressCountryRegionTranslation, ShortName)).value(SysQuery::valueLike(textDesc))
OR command, could you
static void WIK_LikeNotLike(Args _args)
{
CustTable custTable;
Query query = new Query();
QueryRun queryRun;
QueryBuildDataSource qbds = query.addDataSource(custTable.TableId);
QueryBuildRange qbr = SysQuery::findOrCreateRange(qbds, fieldNum(CustTable, AccountNum));
str range = strFmt('((AccountNum LIKE "%1") || (!(AccountNum LIKE "%2")))',
SysQuery::valueLikeAfter('C904029'),
SysQuery::valueLikeAfter('C'));
qbr.value(range);
info(range);
info(qbds.toString());
queryRun = new QueryRun(query);
while (queryRun.next())
{
custTable = queryRun.get(tableNum(CustTable));
info(custTable.AccountNum);
}
}
Helpful links:
https://stoneridgesoftware.com/programmatically-create-queries-dynamics-ax-data-surprises/
https://community.dynamics.com/ax/f/microsoft-dynamics-ax-forum/148751/how-to-join-using-querybuilder/337061
https://community.dynamics.com/ax/f/microsoft-dynamics-ax-forum/223431/query-with-or-and-not-like
Find you way.

Related

Displaying data from CMS_User in kentico

I have user control and I want to fill a drop-down list form control with CMS User table with a condition on it. could you please help me to do it. thank you in advance
for someone who needs, the answer is here (the where condition depends on the type of search you have, so I left it empty) :
public void FillUsers()
{
string where = "";
var UserColumns = UserInfoProvider.GetUsers().Columns("UserID", "FullName", "BusinessUnitId").Where(where).OrderBy("asia_personalcode");
if (UserColumns != null)
{
DataSet ds = UserColumns;
if (!DataHelper.DataSourceIsEmpty(ds))
{
cmbUser.DataSource = ds;
cmbUser.DataTextField = "FullName";
cmbUser.DataValueField = "UserID";
cmbUser.DataBind();
cmbUser.Items.Insert(0, "-");
cmbUser.Items[0]``.Value = "";
}
}
}

how to specify particular record type of transaction search in netsuite...

I want Salesorder records to my application.how to specify Salesorder recordtype to Transaction search Basic.currently i'm getting all types of records but i need only Sales order records...how to do please suggest me...
SearchDateField created=new SearchDateField();
//SearchDateFieldOperator searchDateFieldOperator=new SearchDateFieldOp;
SimpleDateFormat dft1=new SimpleDateFormat("MM-dd-yyyy");
Calendar calendar=Calendar.getInstance();
calendar.setTime(fromDate);
created.setSearchValue(calendar);
Calendar calendar2=Calendar.getInstance();
calendar2.setTime(toDate);
created.setSearchValue2(calendar2);
created.setOperator(SearchDateFieldOperator.within);
TransactionSearchBasic tsb=new TransactionSearchBasic();
tsb.setDateCreated(created);
SearchResult res = _port.search(tsb);
RecordList rl=res.getRecordList();
Record[] records=rl.getRecord();
Suppose you create a utility method like this:
public static SearchEnumMultiSelectField GetSearchEnumMultiSelectField(String[] searchValue, SearchEnumMultiSelectFieldOperator op)
{
SearchEnumMultiSelectField semsf = new SearchEnumMultiSelectField();
semsf.operatorSpecified = true;
semsf.#operator = op;
semsf.searchValue = searchValue;
return semsf;
}
and now during search you call it like this:
TransactionSearch ts = new TransactionSearch();
ts.basic = new TransactionSearchBasic();
ts.basic.type = GetSearchEnumMultiSelectField(new String[] { "salesOrder" }, SearchEnumMultiSelectFieldOperator.anyOf);
//Do rest of the code here for calling search
//Call Port.search etc
So the idea here is to use SearchEnumMultiSelectField object and set its different values to achieve your result.
Hope this helps!

c# string delimiter

I have string value like this:
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
I just need to retrieve role to string array. I wonder if there is the best way to split the string in C# 4.0
string[] arrStrRole = strRole.Split('|').Select .. ??
Basically, I need brandUK, brandUsa, brandAu to string[] arrStrRole.
Thanks.
string[] arrStrRole = strRole.Split('|').Select(r => r.Split(new []{"role="}, StringSplitOptions.None)[1]).ToArray()
results in an string array with three strings:
branduk
brankdusa
brandAu
you can use string[] arrStrRole = strRole.Split('|',','); and this will split according to | and , characters
You can use String.Split in this LINQ query:
var roles = from token in strRole.Split('|')
from part in token.Split(',')
where part.Split('=')[0] == "role"
select part.Split('=')[1];
Note that this is yet prone to error and requires the data always to have this format. I mention it because you've started with Split('|').Select.... You can also use nested loops.
If you need it as String[] you just need to call ToArray:
String[] result = roles.ToArray();
I would go with Regex rather than splitting string. In combination with your intended Select solution, it could look like this:
var roles = Regex.Matches(strRole, #"role=(\w+)")
.Cast<Match>()
.Select(x => x.Groups[1].Value).ToArray();
You could use an extension like this which would allow you to test it easily.
public static string[] ParseRolesIntoList(this string csvGiven)
{
var list = new List<string>();
if (csvGiven == null) return null;
var csv = csvGiven.Split(',');
foreach (var s in csv)
{
if (string.IsNullOrEmpty(s)) continue;
if(!s.StartsWith("role")) continue;
var upperBound = s.IndexOf("|");
if (upperBound <= 0) upperBound = s.Length;
var role = s.Substring(s.IndexOf("=") + 1,
upperBound - s.IndexOf("=") - 1);
list.Add(role);
}
return list.ToArray();
}
Test below found brankdusa typo in your example. Some of the other answers would not deal with brandAu as it matches slightly differently. Try running this test against them if you like
[Test]
public void Should_parse_into_roles()
{
//GIVEN
const string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
//WHEN
var roles = strRole.ParseRolesIntoList();
//THEN
Assert.That(roles.Length, Is.EqualTo(3));
Assert.That(roles[0], Is.EqualTo("branduk"));
Assert.That(roles[1], Is.EqualTo("brankdusa"));
Assert.That(roles[2], Is.EqualTo("brandAu"));
}
This gives an array of the 3 values.
void Main()
{
string strRole = "ab=Admin,ca=system,ou=application,role=branduk|ab=Manager,ca=system,ou=application,role=brankdusa|ab=sale,ca=system,ou=application,role=brandAu";
var arrStrRole = strRole.Split('|',',')
.Where(a => a.Split('=')[0] == "role")
.Select(b => b.Split('=')[1]);
arrStrRole.Dump();
}

Bast Way On Passing Query Parameters to Solrnet

I have been working on making a Search using Solrnet which is working the way I want to. But I just would like some advice on the best way to pass my query parameters from my web page into Solrnet.
What I would ideally like to do is pass my query string parameters similar to how this site does it: http://www.watchfinder.co.uk/SearchResults.aspx?q=%3a&f_brand=Rolex&f_bracelets=Steel&f_movements=Automatic.
As you can see from the sites query string it looks like it is being passed into SolrNet directly. Here is I am doing it at the moment (facet query segment):
public class SoftwareSalesSearcher
{
public static SoftwareSalesSearchResults Facet()
{
ISolrOperations solr = SolrOperationsCache.GetSolrOperations(ConfigurationManager.AppSettings["SolrUrl"]);
//Iterate through querystring to get the required fields to query Solrnet
List queryCollection = new List();
foreach (string key in HttpContext.Current.Request.QueryString.Keys)
{
queryCollection.Add(new SolrQuery(String.Format("{0}:{1}", key, HttpContext.Current.Request.QueryString[key])));
}
var lessThan25 = new SolrQueryByRange("SoftwareSales", 0m, 25m);
var moreThan25 = new SolrQueryByRange("SoftwareSales", 26m, 50m);
var moreThan50 = new SolrQueryByRange("SoftwareSales", 51m, 75m);
var moreThan75 = new SolrQueryByRange("SoftwareSales", 76m, 100m);
QueryOptions options = new QueryOptions
{
Rows = 0,
Facet = new FacetParameters {
Queries = new[] { new SolrFacetQuery(lessThan25), new SolrFacetQuery(moreThan25), new SolrFacetQuery(moreThan50), new SolrFacetQuery(moreThan75) }
},
FilterQueries = queryCollection.ToArray()
};
var results = solr.Query(SolrQuery.All, options);
var searchResults = new SoftwareSalesSearchResults();
List softwareSalesInformation = new List();
foreach (var facet in results.FacetQueries)
{
if (facet.Value != 0)
{
SoftwareSalesFacetDetail salesItem = new SoftwareSalesFacetDetail();
salesItem.Price = facet.Key;
salesItem.Value = facet.Value;
softwareSalesInformation.Add(salesItem);
}
}
searchResults.Results = softwareSalesInformation;
searchResults.TotalResults = results.NumFound;
searchResults.QueryTime = results.Header.QTime;
return searchResults;
}
}
At the moment I can't seem to see how I can query all my results from my current code by add the following querystring: q=:.
I'm not sure what you mean by "parameters being passed into SolrNet directly". It seems that watchfinder is using some variant of the model binder included in the SolrNet sample app.
Also take a look at the controller in the sample app to see how the SolrNet parameters are built.

how to run stored procedure from groovy that returns multiple resultsets

I couldnt find any good example of doing this online.
Can someone please show how to run a stored procedure (that returns multiple resultsets) from groovy?
Basically I am just trying to determine how many resultsets the stored procedure returns..
I have written a helper which allows me to work with stored procedures that return a single ResultSet in a way that is similar to working with queries with groovy.sql.Sql. This could easily be adapted to process multiple ResultSets (I assume each would need it's own closure).
Usage:
Sql sql = Sql.newInstance(dataSource)
SqlHelper helper = new SqlHelper(sql);
helper.eachSprocRow('EXEC sp_my_sproc ?, ?, ?', ['a', 'b', 'c']) { row ->
println "foo=${row.foo}, bar=${row.bar}, baz=${row.baz}"
}
Code:
class SqlHelper {
private Sql sql;
SqlHelper(Sql sql) {
this.sql = sql;
}
public void eachSprocRow(String query, List parameters, Closure closure) {
sql.cacheConnection { Connection con ->
CallableStatement proc = con.prepareCall(query)
try {
parameters.eachWithIndex { param, i ->
proc.setObject(i+1, param)
}
boolean result = proc.execute()
boolean found = false
while (!found) {
if (result) {
ResultSet rs = proc.getResultSet()
ResultSetMetaData md = rs.getMetaData()
int columnCount = md.getColumnCount()
while (rs.next()) {
// use case insensitive map
Map row = new TreeMap(String.CASE_INSENSITIVE_ORDER)
for (int i = 0; i < columnCount; ++ i) {
row[md.getColumnName(i+1)] = rs.getObject(i+1)
}
closure.call(row)
}
found = true;
} else if (proc.getUpdateCount() < 0) {
throw new RuntimeException("Sproc ${query} did not return a result set")
}
result = proc.getMoreResults()
}
} finally {
proc.close()
}
}
}
}
All Java classes are usable from Groovy. If Groovy does not give you a way to do it, then you can do it Java-way using JDBC callable statements.
I just stumbled across what could possibly be a solution to your problem, if an example was what you were after, have a look at the reply to this thread

Resources