I am trying to create a custom debug tool and I need to use a component with two separate functions in it. The first function (startTimer) has some arguments such as startCount and the other one (endTimer) has endCount. What I am trying to accomplish is something like the following code:
<cffunction name="startTimer" access="public" returntype="void">
<cfargument name="startActionTime" type="string" required="no">
</cffunction>
<cffunction name="endTimer" returntype="void" access="public">
<cfargument name="endActionTime" type="string" required="no">
<cfset finalTime = endActionTime - startTimer.startActionTime>
<!---Some SQL will go here to record the data in a db table --->
</cffunction>
And this is how I am calling the function
<cfscript>
location = CreateObject("component","timer");
loc =location.startTimer(
startActionTime = getTickCount()
);
end = location.endTimer(
endActionTime = getTickCount()
);
</cfscript>
I guess I am having scope issues because when I am trying to run the code I am getting an undefined error on startTimer.startActionTime. What is the correct way to do something like this?
You can use the variables scope like so:
<cfcomponent>
<cfset variables.startActionTime = 0>
<cffunction name="startTimer" access="public" returntype="void">
<cfargument name="startActionTime" type="numeric" required="no">
<cfset variables.startActionTime = arguments.startActionTime>
</cffunction>
<cffunction name="endTimer" returntype="string" access="public">
<cfargument name="endActionTime" type="numeric" required="no">
<cfset finalTime = endActionTime - variables.startActionTime>
<!---Some SQL will go here to record the data in a db table --->
<Cfreturn finaltime>
</cffunction>
</cfcomponent>
From the Adobe Docs: Variables scope variables created in a CFC are available only to the component and its functions, and not to the page that instantiates the component or calls its functions.
Related
For several years, I have used dropdowns to determine the requirements for a SQL query and have never needed to use dropdowns with ‘related selects’ until now. I found a sample on how to do this and I can create related selects (with static data) which works well, see below using my data relating to vehicles and makes.
However, when I come to apply this to my environment, and use dynamic SQL query data, I cannot get it to work. I am confident that all the pieces of code are working together (as it works perfectly for the static data), but if I try and build the data automatically and then create the string to pass to the queryNew function, it fails.
This is the working Content.cfc file with STATIC query strings/data array
<cfcomponent>
<cfset tblMake = queryNew("name,id", "varchar,varchar", [{name:'RENAULT',id:'RENAULT'},{name:'RENAULT',id:'RENAULT'},{name:'RENAULT',id:'RENAULT'}])>
<cfset tblModel = queryNew("name,code,continent_id", "varchar,varchar,varchar", [{name:"TSERIES",code:"TSERIES",continent_id:"RENAULT"},{name:"MASTER",code:"MASTER",continent_id:"RENAULT"}])>
<cfset tblVoltage = queryNew("name,code", "varchar,varchar", [{name:"24 volt",code:"MASTER"},{name:"12 volt",code:"TSERIES"}])>
<cffunction name="getContent" access="remote" returntype="query" output="true">
<cfargument name="strTableName" type="string" required="true">
<cfargument name="strID" type="string" required="true">
<cfargument name="strName" type="string" required="true">
<cfargument name="intDistinct" type="numeric" required="false" default="0">
<cfargument name="selectedCol" type="string" required="false" default="0">
<cfargument name="selectedID" type="string" required="false" default="0">
<cfquery name="qryContent" dbtype="query">
select
<cfif arguments.intDistinct eq 1>distinct</cfif>
#arguments.strID# as theID,
#arguments.strName# as theValue
from #arguments.strTableName#
<cfif arguments.selectedID neq 0>
where #arguments.selectedCol# = '#arguments.selectedID#'
</cfif>
order by #arguments.strName#
</cfquery>
<cfreturn qryContent />
</cffunction>
</cfcomponent>
When I try and create the query using this method, nothing appears to work. I am looping through the database (from a query) and then creating a string using the required structure and the passing it to the function.
<cfcomponent>
<cfset XSTATIC = ""/>
<cfquery name="NOXVehicleModels" datasource="EBSNOX" >
SELECT DISTINCT VehicleMake
FROM [dbo].[NOX-Master]
WHERE VehicleMake IS NOT NULL
</cfquery>
<cfloop query="NOXVehicleModels">
<cfset XSTATIC = XSTATIC & "{name:'" & #Trim(NOXVehicleModels.VehicleMake)# & "',id:'"& #Trim(NOXVehicleModels.VehicleMake)# & "'},"/>
</cfloop>
<cfset XLEN=LEN(#XSTATIC#)/>
<cfset XSTATIC = MID(XSTATIC,1,XLEN-1)/>
<cfoutput>#XSTATIC#</cfoutput>
<cfset tblMake = queryNew("name,id", "varchar,varchar", [#XSTATIC#])>
I have created a separate cfoutput to test the string for structure etc and it appears to be correct, but it is just not passing to the querynew function. This is what the output looks like:-
{name:'CUMMINS',id:'CUMMINS'},{name:'DAF',id:'DAF'},{name:'IVECO',id:'IVECO'},{name:'MAN',id:'MAN'},{name:'MERCEDES',id:'MERCEDES'},{name:'RENAULT',id:'RENAULT'},{name:'SCANIA',id:'SCANIA'},{name:'VOLVO',id:'VOLVO'}
{name:'RENAULT',id:'RENAULT'},{name:'RENAULT',id:'RENAULT'},{name:'RENAULT',id:'RENAULT'}
What I have done so far:-
I have checked that the quotes are not important i.e. single/double.
I have tried to build the query outside of the tag.
Again, all appears (?) to be in order and I cannot understand that could be the problem. Possibly the structure is missing something before parsed to the function?
Any help would be greatly appreciated.
Thanks,
Jack
I'm currently attempting to migrate my site from Adobe Coldfusion 10 to Lucee 4.5.1.
I'm getting the following error: key [TITLE] doesn't exist.
The code I was using was:
<cfset variables.title = ress.title.welcome>
The code that I need to fix the issue seems to be:
<cfset variables.title = ress["title.welcome"]>
I'm using JavaRB and loading a properties file (onRequestStart()) and setting it to the variable ress.
<cfset ress = utilObj.getResourceBundle()>
Is there an alternative other than going through my code to fix all the references? Is there a setting in the server to exhibit the old behavior?
Update #1
Properties files looks like this:
# #comment
title.welcome=Content here
Update #2
This currently works on CF10 Developer on Windows 2008 R2 and CF10 on my shared host which is also Windows Server. I will also acknowledge that this is old code :)
JavaRB returns a structure from the content of the file:
var resourceBundle=structNew(); // structure to hold resource bundle
...
<cfreturn resourceBundle />
Partial CFC and method calls...
<cfcomponent name="utils" output="false">
<cfset this.ress = "">
<cffunction name="init">
<cfscript>
this.ress = loadResourceBundle();
</cfscript>
<cfreturn this>
</cffunction>
<cffunction name="loadResourceBundle" access="public" output="true">
<!--- Get javaRB --->
<cfinvoke component="#application.cfcPath#.javaRB" method="init" returnvariable="rb">
</cfinvoke>
<cfscript>
rbFile = GetDirectoryFromPath(expandpath("/resources/")) & "mgs.properties";
</cfscript>
<cfreturn rb.getResourceBundle("#rbFile#")>
</cffunction>
...
</cfcomponent>
<cfcomponent displayname="javaRB" output="no">
<cffunction access="public" name="init" output="No">
<cfscript>
rB=createObject("java", "java.util.PropertyResourceBundle");
fis=createObject("java", "java.io.FileInputStream");
msgFormat=createObject("java", "java.text.MessageFormat");
locale=createObject("java","java.util.Locale");
</cfscript>
<cfreturn this>
</cffunction>
<cffunction access="public" name="getResourceBundle" output="No" returntype="struct" hint="reads and parses java resource bundle per locale">
<cfargument name="rbFile" required="Yes" type="string" />
<cfargument name="rbLocale" required="No" type="string" default="en_US" />
<cfargument name="markDebug" required="No" type="boolean" default="false" />
<cfscript>
var isOk=false; // success flag
var keys=""; // var to hold rb keys
var resourceBundle=structNew(); // structure to hold resource bundle
var thisKey="";
var thisMSG="";
var thisLang=listFirst(arguments.rbLocale,"_");
var thisDir=GetDirectoryFromPath(arguments.rbFile);
var thisFile=getFileFromPath(arguments.rbFile);
var thisRBfile=thisDir & listFirst(thisFile,".") & "_"& arguments.rbLocale & "." & listLast(thisFile,".");
if (NOT fileExists(thisRBfile)) //try just the language
thisRBfile=thisDir & listFirst(thisFile,".") & "_"& thisLang & "." & listLast(thisFile,".");
if (NOT fileExists(thisRBfile))// still nothing? strip thisRBfile back to base rb
thisRBFile=arguments.rbFile;
if (fileExists(thisRBFile)) { // final check, if this fails the file is not where it should be
isOK=true;
fis.init(thisRBFile);
rB.init(fis);
keys=rB.getKeys();
while (keys.hasMoreElements()) {
thisKEY=keys.nextElement();
thisMSG=rB.handleGetObject(thisKey);
if (arguments.markDebug)
resourceBundle["#thisKEY#"]="****"&thisMSG;
else
resourceBundle["#thisKEY#"]=thisMSG;
}
fis.close();
}
</cfscript>
<cfif isOK>
<cfreturn resourceBundle />
<cfelse>
<cfthrow message="#e.message#" detail="#e.detail#" type="#e.type#" />
</cfif>
</cffunction>
...
</cfcomponent>
Update #3
FWIW, I used the Eclipse IDE and did a find replace using a regex and replaced it with a value...
regex: ((ress\.){1}(([a-z\.])+))
value: ress["$3"]
Update #4
So, using Lucee and MySQL, table names are case sensitive!?
Welcome to Adobe ColdFusion, where syntactical mistakes are not punished immediately.
<cfset ress = { "title.welcome": "Content here" }>
<cfoutput>#ress.title.welcome#</cfoutput>
<!---
>> outputs "Content here" in Adobe ColdFusion
>> throws an exception in Lucee/Railo
--->
The behavior in Adobe ColdFusion is misleading and plain wrong. "title.welcome" is a key that is supposed to be put in the struct ress. Instead the key is split into two structs with the keys "title" and "welcome", linked to each other and then put into the struct ress.
Your only chance to fix this issues is by adapting your getResourceBundle function. Here you need to refactor the lines with resourceBundle["#thisKEY#"] so that thisKEY creates a struct chain.
I am currently checking all my functions and components for unscoped variables. I am using a tool called varscoper4 to check all functions. Given the following code varscoper tells me that the variable "input" at line 4 in unscoped. Is this true and do i need to scope the argument variable if I alter it?
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<Cfset input = 3>
<cfreturn input>
</cffunction>
FYI if I do not alter the argument variable input in the function varscoper4 does not report any unscoped variables.
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<Cfset var output = 3 + input>
<cfreturn output>
</cffunction>
In your fist code block, input is "unscoped" but CF interprets it as arguments scope. CF will always try to find your unscoped variables by looking through a priority order. You can find more information on that here: http://www.learncfinaweek.com/week1/Scopes/
You can also view for yourself what that looks like by dumping the different scopes and seeing the output.
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<cfset input = 3>
<cfdump var="#variables#" label="variables">
<cfdump var="#arguments#" label="arguments">
<cfdump var="#local#" label="local">
<cfreturn input>
</cffunction>
I would strongly encourage you to take the output of your varscoper tool as a guide to where you should explicitly scope your variables. In that case, your first block of code would look like this. This is for clarity and certainty in your code.
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<cfset arguments.input = 3>
<cfdump var="#variables#" label="variables">
<cfdump var="#arguments#" label="arguments">
<cfdump var="#local#" label="local">
<cfreturn arguments.input>
</cffunction>
Personally, I don't like setting or changing arguments in my functions and methods. I'd rather keep them unadulterated as you have in your second block of code. But even there, I would explicitly scope the arguments so that you know where it came from -- even if not flagged by varscoper
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<cfset var output = 3 + arguments.input>
<cfdump var="#variables#" label="variables">
<cfdump var="#arguments#" label="arguments">
<cfdump var="#local#" label="local">
<cfreturn output>
</cffunction>
Last thing to be added here if it's not clear is that var scoping puts everything int he local scope. You could also do this and it would be functionally equivalent to the previous block of code:
<cfoutput>#testit(1)#</cfoutput>
<cffunction name="testit">
<cfargument name="input">
<cfset local.output = 3 + arguments.input>
<cfdump var="#variables#" label="variables">
<cfdump var="#arguments#" label="arguments">
<cfdump var="#local#" label="local">
<cfreturn local.output>
</cffunction>
You should use arguments.input:
<cfset arguments.input = 3>
Although even better would be to use your second example, with the arguments scope:
<cfset var output = 3 + arguments.input >
Don't modify arguments, leave them as they are when they arrive, incase you want to re-use the original value later on.
http://help.adobe.com/livedocs/coldfusion/8/htmldocs/help.html?content=buildingComponents_29.html
I have a web form which uses the action attribute to call a CFC like this:
<form action="mycfc.cfc?method=registeruser">
The CFC processes the data in the form and then I want it to return a variable telling the user if their form submission has been successful or not.
So within my CFC, I put this:
<cffunction name="registeruser" access="remote" hint="registers a new user" returnformat="JSON">
... PROCESSES FORM HERE THEN...
<cfset Msg = 'Success'>
<cfreturn Msg>
<cflocation url = "/registrationpage.cfm">
</cffunction>
How do I display the Msg variable in the registrationpage.cfm page? My output is set to JSON so I guess I have to DeSerialize but I have no idea how to actually reference/access this output from the method.
My whole answer is for educationnal purposes only and I strongly advise you to use an existing framework rather than reinventing the Wheels. Have a look at Picking a ColdFusion MVC Framework
You can store the value in the session scope. A lot of frameworks does it using a flash memory concept, which is a temporary memory (implemented as a struct) that destroys members when accessed.
Have a look at http://cfwheels.org/docs/1-1/chapter/using-the-flash it's quite straight forward to implement an API that does this.
Client code could look like (depending on your implementation):
<cfset session.flash.set('importantMsg', 'some important msg')>
<cflocation ...>
Then from the other page:
<cfif session.flash.has('importantMsg')>
<!--- The following line should also destroy the 'importantMsg' key --->
#session.flash.get('importantMsg')#
</cfif>
Here's an implementation example (not that the implementation is not thread-safe):
FlashMemory.cfc
<cfcomponent>
<cffunction name="init" returntype="FlashMemory">
<cfset variables.instance = {flash = {}}>
</cffunction>
<cffunction name="set" returntype="void">
<cfargument name="key" type="string" required="true">
<cfargument name="value" type="any" required="true">
<cfset variables.instance.flash[arguments.key] = arguments.value>
</cffunction>
<cffunction name="get" returntype="any">
<cfargument name="key" type="string" required="true">
<cfset var v = variables.instance.flash[arguments.key]>
<cfset structDelete(variables.instance.flash, arguments.key)>
<cfreturn v>
</cffunction>
<cffunction name="has" returntype="boolean">
<cfargument name="key" type="string" required="true">
<cfreturn structKeyExists(variables.instance.flash, arguments.key)>
</cffunction>
</cfcomponent>
onSessionStart
<cfset session.flash = new FlashMemory()>
Also please note that in your case, your remote CFC methods shouldn't return anything. You will use the flash memory to pass data around instead. That means when the method has finished it's work you can simply redirect the client.
You probably shouldn't use remote CFC methods in this particular case:
I have never really used remote CFC methods as stateful web services. The various advantages of remote CFC methods like their ability to spit out data in multiple data-interchange formats (JSON, WDDX...) is lost with your implementation.
You could simply do something like:
registration.cfm
<cfset errors = session.flash.get('registrationErrors')>
<cfif arrayLen(errors)>
<!--- Display errors --->
</cfif>
<form method="post" action="register.cfm">
...
</form>
register.cfm
<cfset registration = new Registration(argumentcollection = form)>
<cfset validator = new RegistrationValidator(registration)>
<cfif validator.validate()>
<cfset application.userService.register(registration)>
<!--- You can also redirect to a page that represents the correct state --->
<cflocation url="registered.cfm" addtoken="no">
<cfelse>
<!--- Store the errors collection in the flash memory --->
<cfset session.flash.set('registrationErrors', validator.errors())>
<!--- Redirect to the page the user came from --->
<cflocation url="#cgi.http_referer#" addtoken="no">
</cfif>
Take the cflocation tag out of your function. It will not execute anyway because it's after the cfreturn tag.
Also, post your form to a .cfm page, not the .cfc. From that .cfm page, do this:
<cfset MyObject = CreateObject(stuff for your cfc goes here)>
<cfset MessageFromFunction = MyObject.registeruser()>
<cfoutput>#MessageFromFunction</cfoutput.
I have a CFC file which handles all of the emails I'm sending form an application (using Coldfusion8).
I was using CFINVOKE to call the respective function inside this CFC and passed a struct with all user data along like so:
<cfscript>
var User.data = {};
User.data.name = "John Doe";
User.data.email = "john#doe.com";
...
</cfscript>
// call mailer
<cfinvoke component="mailer_user" method="say_hi">
<cfinvokeargument name="userData" value="#User.data#">
</cfinvoke>
And inside my mailer.cfc
<cffunction name="say_hi" access="public" output="false">
<cfargument name="userData" type="struct" required="true" />
....
For some reason this now fails and I can only get it to work if I pass fields seperately as cfargument, which is a a pain, since I'm passing a lot of data.
Question:
How can I get this to work using argumentCollection.
Even if I CFINVOKE like this:
<cfinvoke component="mailer_user" argumentcollection="#User.data#" method="say_hi"></cfinvoke>
it still doesn't do a thing. I'm setting output flags right before the cfinvoke and after, as well as inside the "say_hi" function going in and out. I'm only getting the flag before CFINVOKE.
Side note: This is all done through AJAX and I'm only getting back success="false" if my CFC has an error somewhere. I only work remotely on the system, so I can't set AJAX debugging in CFADMIN
As I typed the comment above it occurred to me what the problem is likely to be.
You are passing in a structure to your function. You pass User.data which has name,email,blah,etc as keys in that structure. Those keys need to match the arguments in your function
<cffunction name="say_hi" access="public" output="false">
<cfargument name="name" type="struct" required="true" />
<cfargument name="email" type="struct" required="true" />
<cfargument name="blah" type="struct" required="true" />
<cfargument name="etc" type="struct" required="true" />
If you want to pass in the structure as a argument, you would need to have a user.userData as your structure of user data and your function should be
<cffunction name="say_hi" access="public" output="false">
<cfargument name="userData" type="struct" required="true" />
When you pass the collection as argumentCollection you should do argumentCollection="#user#", so that the userData part matches your cfargument in the function.
Clear as mud?
I think you should stay in cfscript style by writing
// call mailer
mailUser = createObject("component", "mailer_user"); // or new mailer_user(); for CF9+
mailUser.say_hi(User.data);
That should work, if it doesn't, it's somewhere else in your code. Try looking at the error log.
You should map the variable to the data you pass, then no problem sending a struct. Do it this way
<cfset objMailer = createObject("component","mailer_user") />
<cfset objMailer.say_hi(userData:user.data)/>
This works even in CF7.
Ok. There was a typo inside my mailer CFC, where I had a variable with "##". As is was inside my email text
it went unnoticed...
So you can pass a struct allright using this:
<cfinvoke component="mailer_user" method="say_hi">
<cfinvokeargument name="userData" value="#User.userdata#">
</cfinvoke>
and grab it inside your called function like so:
<cffunction name="say_hi" access="public" output="false" hint="">
<cfargument name="userData" type="struct" required="true" hint="user data passed" />
<cfscript>
var internalInfo = "";
var User = {};
User.userdata = userData;
</cfscript>
...
Maybe someone else can use the snippet.