Can CFThread, when wrapping over cfhttp, solves my Timeout error issue? - coldfusion

My application pulls lots of data from different applications according to the selected scopes. For e.g. Org level and SubOrg level scopes, this can cause to bring server down and everyday causes server crashing and timeouts.
So I wanted to know whether wrapping cfthread around my cfhttp will solve my timeout problem?
<cfinclude template="fundedScopes.cfm">
<!--- Call the funded scopes --->
<cfset dynVarName = "funded" & bizforShort>
<cfif structKeyExists(variables,dynVarName)>
<cfset howManyCustomScopes = listLen(structkeylist(variables[dynVarName],"|" ),"|" )>
<cfmodule template="#Request.Library.CustomTags.VirtualPath#Scheduler_LogDetail.cfm"
Step="Funded Level Cache" Detail="Custom Scopes to be cached: #howManyCustomScopes#"
LogData=""></cfmodule>
<cfloop collection="#variables[dynVarName]#" item="t">
<cfset tempurl = variables[dynVarName][t]["url"]>
<cfset tempurl = tempurl & "&retainCache=1">
<cfoutput>
<cfhttp url="#tempurl#" method="GET" resolveurl="false" timeout="3000">
#tempurl#<br>
<cfset scopesCachedCounter = scopesCachedCounter + 1>
<cfmodule template="#Request.Library.CustomTags.VirtualPath#Scheduler_LogDetail.cfm" Step="Funded Scopes Cache" Detail="#scopesCachedCounter#.- #t#" LogData="#tempurl#"></cfmodule>
</cfoutput>
</cfloop>
</cfif>

Related

trying to check for a session if itexist and has value

i am writing a code to check for session and session value and if they do not exists or exists but have empty value or 0, i want them redirected
here is my start
<cfset lstofSessionsToCheck = 'EmplyID,Username'>
<cfset st = {}>
<cfloop collection="#session#" item="i">
<cfset SetVariable("st.session.#i#",duplicate(session[i]))>
</cfloop>
<cfparam name="redirection" default="false">
<cfif session.Username eq ''>
<cfset redirection = true>
<cfelseif session.EmplyID eq ''>
<cfset redirection = true>
</cfif>
it is missing some checks here
check if session is defined before it checks its value
if its defined, its value should not be empty or 0 or -1
please guide,m i am almost near its end but stuck at that
session is a special scope in ColdFusion and either always or never exists. It depends on the state of the sessionManagement attribute in your Application.cfc (or Application.cfm/<cfapplication>). In case sessionManagement is false, accessing session will immediately throw an exception. I assume you are not seeing this error, so session management is enabled in your environment. That leaves you with checking if the session fields are initialized. Your new best friend is called structKeyExists().
<!--- username needs to exist and must not be empty --->
<cfset hasUsername = (
structKeyExists(session, "Username") and
(len(session.Username) gt 0)
)>
<!--- ID needs to exist, must be a number and > 0 --->
<cfset hasID = (
structKeyExists(session, "EmplyID") and
isNumeric(session.EmplyID) and
(session.EmplyID gt 0)
)>
<!--- if either username or ID is not properly set, do a redirect --->
<cfif (not hasUsername) or (not hasID)>
<cfset redirection = true>
</cfif>
You can simplify the last line to a single expression:
<cfset redirection = ((not hasUsername) or (not hasID))>
As for your usage of setVariable(): You should generally avoid this function (along with evaluate()) as they can be easily exploited and pose a security risk.
Rewrite:
<cfset st = {}>
<cfloop collection="#session#" item="i">
<cfset SetVariable("st.session.#i#",duplicate(session[i]))>
</cfloop>
to
<cfset st = {}>
<cfset st.session = {}>
<cfloop collection="#session#" item="i">
<cfset st.session[i] = duplicate(session[i])>
</cfloop>
(And by the way, i is actually a key here, not a numeric index. Only use i with a for loop.)
I'm not sure the best way to do this is by looping through the entire thing every time you check. Unless those values are coming from a database or something after authentication?
Typically, if you want to restrict access to a page, you would check the session scope using structKeyExists(), for just a couple specific things.
The code would look something like this:
<!---This code sees if the user is logged in at all. If they are missing important information, I clear the session scope and redirect them to the login page. --->
<cfif !structKeyExists(SESSION, 'Username')>
<cfset structClear(SESSION)>
<cflocation url="YourPageHere" addtoken="maybe">
</cfif>
<!---This code checks for a specific permission to be defined. If not, it stops or redirects the user.--->
<cfif structKeyExists(SESSION, 'CanEditUsers') AND SESSION.CanEditUsers eq 1>
<!---your code here--->
<cfelse>
<cflocation url="YourPageHere" addtoken="maybe">
</cfif>
This is only a rough example - but hopefully puts you on the right path. Let me know if anything is unclear or needs to be edited to better fit your situation.

Coldfusion set time out in .cfc page?

I have one .cfc that I use for all communication between client and server code. This cfc page has about 10 different function. Each function has different purpose and I have queries for Select, Insert, Update and Delete. I'm wondering if I should set timeout on the top of the .cfc page inside cfcomponent tag or this should be set inside of the each function or do I even need this? In our current system we have some many error messages like: The request has exceeded the allowable time limit Tag: CFQUERY.
I would like to prevent any similar error messages in my app. Here is example of my cfc page:
<cfcomponent>
<cfset currentDate = DateFormat(Now(),'mm/dd/yyyy')>
<cfset currentTime = TimeFormat(Now(),'hh:mm tt')>
<cfinvoke component="appEntry" method="getRecord" returnvariable="CHKAccess">
<cfinvokeargument name="user" value="userdata"/>
<cfinvokeargument name="app" value="myApp"/>
</cfinvoke>
<cfset adminAccess = false>
<cfset userAccess = false>
<cfif CHKAccess.RecordCount EQ 1>
<cfif CHKAccess.pd_hfmAccess EQ 'A'>
<cfset adminAccess = true>
</cfif>
<cfif CHKAccess.pd_hfmAccess EQ 'U'>
<cfset userAccess = true>
</cfif>
</cfif>
<cffunction name="getData" access="remote" output="true" returnformat="JSON">
<cfargument name="keyVal" type="string" required="true">
<cfset fnResults = structNew()>
<cfif userAccess>
<cfquery name="getRec" datasource="tes">
SELECT some columns
FROM Test
</cfquery>
<cfset fnResults.status = "200">
<cfelse>
<cfset fnResults.status = "400">
<cfset fnResults.message = "Invalid access attempt.">
</cfif>
<cfreturn fnResults>
</cffunction>
<!--- More functions below --->
</cfcomponents>
If anyone have suggestion what would be the best fix please let me know. Thank you.
You should set the requesttimeout in the method that contains that long-running cfquery.
You don't want to "punish" all methods for just one method. If you set it for all, how do you know which one is slow and which one is okay, unless you don't care?

Invalid Component Definition

I'm having an issue in the logs I cannot replicate on the browser. I'm getting hundreds of these per day
invalid component definition, can't find component [cfc.udf]
The cfc are stored in a cfc folder one level above the app. This is so that many apps can use the same cfc.
Folder structure:
---- cfc
--------- udf.cfc
---- myApp
--------- application.cfc
In the application.cfc, I'm using application-specific mappings because this is set on a lot of different load-balanced-servers in production as well as a QA environment and local testing environment and keeping them all synced would be difficult.
At onRequestStart, I have a function that restarts the application every 5 minutes. It was supplied by a consultant. I suspect that this is the culprit because the logs show these errors coming in at exactly 5 minute intervals
<cfcomponent>
<cfset This.name = "myApp">
<cfset This.Sessionmanagement=true>
<cfset This.Sessiontimeout="#createtimespan(0,0,30,0)#">
<cfset this.mappings['/cfc'] = ExpandPath('../cfc')>
<cffunction name="onApplicationStart">
<cfset Application.udf = createObject("component", "cfc.udf").init()>
</cffunction>
<cffunction name="onRequestStart">
<cfset appRefreshMinutes = 5>
<cfif Not IsDefined("Application.refreshTime")>
<cfset currentMinute = Minute(Now())>
<cfset Application.refreshTime = DateAdd("n", -(currentMinute MOD appRefreshMinutes)+appRefreshMinutes, Now())>
<cfset Application.refreshTime = DateAdd("s", -(Second(Application.refreshTime)), Application.refreshTime)>
</cfif>
<cfif Now() GTE Application.refreshTime Or IsDefined("URL.reload")>
<cflock name="ApplicationInit" type="exclusive" timeout="5" throwontimeout="false">
<cfif Now() GTE Application.refreshTime Or IsDefined("URL.reload")>
<cfset OnApplicationStart()>
<cfset Application.refreshTime = DateAdd("n", appRefreshMinutes, Application.refreshTime)>
</cfif>
</cflock>
</cfif>
</cffunction>
</cfcomponent>
Promoted from the comments
Have you tried using a mapping name other than /cfc? Like:
<cfset this.mappings['/somethingelse'] = ExpandPath('../cfc')>
so that you can then call it like:
<cfset Application.udf = createObject("component", "somethingelse.udf").init()>
Maybe it just looks odd to me or maybe that is causing your issue (cfc being a reserved word or somehow getting special treatment in this case).

Is there a way to get the list of all coldfusion scheduled tasks running on different web servers in same network?

I want to find out the details of scheduled tasks running on 5 or 6 coldfusion web-servers, by just writing a single page on one of them. Is there any way to do it?
It might be done by reading cron.xml on all of them.
I came across with following code
<cflock name="alltasks" type="exclusive" timeout="10">
<cfscript>
factory = CreateObject("java","coldfusion.server.ServiceFactory");
cron_service = factory.CronService;
services = cron_service.listALL();
</cfscript>
This code is good for finding out details for web server on which it will be executed.
I am looking for something similar to this, that will get me details of scheduled tasks running on all web-servers in same network. Thanks!!
You could use the cfschedule tag, and place a page on each server that outputs the scheduled tasks for that machine. You could then use an HTTP request to each server to pick up the tasks it's responsible for and output them to the page on your monitoring server.
<!--- ServerList contains all server's(7,8,9) ipaddress,,, --->
<cfset serverList = 'a.b.c.d, p.q.r.s, ....... , u.v.w.x'>
<cfoutput>
Searched In: #serverList#<br>
<Cfloop list="#serverList#" index="s">
<cfif FileExists('\\#s#\C$\ColdFusion8\lib\neo-cron.xml')>
<cfset pathToFindNeo = '\\#s#\C$\ColdFusion8\lib\neo-cron.xml'>
<cfelseif FileExists('\\#s#\C$\CFusionMX7\lib\neo-cron.xml') >
<cfset pathToFindNeo = '\\#s#\C$\CFusionMX7\lib\neo-cron.xml'>
<cfelseif FileExists('\\#s#\C$\ColdFusion9\lib\neo-cron.xml')>
<cfset pathToFindNeo = '\\#s#\C$\ColdFusion9\lib\neo-cron.xml'>
<cfelseif FileExists('\\#s#\ColdFusion\lib\neo-cron.xml')>
<cfset pathToFindNeo = '\\#s#\ColdFusion\lib\neo-cron.xml'>
<cfelse>
<cfset pathToFindNeo = 0>
</cfif>
<h3>#s# [#pathToFindNeo#]</h3>
<!--- Get the scheduler xml file. It's stored as WDDX in CFroot dir--->
<cfif pathToFindNeo neq 0>
<cffile action="Read" file="#pathToFindNeo#" variable="TaskXML">
<!--- Convert the WDDX to CFML - and array of structs --->
<cfwddx action="WDDX2CFML" input="#TaskXML#" output="GetTasks">
<table border="1" width="100%">
<tr>
<td><strong>Name</strong></td>
<Td><strong>URL</strong></Td>
<td><strong>Interval</strong></td>
<Td><strong>Disabled</strong></Td>
<td><strong>Start Date</strong></td>
<td><strong>Start Time</strong></td>
<td><strong>End Time</strong></td>
<td><strong>Operation</strong></td>
</tr>
<cfloop collection="#GetTasks[1]#" item="key">
<cfif GetTasks[1][key]['disabled'] eq 'NO'>
<tr>
<cfelse>
<tr style="background-color:##CCC">
</cfif>
<td>#key#</td>
<td>#GetTasks[1][key]['url']#</td>
<td>#GetTasks[1][key]['interval']#</td>
<td>#GetTasks[1][key]['disabled']#</td>
<td>#GetTasks[1][key]['start_date']#</td>
<td>#GetTasks[1][key]['start_time']#</td>
<td>
<cfif StructKeyExists(GetTasks[1][key], "end_time")>
#GetTasks[1][key]['end_time']#
<cfelse>
-
</Cfif>
</td>
<td>#GetTasks[1][key]['operation']#</td>
</tr>
</cfloop>
</TABLE>
<CFELSE>
FILE 'neo-cron.xml' NOT FOUND
</cfif>
</Cfloop>
</cfoutput>
What I would probably do is create a cfc on the destination server, that would return the results from the lookup of scheduled tasks into some kind of json, xml, or query that would be available with a set username & password to get the data from 1 server to another, as needed....
The way we take care of this is to add a line to a database table with the URL of the task. If you have all your tasks in the one directory the best way to do this is add the database logging in Application.cfc using the available CGI variables.
This can then be checked against what you expected to run.
Hope that helps!

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.