ColdFusion ServerFile is undefined in CFFile - coldfusion

When I try to run the following code, I'm getting the error message: "Element SERVERFILE is undefined in CFFILE.". I've done this a million times. Can anyone see what I'm missing?
<cffile action="upload" fileField="fileField" destination="xxxx"
nameConflict="Overwrite" result="thisResult">
<cfoutput>#cffile.ServerFile#</cfoutput>

You are using the result attribute. So instead of cffile.serverFile, use thisResult.serverFile.
Result Lets you specify a name for the variable in which cffile returns the
result (or status) parameters. If you do not specify a value for this
attribute, cffile uses the prefix cffile. For more information, see
Usage.

Related

How can I confirm a cffile write is successful?

I am using cffile to create a new file or update an existing file, depending on what the user requested. The request comes through a form from the previous procedure, so the code involving cffile looks like this:
<cfset thefile = "#form.dyn#">
<cfoutput>
<cfsavecontent variable = "testvar">
#form.editor1#
</cfsavecontent>
<cffile action = "write"
file = "/var/www/reports/#thefile#.cfm"
output = "#testvar#">
</cfoutput>
When I am done writing to the file, I want to confirm to the user that this happened. For a new file I could use IsDefined to check that it is there. But I can't think of a way to check for an existing file that was updated. I considered a try/catch on the cffile, but the catch operates only if nothing seems to go wrong. If I don't get an error on the catch, can I assume everything is all right? I would prefer a direct check if possible. Does anyone have an idea?
If <cffile> doesn't work, it'll tell you by throwing an exception. If it doesn't do that, you can safely assume it has worked. Don't over-engineer your app.
You could use cfdirectory with the action="list" and filter="your-filename" to get the following information about the uploaded file:
If action = "list", cfdirectory returns the following result columns, which you can reference in a cfoutput tag:
name: Directory entry name. The entries "." and ".." are not returned.
directory: Directory that contains the entry.
size: Directory entry size.
type: File type: file, for a file; dir, for a directory.
dateLastModified: The date that an entry was last modified.
attributes: File attributes, if applicable.
mode: Empty column; retained for backward compatibility with ColdFusion 5 applications on UNIX.
Of interest to you is the dateLastModified column.
So you should be able to do something like:
<cfdirectory action="list" name="dirQuery" directory="C:/var/www/reports/" filter="#thefile#.cfm">
Then you can dump that result to see what information is available to you:
<cfdump var="#dirQuery#">
The dateLastModified column can be accessed like:
<cfoutput>#dirQuery.dateLastModified#</cfoutput>
Use CFDirectory to get the file's dateLastModified before you update the file and then again afterwards. If they are not the same, then it was updated.

create contain file log coldfusion

I want create a log file. I tried but its show me an error. Can anyone help? I show my full code here:
http://pastebin.com/SxAMCUnv
Please see this line. I don't know what happened with it, can output error:
<cffile action="WRITE" file="#expandpath('API.log')#"
output="#filecontent#" addnewline="Yes" fixnewline="No"
Edit: I tried and it showed me an error:
Invalid CFML construct found on line 213 at column 110. ColdFusion
was looking at the following text:
''
The CFML compiler was processing:
A cffile tag beginning on line 213, column 2.
The main error is in this line:
<cffile action="WRITE" file="#expandpath('Info.log')#"
output="#filecontent#" addnewline="Yes" fixnewline="No"
Please tell me what's happening?
A superficial glance at your code suggests you're trying to write out a variable fileContent, but at no point do you actually set that variable. Without seeing the error, there;s no way of knowing if that's the problem, or the variable is being created in code that you haven't included.
Another consideration is that you're re-inventing the wheel slightly here. ColdFusion has an inbuilt <cflog> tag or writeLog() statement for writing to log files.
=====
UPDATE (based on updates to the question)
That's a compile error you're getting, and the line that's erroring is not the line you indicated in your code (# pastebin), which is a bit odd. Can you confirm line 213 is that <cffile> line? And can you reproduce that line in its entirety (the snippet you quoted was incomplete). But basically the error message is telling you what's wrong: you have a syntax error in your code. It could be in the specific statement the error message says (line and column), although sometimes depending on the code, the CF compiler can get confused and a syntax error in a preceding line might be reported as being further down the file than it actually is. But for starters, post the whole line of code, not just the first bit of it.
comments tl;dr version -
This answer worked but asker began asking questions about the new error, he was urged to create a new question.
Answer:
I don't see this line in the link you posted (I searched for api.log). Invalid CFML construct typically means you have a syntax error, usually forgetting a closing quote, second pound, or closing your tag (greater than). If the below suggestion doesn't work, look above or below the line containing the cffile for a missing part of a closing pair.
The code you posted:
<cffile action="WRITE" file="#expandpath('API.log')#" output="#filecontent#" addnewline="Yes" fixnewline="No"
...does not have a closing greater than to close your tag. If that is your actual code, I would suspect that is the problem.
<cffile ... >
^^^ this is missing right here
If you're not going to take Adam's suggestion and use cflog (which you should), you also probably want action="append" or you will keep overwriting the file with the contents of fileContent.
==edit==
On a side note, this will not solve your problem but you should be using cfqueryparam, especially when using user entered data.
For example:
Select *
FROM Purchasers
WHERE PurchaserID = #PurchaserID#
Should be
Select *
FROM Purchasers
WHERE PurchaserID = <cfqueryparam cfsqltype="cf_sql_integer" value="#PurchaserID#">

Coldfusion: How to dump out arguments scope with cfthrow?

After my form submits I am calling a controller method that runs an orm EntitySave in my cfc. I would like to dump out the arguments before I save my data via ORM just to visually validate those are indeed the values I want to save in the database.
So when I use this
<cfthrow message="value = #arguments#">
I am getting this:
Error: Complex object types cannot be converted to simple values.
I understand you are not allowed to do this with complex objects, so in those cases I would use <cfdump> but I can't find a way to dump in a <cfthrow>. I am sure there is a better way to accomplish this. I have also tried doing a <cfmail> to myself which works amazingly but the email will take a minute or two. Any suggestions would be greatly appreciated. I am currently checking into ValidateThis.
You could serialise it:
<cfthrow message="value = #serializeJson(arguments)#">
But I don't think you want that sort of thing showing up on the screen.
I'd log it if I was you (so same notion, just <cflog> before the <cfthrow>, and put the arguments in the log entry, and in the <cfthrow> just put a brief explanation of the error (you should also use a TYPE attribute, for subsequent handling of the exception that you've raised.
Rather than throwing it, you could try dumping it to a file and see if that meets your needs:
<cfdump var="#arguments#" output="C:\dump.html" format="html">
If you need to abort (as a throw would do), you can add abort on to the end of the tag, <cfdump... abort>.
You could do the following in order to use <cfdump>:
<cfsavecontent variable="arguments_dump">
<cfdump var="#arguments#" />
</cfsavecontent>
<cfthrow message="#arguments_dump#" />
Takes a little bit more code however and is not as elegant as Adam Cameron's answer above.

Is it possible to download a file variable in coldfusion?

Using Coldfusion's SpreadSheet() object I have created an excel file and now the user needs to be able to download it.
mySS = SpreadsheetNew();
format1 = StructNew();
format1.color="dark_green";
format1.size="24";
SpreadSheetSetCellValue(mySS, 7,2,3);
SpreadSheetFormatCell(mySS, format1, 2, 3);
essentially I would like something like
<cfdownload var="#mySS#">
however it's almost never that simple. I realize that I can write the file and then use cfheader \ cfcontent however I am trying to avoid writing the file if possible.
Edit
Based on the suggestion I got from speshak I tried
<cfcontent variable="#mySS#" type="application/msexcel">
and the error I got was, am I missing something?
coldfusion.excel.ExcelInfo is not a supported variable type. The
variable is expected to contain binary data.
Alright so thanks to Raymond Camden's Post and speshak here is the final solution.
<cfheader name="Content-Disposition" value="attachment;filename=filename.xls">
<cfcontent variable="#spreadsheetReadBinary(mySS)#" type="application/msexcel">
Try:
<cfcontent variable="#mySS#">
You probably want to set the type attribute as well so the browser knows it's not HTML.

How do I force evaluation of a cfif stored in a string?

I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:
"RE: <cfif myData.general.legalName NEQ """"> {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s) {{docketString}}"
When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.
<cfsavecontent variable="subject">
<cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
I also tried
<cfsavecontent variable="subject">
<cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
And then I replace all the {{ }} with the appropriate values.
However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.
Any ideas?
The only way to dynamically evaluate code that you are creating at runtime is via writing it out to a file, and then executing it.
The easiest way would be to write it a .cfm page in the Virtual File System (probably name the file after a UUID, so it's unique), and then it where you need to run the contents.
I wouldn't normally advocate generating code at runtime like this, but it can be the most elegant solution in some cases.
As an alternative, instead of storing the CFML code in the database, you have a set of CFML email template files that get stored in a directory on your server, and in your database you simply record which template needs to be included either via cfinclude or cfmodule.
You can't dynamically evaluate CFML stored in a database without first writing it to file and then using <cfinclude> to include it.
Further to Mark's answer here is some psuedo code:
<cfset fileName = createUUID() & ".cfm">
<cfset fileWrite( fileName, [CODE_FROM_DB]>
<cfinclude template="#fileName#">
<cfset fileDelete( fileName )>
I have used code like this before with no problems. Anything in the Virtual File System flies as it is all run in RAM. For best practice do remember to delete the files created ;)
If you absolutely have to do this, look at the evaluate() function. This, essentially, fires up a new CF thread, compiles the string passed to it, runs it, and returns the result.
If at all possible, I would try to find a way to move your logic to the actual file being run, not the string from the database. I assume you are pulling the data based on some string you've already built, so you might consider appending something to it, so you are looking up subjectDotLegal and subjectDocketLegal or something similar.
Remember, evaluate() is slow, ugly, and can be dangerous (it will run anything passed to it!). If there's a way around it, I suggest you use it.
why not just use something like mustache?
http://mustache.github.com/
https://github.com/pmcelhaney/Mustache.cfc
it has the ability to not only do some of the logic that you want in your script dynamically. i really would suggest you check out the project and maybe even improve and contribute on it.
OH and just for the chance to be on a soapbox: I've been emailing Adobe for years saying that we need the ability to dynamically parse and render CFML. Sadly my cries have only gotten ignored. maybe if more people complained that this feature needs to be added, it would get the attention it deserves.
To give an example: Assume code.txt is a text file that contains the following (just to facilitate simulating CFML stored in a db): <cfoutput>#now()#</cfoutput>
The following code would work:
<cfset q = queryNew("code") />
<cfset queryAddRow(q,1) />
<cfset querySetCell(q, "code", fileRead(expandPath('code.txt')), 1) />
<cfdump var="#q#">
<cfset newCodeFile = expandPath('dynamic.cfm') />
<cfset fileWrite(newCodeFile, q.code[1]) />
<cfinclude template="dynamic.cfm" />
In OpenBlueDragon there is the render function, which can do this.
You can mimic this function in Railo by creating a custom built-in function that saves the file into RAM then cfincludes it, using the following code:
<cffunction name="render" output="Yes" returntype="string"><!---
---><cfargument name="Code" required="Yes" type="string"><!---
---><cfset local.mapping = {'/render_ram_resource':'ram://'}><!---
---><cfapplication action="update" mappings="#local.mapping#"><!---
---><cfset local.fileName = "/render_ram_resource/_render_" &
createUUID() & ".cfm"><!---
---><cffile action="WRITE" file="#fileName#"
output="#arguments.Code#"><!---
---><cfinclude template="#fileName#"><!---
---><cffile action="DELETE" file="#fileName#"><!---
---></cffunction>
(This looks unusual because it needs to allow output, but prevent extra whitespace, hence why all the comments. Unfortunately SO's syntax highlighting seems to be confused by them.)
If you need an ACF-compatible solution, you'll need to use the regular filesystem and a pre-created mapping. (Well, in ACF9 and above you can use the RAM virtual filesystem, but afaik you can't create mappings on the fly like this.)
There's a better way, namely using in memory files. This way you don't have any I/O on the disk and therefore much faster:
For tags that take logical path, define mapping in Administrator. Execute in-memory CFM pages using the cfinclude tag:
Create a mapping for ram:/// so that it can be used in the tags. In this example, /inmemory is the mapping that points to ram:///.
For tags that take absolute path, specify the syntax as provided in the following example:
You can also delete the file from the ram usinf cffile and action delete.
Here's how I stored my header and footers for all pages in a record. This code can go at the top of each page. But I have it in the APPLICATION.cfm and it seems to be working great.
The key here is not use #pound# signs on your expressions. User [square braces]. The code will pick them and evaluate them and return the result back to the template.
It will substitute the number 0 if it can not evaluate an expression as a means of error handling.
<CFSET FooterID=1234> <!-- ID of the record you want to use -->
<CFQUERY NAME="StoredHeader" Datasource="DS1">
Select Body from templates where id=#FooterID#
</CFQUERY>
<CFSET Parse=StoredHeader.Body>
<CFLOOP CONDITION="FindNoCase('[',Parse,1) GT 0">
<CFSET STB=FindNoCase('[',Parse,1)>
<CFSET ENB=FindNoCase(']',Parse,1)>
<CFIF ENB-STB GT 0>
<CFSET BracketExp=Mid(Parse,STB+1,ENB-1-STB)>
<CFTRY>
<CFSET BracketValue=Evaluate(BracketExp)>
<CFSET Parse=ReplaceNoCase(Parse,'['&BracketExp&']',Evaluate(#BracketExp#))>
<cfcatch type="any">
<div>'Using ZERO 0 for missing <cfoutput>#BracketExp#' </cfoutput> </div>
<CFSET Parse=ReplaceNoCase(Parse,'['&BracketExp&']','0')>
</cfcatch>
</CFTRY>
</CFIF>
</CFLOOP>
<CFSET Footer=Parse>
<cfoutput>FOOTER</cfoutput>
I would try the built-in QuoteName function.