Question

Execute code stored in database?

Asked by: econosource

Hi,

Is there a coldfusion function that will allow me "include" cfml code for execution within a page?

I have a database with CFML templates stored in it I have another  page that looks up the right template in the database then displays it. How can i have thecode stored within the database execute along with the lookup page exactly the way an cfinclude would work but instead of  specifying a template file, specifying a variable?

thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-04-22 at 10:27:20ID20592663
Tags

coldfusion

,

database

,

execute

,

stored

Topics

ColdFusion Application Server

,

ColdFusion Studio

Participating Experts
8
Points
500
Comments
27

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. CFINCLUDE equivalent for HTML only
    Hi, Is there CFINCLUDE equivalent tag that would include some html file, but would not process any CFM? Basically I allow users to save files using my interface. Then on my page I have the following structure: .....my code (necessary)...... <cfinclude template="us...
  2. cfinclude problem
    I'm checking to see if a user's session has expired, if it has sending them to the login page... nice and easy. Except that when a user is in a subdirectory the server is looking for login.cfm in that folder. <cfif NOT IsDefined("SESSION.UserID")> <!--...
  3. CFML from MSSQL
    Reader; My website is one page that is essentially a template and each link throughout the site specifies an ID number which corresponds to the ID number of a page on MSSQL. When the page reloads the requested information is pulled and the viewer thinks their on a different...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: danrosenthalPosted on 2003-04-22 at 12:33:23ID: 8375770

You could write the variable to a file (CFFILE) and then include that file. I am not sure this is the best method, especially if you are using these database templates frequently. You would also have to somehow guarantee that the temporary pages would not overlap between 2 simultaneous users, either by uniquely naming each temporary file, or by managing their use through a database table.

 

by: rebiesPosted on 2003-04-22 at 15:26:51ID: 8376808

If its just a variable your inserting, you can simply do the following..

#Evaluate(QueryName.VariableToInput)#

If there is more then one variable on the template your best bet would be to write the template to the hard drive, include it, then delete it to clean up after yourself.  If you go this route it will help to have a 7200 RPM hard drive, if not a 10K or 15K SCSI drive.

<cfset UniqueFileName="#CreateUUID()#.cfm">
<cffile action="write" file="c:\#UniqueFileName#" output="#QueryName.TemplateToUse#">
<cfinclude template="#UniqueFileName#">
<cffile action="delete" file="c:\#UniqueFileName#">

Another idea is to use a RamDrive as the temporary storage means.  I prefer RamDiskNT and it essentially puts a portion of your memory into a virtual disk, thus giving you near immediate access to that information.

 

by: TallerMikePosted on 2003-04-22 at 15:28:46ID: 8376818

I had a similar problem where I had a piece of text that was stored in the DB, and in that piece of text users were allowed to put a symbol like so:

"Welcome #Name# to my website!"

And I would fill in the #Name# portion on the text dynamically later. But when I returned the string from the DB, it would have the variable #Name# in it, but Cold Fusion would simply ignore it of course as it would consider it a piece of text.

What I ended up doing was to simply replace all instance of "#Name#" with Evaluate("Name"). You could setup a Regular Expression to do this dynamically.

Now this worked for me because the code that was in the DB simply had some variables in it that needed to be processed. I don't think that there would be a way to process something like a CFLOOP within the code.

I don't think there is a viable solution to that. Creating and uniquely naming temporary files will work, but then what was the point of putting it in the DB anyhow since it's jsut going to get written to a file anyhow. You best bet might be instead to just create a bunch of files with some naminc convention, and store the location of these files in the DB rather than the actual code itself. Then when you do the CFINCLUDE, simly get the URL from the DB and CFINCLUDE the file.

 

by: rebiesPosted on 2003-04-22 at 15:42:31ID: 8376878

TallerMike:

Yes, I have done that before too.  The only problem I saw with that was when I would be replacing multiple variables through a large template, it was not all that speedy.  (I was looping through something like 100 variables to replace)

One other thing to note is if you save files to the hard drive you will not want users (IE non-admin) writing the templates.  Otherwise they could put some very damaging code in there and comprimise your system.  If users are creating the templates you *must* go through the code to make sure they don't have access to most Cold Fusion functions.

 

by: TallerMikePosted on 2003-04-22 at 17:30:43ID: 8377204

rebies, this is true, it is a VERY slow process for either large templates or a large number of replaces. Especially if both cases. But it works if all you need to do is replace some variables like MailMerge (basically what I used it for).

 

by: anandkpPosted on 2003-04-22 at 22:14:27ID: 8377972

yes a combination of "#" / "##" / Evaluate() / Evaluate(De())

shld see thigns for u !

the process depends on how u code it .... & what methodologies u follow !

K'Rgds
Anand

 

by: dash420Posted on 2003-04-23 at 02:35:22ID: 8378799

it is not clear what database return. whether it is return string of the template or template name. if it string the write one cfm file with this string. and use this file name in the cfinlude.

<cffile action="write" file="c:\<file_name>" output="#queryname.TemplateToUse#">
<cfinclude template="#file_name#">


if it is returning the template name

<cfset myTemplate = queryname.template_name>
<cfinclude template="#myTemplate#">

 

by: econosourcePosted on 2003-04-23 at 05:56:39ID: 8379692

thanks everyone for your comments up until now I am getting the source for the DB and writing it to a file.I then Include that file, then delete it afterwards. The problem here is that the file you include hasa to be recompiled by ColdFusion on each page view and therefore resulting in slow page views.


Dash420,

I'm not sure what you are suggesting by your post can you please be more clear, thanks.

 

by: econosourcePosted on 2003-04-23 at 05:59:48ID: 8379713

anandkp,

I am not sure what you are suggesting?

The source that I am drawing from the database is a complete cfml page with HTML and CFML code embeded in it.

 

by: anandkpPosted on 2003-04-23 at 06:08:50ID: 8379789

show me the code that goes in teh DB & i'll explain it out !

give me a example with variables that have to be executed on the fly [in a loop] - thru includes etc ...

 

by: TallerMikePosted on 2003-04-23 at 06:28:44ID: 8379941

econosource, realistically....you can't do this. If your page had something like this in it:

"Welcome #Name# to my website!"

You could simply call a replace function like so:

#Replace(DBString,"##Name##",Name)#

Which will replace all of the #Name# variables in the string with the variable value Name. You could convert this to a regular expression which would replace all strings that are surrounded with # signs, with the Evaluation of what is between the pound signs.

I believe what anand is trying to point our is that if you converted the above string to something more like the next example, you could simple use Evaluate on the whole string:

#DE("Welcome ")##Name##DE(" to my website!")#

DE prevents the Evaluate function from attempting to Evaluate those strings. Really it's supposed to be used to delay the evaluation of strings so that if you were going to re-evaluate an evaluated string, the second evaluation would evaluate the strings that were in the DE block. (follow?). Not there is any reason they can't be used here.

Again, this is going to be VERY slow and heavy on the processor. Not to mention, if you had something like CFLOOP in your code, there will be NO way to evaluate this. Evaluate will NOT evaluate a Cold Fusion tag. You may however be able to evaluate CFSCRIPT possible. I haven't tried converting a CFLOOP into a CFSCRIPT loop.

****************************************************************************************
****************************************************************************************

Anyhow, onto something more important. Your comments:

"The problem here is that the file you include hasa to be recompiled by ColdFusion on each page view and therefore resulting in slow page views."

I'll tell you right now, if this is the problem, then storing the CFML in the Database and trying to evaluate it on the fly is NOT going to speed up this process in the slightest. Infact, I would be willing to say it will be much slower. Evaluate is a slow function that should be avoided at all costs, and if your only solution involves Evaluating a large amount of CMFL, then I'd say you're going down the wrong path.

I really don't see why you don't just write all of the CFML to the server and leave it there, then just store the location of the file in the DB. And then just get the location from the DB and do a CFINCLUDE. If users need to modify these files, then simply allow them to open the file and modify it instead of pulling the CFML from the DB. I just don't see any reason to store it in the DB other than to have it centrally located. Really, storing data like that in the DB is expensive. Especially if the field type that is storing these values is 'Text'. It sounds like you're putting an unneccessary strain on BOTH your DB AND Cold Fusion server to achieve this.

Cold Fusion server will never cache the CFML that is coming from the DB, so there is no way that bringing it from the DB is going to increase in speed. And if you're already writing the file to the server, including it and then deleting it, why not just leave it? Then is will cache the page, (so long as you have enough memory) and everything should work fine.

If this doesn't work for you, we're going to need you to explain 3 things:

1). What kind of code are you storing in the DB, give us an example (I know anand already requested this, just reiterating).

2). Is someone modifying this CFML every so often, or is it just stored in the DB so it can be pulled out (but never modified).

3). WHY are you storing it in the DB? And WHY can't you simply store the location of the file on the server instead?

 

by: dash420Posted on 2003-04-23 at 06:31:59ID: 8379967

Time is taking in writing file. Every coldfusion file needs to complie when it is request.

 

by: TallerMikePosted on 2003-04-23 at 06:49:36ID: 8380104

dash420, Cold Fusion does cache the page in memory however, not the compiled version of it, just the CFML code so that it doesn't have to read the HD to get the CFML. If you had a large number of CFML files, lets say 50 Megs worth of them, and you had only set the file caching memory to 10 Megs, when it gets to the files that are NOT cached, the server will have to read from the HD to get the while, where as the cached files are already in memory. When you are creating temporary files to store the CFML that you pull from the DB, the server obviously will never cache these files as the file names will constantly change and the server will not be able to process them.

Even worse, the server may attempt to cache the file by putting it in memory when it reads the file. And in file caching, it's FIFO I would imagine, so if you did it enough, it would start to push your other files out of cache to make room for these temporary files that can never be read from cache again anyhow, thus making the other files on yoru system run slower because they may not be cached anymore.

 

by: dash420Posted on 2003-04-24 at 01:41:40ID: 8386904

TallerMike
if we cache the page. but contents of the page is not dynamic. then what will happen. my idea is cache the page where u know this static html. server no need to spend time in processing the page. but we can't take thsi risk where contents of the page is dynamic. Am i right?

regards,
Dash

 

by: econosourcePosted on 2003-04-24 at 05:39:54ID: 8388033

You are all right in what you say. The route I chose was to only store the dynamic pages to  include files and the rest just do a straight dump to the page. It works, but like anticipated page loads on dynamic pages is very slow.

 

by: anandkpPosted on 2003-04-24 at 05:54:15ID: 8388124

like i said, it all depends on ur requirements & how u code it .... & also what methodologies u follow !

:)

 

by: danrosenthalPosted on 2003-04-24 at 12:52:25ID: 8390923

I know this doens't really apply to anything any more, but here is a cool little script I made that parses out any variables surrounded by # signs...

<CFSET mystring="Hello, ##fname##, Today is ##day##">

Original String: <CFOUTPUT>#mystring#</cfoutput><BR>

<!--- Replacement Variables --->
<CFSET Fname="Bob">
<CFSET Day="Tuesday">

<CFLOOP condition="#REFIND("##{1}[^(## )]+##{1}",mystring)# neq 0">
     <CFSET y=REFIND("##{1}[^(## )]+##{1}",mystring)+1>
     <CFSET c="#MID(mystring,y,REFIND("##",mystring,y)-y)#">
     <CFPARAM name="#c#" default="">
     <CFSET mystring=REPLACENOCASE(mystring,"###c###",evaluate(c),"ONE")>
</cfloop>

Final String: <CFOUTPUT>#mystring#</cfoutput>

 

by: avatraxiomPosted on 2003-04-26 at 02:07:16ID: 8400302

Indeed, no matter what you do, the page loads will be slow.

It's a logical problem. Every time you load the page, the code will be dynamic, because you have code stored in the database. Either the code will have to be compiled as a separate file, or it will have to be compiled by the Evaluate() function.

One way or another, if you have uncompiled code, it's going to have to be compiled.

It's possible, though, that you could:

1) Throw the code you're going to store inside of a function.

2) Somehow compile the code manually (I'm not sure if the CF compiler is accessible, but perhaps it exists somewhere as a stand-alone executable in the system) and then save the compiled class file in the database as a binary field.

And then when you need to get the code:

3) Whip the code out of the database and save it in a random .class file

4) Instantiate the class file as a Java object.

5) Call the function in the instantiated Java object.

I'm not sure exactly if it would work, and I'm not sure of the details, but if you're in for an adventure this is probably the way to go. :-)

-M

 

by: avatraxiomPosted on 2003-04-26 at 02:09:26ID: 8400305

Oh, and I forgot to mention one detail of step 3:

You'd also have to wrap the code in <cfsavecontent>, so that you could return the code as a String from the function in the Java object.

-M

 

by: heathprovostPosted on 2003-05-05 at 23:22:50ID: 8468260

I would suggest the following method as a sort of compromise:

1. Continue storing the templates in the database as you are now. I say that assuming you have some alternate motive for doing this.

2. Add a field to the database to mark the record as "cached". A simple boolean field will do. Make sure that whatever code does the updating to your db always clears the cached flag whenever an update occurs. Records should be created with the cache flag set to false by default.

3. Create a "cache" directory which will be used to hold disk based versions of the templates from the db. You will need to create some form of naming scheme, ideally tied directly into the primary key the table with stores the template uses.

4. When a request is made for a template, first check the value of the cached flag. If it is false, then you write out the template to the cache folder and include it. But do not delete it, just leave it there. After writing it to disk, set the cached flag to true. On the next request when you check the flag it will be true (assuming no updates to the db have occured). So the logic is if the flag is true and a matching cache file is in the cache folder, you just include it, otherwise write out a new version using the data from the db and reset the flag to true. No need to re-read it from the db and it allows CF to treat it as a normal template.

I have left out error checking (you need to make sure of course the file actually exists before including it), locking, etc. But the basic approach should work and would be a decent compromise I think

Heath

 

by: TallerMikePosted on 2003-05-06 at 05:38:46ID: 8470518

What would be the advantage of doing that over simply writing the code to a file every time it's changed?

 

by: heathprovostPosted on 2003-05-06 at 11:15:01ID: 8473736

Well that is a matter if taste I guess. I personally prefer to have the logic that creates the cache files fired by the template doing the requests, rather than the template doing the updates.

The main reason is to allow you to treat the cache like it really IS a cache, i.e. its contents are temporary in nature and can be deleted at will with no side-effects.

If you only do the changes at update time, the disk based cache becomes "tied" to the state of the db. If for some reason cache files become deleted or something... The point is the requesting template needs to be capable of created the cache files _anyway_ in order to deal with problems like this, so you might as well have it do all the work.

You could of course do it both ways at once, I just dont like duplicating code like that.

Heath

 

by: TallerMikePosted on 2003-05-06 at 13:35:24ID: 8474703

Good call. I'll accept that.

I guess it depends on if these files are determined to be temporary or not.

Any of the the above solutions should work. One solution puts the processing time when the template is requested, and the other puts the time when the template is changed. The choice is yours.

 

by: heathprovostPosted on 2003-05-06 at 18:27:47ID: 8476163

One other point I should mention considering I came into this discussion kind of late. I personally agree with TallerMike's earlier assessment. This is NOT the best way to go about doing this. It would be much more effecient to just store the templates as files on disk and link them to the db using the filename.

My comment was made specifically to address the situation where this is for some reason not possible, and the templates MUST be stored in the database for some reason. If this is the case, I would be interested in hearing the reason.

If you have any choice in the matter I would recommend changing your approach, there is simply no upside to storing the templates in the db, _especially_ if you are going to cfinclude them, since that requires them to be disk based at some point anyway.

Heath

 

by: substandPosted on 2003-07-31 at 18:20:42ID: 9045338

you still need help on this?

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...