CFScript Evaluate() throws error in loop - coldfusion

I'm attempting to dump a bunch of get functions into a spreadsheet using cfspreadsheet - instead of passing each individual function, I've decided to create a list and loop through it. I think I am using Evaluate() incorrectly here, but I'm not sure what the best way to accomplish this is. Any suggestions/optimizations would be appreciated, as my Cold-Fu isn't that great.
Error thrown is Variable GETFIELDS is undefined.
<cfset var fields = "Function1,Function2" />
<cfspreadsheet action="read" src="#strDestinationPath#information.xls" name="xlsInfo" headerrow="1" />
<cfset var row = xlsData.rowcount + 1 />
<cfset var count = 1 />
<cfloop list="fields" index="f" delimiters=",">
<cfscript>
SpreadsheetSetCellValue(xlsInfo,Evaluate('get' & f & '()'),row,count);
count++;
</cfscript>
</cfloop>
<cfspreadsheet action="write" overwrite="true" filename="#strDestinationPath#information.xls" name="xlsInformation" />

cfloop expects a list of items as an argument.
Try changing from
<cfloop list="fields" index="f" delimiters=",">
to
<cfloop list="#fields#" index="f" delimiters=",">
or to
<cfloop list="Function1,Function2" index="f" delimiters=",">

Related

ColdFusion looping over an array with an empty/undefined field

I am downloading data from an API from one of our vendors. The data is an array but some of the fields are empty and come over as undefined. I am able to get most of the information out with a loop but when I add the field "notes" it fails with the error of:
"Element notes is undefined in a CFML structure referenced as part of an expression. The specific sequence of files included or processed is:
C:\websites\Fire\Reports\xml_parse\Crewsense_payroll_loop.cfm, line:
21 "
When I look at the dump I see that the field shows as "undefined". I've run out of ideas. Any help would be greatly appreciated. I've included the entire code and a link to the dump showing the array.
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
#ApiData[i]["notes"]# <---Fails here when added--->
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>
Dump
When dealing with data structures that have optional elements you will need to check for their existence before trying to access them. Otherwise you will get that error. I have added a snippet with an if condition utilizing the structKeyExists() function to your code as an example.
<cfhttp url="https://api.crewsense.com/v1/payroll? access_token=as;lkdfj;alskdfj;laksdfj&token_type=bearer&start=2019-01-05%2019:00:00&end=2019-01-06%2007:59:00" method="GET" resolveurl="YES" result="result">
</cfhttp>
<cfoutput>
<cfset ApiData = deserializeJSON(result.filecontent)>
<cfset API_ArrayLength = arraylen(ApiData)>
<cfloop index="i" from="1" to=#API_ArrayLength#>
#i# #ApiData[i]["name"]#
#ApiData[i]["employee_id"]#
#ApiData[i]["start"]#
#ApiData[i]["end"]#
#ApiData[i]["total_hours"]#
#ApiData[i]["work_type"]#
#ApiData[i]["work_code"]#
#ApiData[i]["user_id"]#
<cfif structKeyExists(ApiData[i],"notes")>
#ApiData[i]["notes"]# <!--- Show 'notes' if it exists --->
<cfelse>
'notes' is not available <!--- Do something here (or not) --->
</cfif>
<cfset i = i+1>
<br>
</cfloop>
<cfdump var="#ApiData#">
</cfoutput>

Getting data from the function using an Object in CF

I have a CFC object and a function which gets me the data which I want. Now I want to use that data and provide it to an already defined custom tag attribute. When I dump the #iEngine.listScore()# I get some parameters. But my problem is how should I provide those to an attribute?
<cfdump var="#iEngine.listScores()#" label="Swapnil Test - Function ListScore">
<cfset filename="ACE_DataExtract_#DateFormat(now(),'dd.mmm.yyyy')#.xls" />
<!--- Calling Custom tags to create/output xls files --->
<cfmodule template="#request.library.customtags.virtualpath#excel.cfm" file="#filename#" sheetname="ACE Report">
<cfmodule template="#request.library.customtags.virtualpath#exceldata.cfm"
query="#iEngine.listScores()#"
action="AddWorksheet"
sheetname="ACE Report"
colorscheme="blue"
useheaders="true"
contentformat="#{bold=true}#"
customheaders="#ListScore#">
<cfoutput>Excel Extract - ACE Report - #DateFormat(Now(),"d-mmm-yyyy")#</cfoutput>
</cfmodule>
</cfmodule>
Here I want to provide the data of iEngine.listScore() to the "Query" attribute in "exceldata" custom tag.
Below is the dump of iEngine.listScore()
I would write a transform Data function to change your array-struct to a query object, then pass that on....
<cffunction name="transformData" result="query">
<cfargument name="inArray" type="array">
<cfset local.qryReturn = queryNew("actiondate,actionId,closedate")>
<!--- You may look up queryNew and also set your dataTypes --->
<cfloop array="#arguments.inArray#" index="i">
<cfset QueryAddRow(local.qryReturn)>
<cfset querySetCell(local.qryReturn,"actionDate",i["actiondate"])>
<cfset querySetCell(local.qryReturn,"actionid",i["actionid"])>
<cfset querySetCell(local.qryReturn,"closedate",i["closedate"])>
</cfloop>
<cfreturn local.qryReturn>
</cffunction>
<cfset test = [
{actiondate='1/1/2015',actionid=134,closedate=''},
{actiondate='1/2/2015',actionid=135,closedate=''},
{actiondate='1/3/2015',actionid=136,closedate=''}
]>
<cfdump var="#test#">
<cfset resultQry = transformData(test)>
<cfif NOT isquery(resultQry)>
Exit invalid Data.
<cfelse>
<cfdump var="#resultQry#">
</cfif>

Coldfusion 10 - Element [n] is undefined in a Java object of type class coldfusion.runtime.Array

I recently upgraded a system from CF8 to CF10 and have one bug that I'm having problems tracking down. It has to do with a remote API call that gets a JSON string back and that string then gets converted to a query object. That's where I'm coming across the error:
Element [n] is undefined in a Java object of type class coldfusion.runtime.Array. The problem is in the function that converts the string to a query.
<cffunction name="CFjsonToQuery" access="public" returntype="query" output="no">
<cfargument name="cfData" required="yes" type="struct"/>
<cfset var LOCAL = {}/>
<cfset LOCAL.tmpQry = QueryNew( ArrayToList(ARGUMENTS.cfData.Data.COLUMNS) ) />
<cfloop index = "i" from = "1" to = "#ArrayLen(ARGUMENTS.cfData.Data.DATA)#">
<cfset LOCAL.Row = QueryAddRow(LOCAL.tmpQry) />
<cfloop index="k" from="1" to="#ArrayLen(ARGUMENTS.cfData.Data.DATA[i])#">
<cfset LOCAL.colName = ARGUMENTS.cfData.Data.COLUMNS[K]/>
<cfset QuerySetCell(LOCAL.tmpQry,LOCAL.colName,ARGUMENTS.cfData.Data.DATA[i][k],LOCAL.Row)/>
</cfloop>
</cfloop>
<cfreturn LOCAL.tmpQry/>
</cffunction>
Anywhere the JSON returns 'null' (i.e. "...","19107-3609",null,null,null,"...") the error is thrown. I've tried using isNull to check if it's null in the cfloop:
<cfif isNull(ARGUMENTS.cfData.Data.DATA[i][k])>
<cfset ARGUMENTS.cfData.Data.DATA[i][k] = 'I AM NULL'/>
</cfif>
EDIT - here's a simplified example - the issue is the way the newer deserializeJson() works I believe:
<cfset jstr = '{"SUCCESS":true,"ERRORS":[],"DATA":{"COLUMNS":["ID","FNAME","LNAME"],"DATA":[[390132,"steve",null]]}}'/>
<cfset cfData = deserializeJson(jstr) />
<cfloop index = "i" from = "1" to = "#ArrayLen(cfData.Data.DATA)#">
<cfset Row = QueryAddRow(tmpQry) />
<cfloop index="k" from="1" to="#ArrayLen(cfData.Data.DATA[i])#">
<cfset colName = cfData.Data.COLUMNS[K]/>
<cfset QuerySetCell(tmpQry,colName,cfData.Data.DATA[i][k],Row)/>
</cfloop>
</cfloop>
I've tried all sorts of tests for empty string, isNull etc. and I'm still not sure how to get the query object built if deserializejson returns:
[undefined array element] Element 3 is undefined in a Java object of type class coldfusion.runtime.Array.
This does seem to work:
<cfset cfData = deserializeJson(returnData,'FALSE') />
<cfset qryData = cfData.data />
This lets me then use qryData as if it were a normal cfquery.
You can do a check if the element is undefined using the CF Function ArrayIsDefined(array, elementIndex)
What I've done for now is add 'FALSE' to the deserializeJSON strictMapping flag and that seems to automatically create a query object? I'll admit though this is getting into the underpinnings of CF10 and I could be wrong on that. I'll update my code above for visual clarity.

Problems with creating an array of structs

I'm making a blog API and am having some very strange issues when trying to create an array of structs in coldfusion. The top level array will contain the post, as a struct, with a .comments that is an array of all comments under that post, also as structs.
Each of the pieces in the following code work individually. But, somehow when I put them together I end up with an infinitely nested array of structs containing an array of structs etc... all of only the very last element in the top level array of posts.
<cfset posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset result = arraynew(1) />
<cfloop index="i" from="1" to="#arrayLen(posts)#">
<cfset post = posts[i].getInstance()>
<cfset StructInsert(post, 'comments', getComments(post.postId))>
<cfset ArrayAppend(result, post)>
</cfloop>
getBlogPosts returns an array of Post beans.
bean.getInstance() returns a struct with all the data in the bean.
getComments(id) returns an array all comments(structs) for post[id].
Each of these works as intended and is used elsewhere without problems.
The structure of the infinitely nested array is as such:
Array containing Post
. Post.comments containing array of comments + Post on end
. . Post.comments containing array of comments + Post on end
. . . etc...
You didn't show the entire code.
I suspect replacing what you did show with either of these will solve the problem:
<cfset local.posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset local.result = arraynew(1) />
<cfloop index="local.i" from="1" to="#arrayLen(local.posts)#">
<cfset local.post = local.posts[local.i].getInstance()>
<cfset StructInsert(local.post, 'comments', getComments(local.post.postId))>
<cfset ArrayAppend(local.result, local.post)>
</cfloop>
Or:
<cfset var posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset var result = arraynew(1) />
<cfset var i = 0 />
<cfset var post = 0 />
<cfloop index="i" from="1" to="#arrayLen(posts)#">
<cfset post = posts[i].getInstance()>
<cfset StructInsert(post, 'comments', getComments(post.postId))>
<cfset ArrayAppend(result, post)>
</cfloop>
You should always use either var keyword or local scope for variables in a cffunction.
You can use VarScoper to check your code for other places where this needs fixing.
Please try adding some cfdumps in there and report back what you get:
<cfset posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset result = arraynew(1) />
<cfloop index="i" from="1" to="#arrayLen(posts)#">
<cfset post = posts[i].getInstance()>
<cfdump var="#post#">
<cfset StructInsert(post, 'comments', getComments(post.postId))>
<cfdump var="#post#">
<cfset ArrayAppend(result, post)>
<cfdump var="#result#"><cfabort>
</cfloop>
edit
I think the problem is a child reference to a parent value, which spawns the infinite loop when recursing through the object. Try changing to this:
<cfset posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset result = arraynew(1) />
<cfloop index="i" from="1" to="#arrayLen(posts)#">
<cfset post = posts[i].getInstance()>
<cfset StructInsert(post, 'comments', Duplicate(getComments(post.postId)))>
<cfset ArrayAppend(result, post)>
</cfloop>

Consuming a webservice code simplification

UPDATED CODE TO LATEST ITERATION
The following function consumes a webservice that returns address details based on zip code (CEP). I'm using this function to parse the xml and populate an empty query with the address details. I would like to know if there is a more elegant way to achieve the same result. It seems to be a waste to create an empty query and populate it...
Any ideas could my method be modified or the code factored/simplified?
<!--- ****** ACTION: getAddress (consumes web-service to retrieve address details) --->
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<!--- Defaults: strcep (cep (Brazilian zip-code) string webservice would look for), search result returned from webservice --->
<cfargument name="cep" type="string" default="00000000">
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0>
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<cftry>
<!--- Consume webservice --->
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#"></cfhttp>
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText>
<cfset tmp.streetName = nodes[1].nome.XmlText>
<cfset tmp.area = nodes[1].bairro.XmlText>
<cfset tmp.city = nodes[1].cidade.XmlText>
<cfset tmp.state = nodes[1].uf.XmlText>
<cfset tmp.cep = arguments.cep>
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(tmp.state)>
<cfset tmp.stateid = stateid.id>
<cfreturn tmp>
</cfif>
<!--- Display error if any --->
<cfcatch type="any">
<cfoutput>
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfoutput>
</cfcatch>
</cftry>
</cfif>
</cffunction>
<!--- ****** END ACTION getAddress --->
The calling code:
<!--- Get address data based on CEP --->
<cfset session.addressData = getAddress(cep=params.newMember.cep)>
I can't test this because I don't have an example XML file / CEP to test with, but here is a minor rewrite that addresses four things:
Instead of using cfparam and some strange "params" structure, you should pass the CEP into the function as an argument.
The function shouldn't directly modify session data. Instead, you should return the result and let the calling code assign it to the session (or wherever else it might be needed). I'll show this in a 2nd code example.
Cache the xml result per CEP -- assuming this doesn't change often. (You'll have to improve it further if you want time-based manual cache invalidation, but I can help add that if necessary)
Don't use StructInsert. It's not necessary and you're just writing it the long way for the sake of writing it the long way. There is no benefit.
Again, this isn't tested, but hopefully it's helpful:
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0 />
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<cfif not structKeyExists(application.cepCache, arguments.cep)><!--- or cache is expired: you'd have to figure this part out --->
<!--- Consume webservice --->
<cftry>
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText />
<cfset tmp.streetName = nodes[1].nome.XmlText />
<cfset tmp.area = nodes[1].bairro.XmlText />
<cfset tmp.city = nodes[1].cidade.XmlText />
<cfset tmp.state = nodes[1].uf.XmlText />
<cfset tmp.cep = arguments.cep />
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
<cfset tmp.stateid = stateid.id />
</cfif>
<cfreturn duplicate(tmp) />
<!--- Display error if any --->
<cfcatch type="any">
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfcatch>
</cftry>
<cfelse>
<!--- cache exists and is not expired, so use it --->
<cfreturn duplicate(application.cepCache[arguments.cep]) />
</cfif>
</cfif>
<!---
<!--- Redirect to page two of the sign up process --->
<cfset redirectTo(controller="assine", action="perfil")>
--->
</cffunction>
Notice that I commented out the redirect you had at the end. That's because with my function, you'll be returning a value, and the redirect should be done after that, like so:
<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>
If you're going to leave out the caching (As you say in a comment you will), then here is a version that makes no attempt at caching:
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0 />
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<!--- Consume webservice --->
<cftry>
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText />
<cfset tmp.streetName = nodes[1].nome.XmlText />
<cfset tmp.area = nodes[1].bairro.XmlText />
<cfset tmp.city = nodes[1].cidade.XmlText />
<cfset tmp.state = nodes[1].uf.XmlText />
<cfset tmp.cep = arguments.cep />
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
<cfset tmp.stateid = stateid.id />
</cfif>
<cfreturn duplicate(tmp) />
<!--- Display error if any --->
<cfcatch type="any">
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfcatch>
</cftry>
</cfif>
<!---
<!--- Redirect to page two of the sign up process --->
<cfset redirectTo(controller="assine", action="perfil")>
--->
</cffunction>
Note that I did leave in the use of duplicate(). What this does is return a duplicate of the object (in this case, the struct). This is much more important when you start to work on applications where you're passing complex values into and out of functions over and over again. Using duplicate() causes things to be passed by value instead of by reference. It may not bite you in this case, but it's a good habit to get into.
I would also still use the function argument and return a value -- but it's arguable that this is my personal preference. In a way it is. I believe that a function should be fully encapsulated; a total "black box". You give it some input and it gives you back some output. It should not modify anything outside of itself. (Again, just my opinion.)
So assuming you're using this function as part of a larger multi-step process, you should still use it the same way I've described above. The only difference is that you're setting the session variable outside of the function body. Just as previously:
<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>
That looks pretty straightforward. CF doesn't (yet?) have any magical XML-to-Query functions, but that would be pretty cool. If you wanted, you could probably write up an XSL transform to go from XML to WDDX so that you could use the cfwddx tag ... but that's probably putting the cart before the horse.
You need to move your arrayLen() if block into the try block. As it stands, if the cfhttp tag throws an error, the nodes variable will be a string and not an array, thus causing the arrayLen() to throw another error.
Minor nitpick: I wouldn't add a row to the query until inside the arrayLen() block. That way, the calling code can check recordCount to see if the result was a success.
Beyond that ... that's pretty much how it's done.