coercing a paramter into an integer in Body Mapping Template, AWS API Gateway - amazon-dynamodb

I've been using a bit of arithmetic in the Body Mapping Template in Integration Request:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + 600)
{
"TableName": "events",
.... [ here get events between $now and $soon]
}
Recently I came to need to pass an offset through a parameter:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + $input.params('offset'))
{
"TableName": "events",
.... [ here get events between $now and $soon] ....
}
It turns out that if $now is 1518939082, with query paramter ?offset=600 $soon will be 1518939082600 - a concatenation. I have tried various ways to force the parameter being recognised as an integer, including:
#set($offset = $Integer.parseInt($input.params('offset')))
#set($offset = 0 + $input.params('offset'))
#set($offset = 1 * $input.params('offset'))
None of them works. I inserted #set($offset = 0) before each test so I can tell "nothing happens" from "a nothingness is returned".
In the first case, $offset prints an empty string, not 0. (This happens to $Integer.parseInt("1") too.)
In the second case, $offset prints a concatenation of "0" and the string value of "offset".
In the third case, $offset prints a 0, as if the entire line doesn't exist.
None of them successfully transformed the parameter to an integer.
Is there a way to use that parameter as an integer?

Related

LINQ to Entities does not recognize the method call within it

I completely understand that this is because LINQ query requires the whole expression to be translated to a server , and therefore I cant call an outside method in it. but as I have looked at other answers there is not relative solution to this. the only approach that I thought about is to loop through all the items in the model and than passing them to the query one by one but even though this approach would not help so I am seeking help in here for anyone to help me to figure out how to call a method or a way of calling a method appendstr that initializes a.PostedDate before checking its actual equivalent value in the giving LINQ Query.
[HttpGet]
public ActionResult SearchResult(int? page, string searchTitle = null, string searchLocation = null, string last24 = "")
{
ViewBag.searchTitle = searchTitle;
ViewBag.searchLocation = searchLocation;
ViewBag.page = page;
ViewBag.last24 = last24;
setUpApi(searchTitle, searchLocation);
var result = new List<AllJobModel>().AsQueryable();
if (!string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.searchTitle) || !string.IsNullOrEmpty(ViewBag.last24))
{
setUpApi(searchTitle, searchLocation);
DateTime now = DateTime.Now;
result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation) &&
appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")));
}
else
{
result = from app in db.AllJobModel select app;
}
return View(result.ToList().ToPagedList(page ?? 1, 5));
}
The second method that gets called in the LINQ Query
public string appendstr(string str)
{
var x = str.Split(' ');
return 01 + "-" + x[1] + "-" + x[2];
}
I think you already understand that the .NET code you write in the Where clause is actually an expression that is parsed and converted to SQL. So if you have a funky string manipulation method, you can't use it directly.
The brute force option, as you seem to already understand, it to materialize the query first and then run the C# code over the results. You can do this with ToList() or AsEnumerable().
result = db.AllJobModel
.Where
(
a => a.JobTitle.Contains(searchTitle)
&& a.LocationName.Contains(searchLocation)
)
.AsEnumerable()
.Where
(
a => appendstr(a.PostedDate).Equals(now.AddHours(-24).ToString("MM-dd-yyyy")))
);
However in your specific case you can try a trick. You are attempting a date comparison, which SQL is perfectly capable of doing... you just need to convert that funky PostedDate to a SQL DateTime so that you can compare it directly. The gimmick for that is to use SqlFunctions.DateAdd to add null interval (e.g. 0 days). This implicitly converts the string to DateTime, where you can now query on the SQL side:
var targetDate = DateTime.Now.AddHours(-24);
result = db.AllJobModel
.Where
(
a => a.JobTitle.Contains(searchTitle)
&& a.LocationName.Contains(searchLocation)
&& SqlFunctions.DateAdd("DAY", 0, a.PostedDate) == targetDate
);
Credit goes to this post for the workaround.

Symfony Invalid parameter format, : given

I need create multiply search by years. From request I get string like 2017,2018 and then I want get Questions which createdAt, between from start year and end year. I have query builder with part, and I'am not understand why I have this error
if ($paramFetcher->get('years')) {
$orXSearch = $qb->expr()->orX();
$yearData = trim($paramFetcher->get('years'));
foreach (explode(',', $yearData) as $key => $id) {
if (!$id) {
continue;
}
$orXSearch
->add($qb->expr()->between('q.createdAt', ':'.$key.'dateFrom', ':'.$key.'dateTo'));
$date = $this->additionalFunction->validateDateTime($id, 'Y');
$first = clone $date;
$first->setDate($date->format('Y'), 1, 1);
$first->setTime(0, 0, 0);
$last = clone $date;
$last->setDate($date->format('Y'), 12, 31);
$last->setTime(23, 59 , 59);
$qb
->setParameter($key.'dateFrom', $first->format('Y-m-d H:i:s'))
->setParameter($key.'dateTo', $last->format('Y-m-d H:i:s'));
}
$qb->andWhere($orXSearch);
}
error:
symfony Invalid parameter format, : given, but :<name> or ?<num> expected.
In your foreach loop, you’re looping over the result of an explode operation which yields a numeric array, i.e. $key will always have a numeric value.
Hence, your parameter placeholder is colon + number + string, i.e. :1dateFrom. This is not allowed. Either you reference a string value with a colon + string placeholder (:foo), or you reference a numeric value with a question mark + number value (?1).
Your problem is easy to solve: Simply add any letter between the colon and the number, and you’re good:
->add($qb->expr()->between(
'q.createdAt',
':x'.$key.'dateFrom',
':x'.$key.'dateTo'
));

Passing javascript string variable into nlapiSearchRecord filter

I'm working on a Suitelet to apply landed costs (through a .csv file) to item receipts. This code below is iterating through an array of PO numbers to build out a formula(number) to pass into nlapiSearchRecord().
I'm having trouble getting the search to fire when passing part of the search filter in from a variable. I've tried passing various sizes of string with and without double or single quotes (see commented out sections for an idea) and now I'm simply passing one variable, testNumber, into the search string. It's still failing giving me this error:
SSS_INVALID_SRCH_FILTER_EXPR_OBJ_TYPEMalformed search filter expression: Unrecognized object type.
The complete line is supposed to be
["formulanumeric: case when {number} = 'PO476' or {number} = '294' then 1 else 2 end","equalto","1"],
for(var i = 0; i<poNumbers.length; i++) {
if(i < (poNumbers.length - 1)) {
poFormula += "{number} = '"+poNumbers[i]+"' or ";
}
else {
poFormula += "{number} = '"+poNumbers[i]+"'";
}
}
//poFormula(string) --> {number} = 'PO481' or {number} = 'PO476' or {number} = '294' or {number} = 'PO440' or {number} = 'PO441'
//var searchFormulaStart = "formulanumeric: case when "+poFormula+" then 1 else 2 end";
//var sfMiddle = "equalto";
//var sfEnd = "1";
var testNumber = "'PO476'";
var purchaseorderSearch = nlapiSearchRecord("purchaseorder",null,
[
["mainline","is","T"],
"AND",
["type","anyof","PurchOrd"],
"AND",
["formulanumeric: case when {number} = "+testNumber+" then 1 else 2 end","equalto","1"],
//[searchFormulaStart,sfMiddle,sfEnd],
"AND",
["type","anyof","PurchOrd"]
],
[
new nlobjSearchColumn("internalid",null,null)
]
);
The idea is that I need to return all the POs included in the .csv so I can get their internal ids. Later in the code, I will pass these ids into another search against item receipts, finding all receipts created from those POs. Once I have those, I can apply freight costs to those receipts.
var itemreceiptSearch = nlapiSearchRecord("itemreceipt",null,
[
["type","anyof","ItemRcpt"],
"AND",
["mainline","is","T"],
"AND",
["createdfrom","anyof", poInternalIds]
],
[
new nlobjSearchColumn("tranid",null,null)
]
);
Can anyone confirm if there's some undocumented bug or something with passing part of a search string in from a variable like this? Alternatively, given PO numbers and freight costs, is there a better way to apply landed costs to item receipts?
Thanks!
I found a solution with help from some folks on Slack. Rather than trying to concatenate variables into the filter string, I'm now creating the entire filter array in a forEach() loop as shown below.
I'm still not sure why the Netsuite API didn't like my search formatted with a concatenation, but this is a much cleaner solution anyway.
for(var i = 0; i<freightCosts.length; i++) {
poNumbers.push(freightCosts[i].PO);
}
poNumbers.forEach(function(tranid){
filters.push(["tranid", "is", tranid]);
filters.push("or");
});
// remove the last "or"
filters.pop();
var purchaseorderSearch = nlapiSearchRecord("purchaseorder",null,
[
["mainline","is","T"],
"AND",
["type","anyof","PurchOrd"],
"AND",
[filters]
],
[
new nlobjSearchColumn("internalid",null,null)
]
);
Weirdly enough, I ran into this exact issue just last week. It appears to be a bug in the Rhino Javascript engine that Netsuite uses. The workaround to get it to work is to wrap your concatenation in a String():
[String("formulanumeric: case when {number} = "+ testNumber + " then 1 else 2 end"), "equalto", "1"]

How can I create xquery using xml response

The below mentioned is actual xquery.
declare variable $rankCode_DL3UJ :=("CPT","FO","FM");
declare variable $rankCode_DL4UJ :=("CRFO","CL");
declare variable $type :=("DOM","ISH");
declare function local:getboardingPriorityCode($flightType as element(), $rankCode as element()) as xs:string
{
if(data($flightType) = $type) then
'DHD'
else
if(data($rankCode) = $rankCode_DL3UJ) then
'DL3UJ'
else if(data($rankCode) = $rankCode_DL4UJ) then
'DL4UJ'
else
'DL5UJ'
};
declare function local:getPreferredClass($flightType as element(flightCategory:Code)) as xs:string
{
if(data($flightType) = $type) then
'Y'
else
'J'
};
declare function xf:createDeadheadReservationRQ-to- PassengerDetailsRQ($createDeadheadReservationRQ1 as element(ns1:CreateDeadheadReservationRQ),$CreateDeadHeadReservationAdapterSelect RS as element(ns3:RefTickettypeCollection),
$airBookRS as element(flightCategory:GetFlightCategoryRS))
as element(ns2:PassengerDetailsRQ) {
<ns2:PassengerDetailsRQ Version = "2.0.0">
<ns2:SpecialReqDetails>
<ns2:AddRemarkRQ>
<ns2:RemarkInfo>
<ns2:Remark Type = "General">
<ns2:Text>{ data($createDeadheadReservationRQ1/ns1:SpecialRequestDetails/ns1:Remark) }</ns2:Text>
</ns2:Remark>
</ns2:RemarkInfo>
</ns2:AddRemarkRQ>
<ns2:SpecialServiceRQ>
<ns2:SpecialServiceInfo>
<ns2:SecureFlight SegmentNumber = "A" SSR_Code = "DOCS">
<ns2:PersonName DateOfBirth = "{ data($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:DateOfBirth) }"
Gender = "{ data($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:Gender) }"
NameNumber = "1.1">
<ns2:GivenName>{ data($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:PassengerName/ns1:GivenName) }</ns2:GivenName>
<ns2:Surname>{ data($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:PassengerName/ns1:Surname) }</ns2:Surname>
</ns2:PersonName>
<ns2:VendorPrefs>
<ns2:Airline Hosted = "true"/>
</ns2:VendorPrefs>
</ns2:SecureFlight>
<ns2:Service SSR_Code = "{ data($createDeadheadReservationRQ1/ns1:SpecialRequestDetails/ns1:RankBasedSSR) }">
<ns2:VendorPrefs>
<ns2:Airline Hosted = "true"/>
</ns2:VendorPrefs>
</ns2:Service>
</ns2:SpecialServiceInfo>
</ns2:SpecialServiceRQ>
</ns2:SpecialReqDetails>
<ns2:TravelItineraryAddInfoRQ>
<ns2:AgencyInfo>
<ns2:Ticketing TicketType = "{fn:concat('7PS-', local:getboardingPriorityCode($airBookRS/flightCategory:ServiceType/flightCategory:Code, $createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:RankCode), local:getPreferredClass($airBookRS/flightCategory:ServiceType/flightCategory:Code))}"/>
</ns2:AgencyInfo>
<ns2:CustomerInfo>
<ns2:PersonName>
<ns2:GivenName>{
xs:string(fn:concat($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:PassengerName/ns1:GivenName,' ',
$createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:PassengerName/ns1:Title))
}</ns2:GivenName>
<ns2:Surname>{ xs:string($createDeadheadReservationRQ1/ns1:PassengerInfo/ns1:PassengerName/ns1:Surname) }</ns2:Surname>
</ns2:PersonName>
</ns2:CustomerInfo>
</ns2:TravelItineraryAddInfoRQ>
</ns2:PassengerDetailsRQ>
};
declare variable $createDeadheadReservationRQ1 as element(ns1:CreateDeadheadReservationRQ) external;
declare variable $airBookRS as element(flightCategory:GetFlightCategoryRS) external;
declare variable $CreateDeadHeadReservationAdapterSelectRS as element(ns3:RefTickettypeCollection) external;
xf:createDeadheadReservationRQ-to- PassengerDetailsRQ($createDeadheadReservationRQ1, $airBookRS, $CreateDeadHeadReservationAdapterSelectRS)
So We have to do the below changes.
for that we have created the below mentioned table in DB, using JCA adapter we have received the response and created the xml response creating business service of JCA adapter in OSB.
condition: In query we need to fetch OTHER always so query will be as follows and if we get 2 results then pick one that is not “other” like pick CPT if it returned in result of select query and if we get 1 result then it will be always “Other”.
Select *from <Table> where Code_name in (‘OTHER’, 'value received in request');
xml request and response of business service JCA adapter:
Request:
<cre:CreateDeadHeadReservationAdapterSelect_CODE_NAMEInputParameters>
<cre:CODE_NAME>CPT</cre:CODE_NAME>
</cre:CreateDeadHeadReservationAdapterSelect_CODE_NAMEInputParameters>
Response:
<cre:RefTickettypeCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cre="http://xmlns.oracle.com/pcbpel/adapter/db/top/CreateDeadHeadReservati onAdapter">
<cre:RefTickettype>
<cre:codeName>CPT</cre:codeName>
<cre:codeType>Rank</cre:codeType>
<cre:priorityCode>DL3UJ</cre:priorityCode>
<cre:preferredClass>J</cre:preferredClass>
</cre:RefTickettype>
<cre:RefTickettype>
<cre:codeName>OTHER</cre:codeName>
<cre:codeType>Other</cre:codeType>
<cre:priorityCode>DL7UJ</cre:priorityCode>
<cre:preferredClass>J</cre:preferredClass>
</cre:RefTickettype></cre:RefTickettypeCollection>
So using the above response could you pls help me to create the xquery logic.
I'm not sure I understand all of your question. But, it sounds like when two RefTickettype elements are returned, you want to select the one where codeName is not OTHER?
The following query checks to see how many RefTickettype elements are in the result. If there is only one, it is returned. If there is more than one, it will return all where codeName is not OTHER.
declare namespace cre="http://xmlns.oracle.com/pcbpel/adapter/db/top/CreateDeadHeadReservationAdapter";
let $response :=
<cre:RefTickettypeCollection>
<cre:RefTickettype>
<cre:codeName>CPT</cre:codeName>
<cre:codeType>Rank</cre:codeType>
<cre:priorityCode>DL3UJ</cre:priorityCode>
<cre:preferredClass>J</cre:preferredClass>
</cre:RefTickettype>
<cre:RefTickettype>
<cre:codeName>OTHER</cre:codeName>
<cre:codeType>Other</cre:codeType>
<cre:priorityCode>DL7UJ</cre:priorityCode>
<cre:preferredClass>J</cre:preferredClass>
</cre:RefTickettype>
</cre:RefTickettypeCollection>
return
if (count($response/cre:RefTickettype) eq 1) then
$response/cre:RefTickettype
else
$response/cre:RefTickettype[cre:codeName ne "OTHER"]

METEOR - Automatically increment order numbers

What I need to do is use either collection-2 or another package to automatically create a new order number, incremented from the last order number used.
i.e. Starting off with PO123456, when I save this order, the next time I make a new PO, it automatically generates the number PO123457.
I've been looking for a good example or tutorial, but I'm not able to find one.
Using konecty:mongo-counter in conjuntion with aldeed:collection2 and aldeed:simple-schema should be pretty straightforward. In your schema definition try:
POnumber: { type: String, autoValue: function(){
if ( this.isInsert ){ // restrict to when inserting a document
var currentNumber = incrementCounter('purchase order'); // this will use mongo-counter
// WARNING: you can only ever get as rich as 10M POs!!
var zeroPad = "000000" + currentNumber; // pad with 6 zeros
zeroPad = zeroPad.substr(zeroPad.length-7); // restrict to 7 places
return 'PO' + zeroPad; // prefix with 'PO'
} else if ( this.isSet ){
this.unset(); // prevent attempts to change the number
}
}

Resources