Accessing Component Object in ColdFusion - coldfusion

I created a component object like this in page1.cfm, to call one of the cfc's functions: IsDigits:
<CFSET MyObj = New cfcomponents.MyComp.RecordValidation(Trim(session.userid)
,Trim(session.yr))>
<CFSET MyObj.IsDigits(st_SSN_and_BDates)>
After page1.cfm is finished processing, it goes to page2.cfm using:
<script>
window.location="page2.cfm
</script>
(I can't use cflocation because of cfflush that I use on almost every page).
In page2.cfm, I still need to call different functions that exist in the RecordValidation.cfc. I'm wondering if I have to run
<CFSET MyObj = New cfcomponents.MyComp.RecordValidation
... one more time?

There's no limit to how many times one can create objects. If you need another one in the next request... create another one!
Do you perhaps need to elaborate on the problem you're perceiving you're having, so we can give you a more exacting answer?
Also perhaps look into using something like DI/1 or WireBox to manage your objects more strategically? It depends on your requirements as to whether something like that will help you.

Related

Verify if a method of an object exists

I'm calling a web service through ColdFusion which returns an object, and I want to verify if one of the methods of this object exists as it won't always exist.
I found this source which seemed promising however based on my tests I can see the results are always negative and the method is never found when it's clearly there.
<cfif structKeyExists("#Result.getNotifications().getValidationResult(0)#","getField")>
Result is my underlying object, and my end goal is to verify if the method getField() exists.
Is there a clean way to do this as opposed to a try/catch?
Update:
Unfortunately, I am not sure IsInstanceOf() works with web services, due to the fact that CF uses a Proxy object to "wrap" the underlying web service class. If not, another simple option is to check class name. That avoids the ambiguity of checking for method name only (which could potentially exist in many different classes). Plus I suspect it may be more light-weight than IsInstanceOf() anyway.
<cfif compare(yourObject.getClass().name, "org.tempuri.ValidationResultField") eq 0>
Found ValidationResultField. do something
</cfif>
It looks like the dump contains several different types of objects/classes: ArrayOfValidationResult, ValidationResultField, etecetera. It sounds like what you are really trying to determine is which of those classes you are working with, so you know exactly what fields and methods will be available, per the web service definitions. Given that, I think IsInstanceOf() would be a more appropriate test, than checking for method names. More accurate as well. Nothing prevents two different classes from having the same method name. So even if method X or Y exists, there is still a possibility it may be a different class than expected.
<cfif IsInstanceOf(yourObject, "org.tempuri.ValidationResultField")>
do something
</cfif>
As far as I know, the mentioned structKeyExists approach only works if CF wraps the class internally, e.g. all instances of cfcomponent.
The only option left is to actually reflect the class:
<cftry>
<cfset Result.getNotifications().getValidationResult(0).getClass().getMethod("getField", javaCast("null", ""))>
<!--- method does exist --->
<cfcatch type="coldfusion.runtime.CfJspPage$UnsupportedBaseTypeException">
<!--- method does not exist --->
</cfcatch>
</cftry>
If the method doesn't exist, it throws UnsupportedBaseTypeException, which seems to be a follow-up of NoSuchMethodException.
Honestly, you might as well just invoke the method and catch it. Reflection comes with an additional overhead and you have to catch it anyway.
Like Miguel-F, I think this is something for getMetadata(). The following should return an array containing the respective functions of the object:
<cfset funcs = getmetadata(nameOfObj).functions>
The names of the functions are then funcs[1].name, funcs[2].name, and so on.
In general, you may obtain the metadata of all the functions of a webservice, given the URL of the WSDL, with something like
<cfhttp method="get" url="http://www.webservicex.net/globalweather.asmx?WSDL" result="res">
<cfset wsXml=xmlparse(res.filecontent)>
<cfset wsOperations = xmlsearch(wsXml,"//wsdl:operation")>
<cfdump var="#wsOperations#">
Another method you could look at (perhaps undocumented) is to get the method names from the class names in the stubs directory.
The code to run is:
<cfscript>
wsargs = structnew();
wsargs.savejava="yes";
</cfscript>
<cfset convert=createobject("webservice","url_of_wsdl",wsargs)>
Then figure out how to fish out the names from the stubs directory, {CF_INSTALL}/stubs. In my case, CF_INSTALL is C:/ColdFusion2016/cfusion/

What's the correct way to allow different ColdFusion CFC's to instance each other?

I have a “best-practices” question in regards to the correct way to instance CFCs that all need to talk to each other in a given project.
Let’s say for example you have a web application that has a bunch of different modules in it:
Online Calendar
Online Store
Blog
File Manager (uploading/downloading/processing files)
User Accounts
Each of these modules is nicely organized so that the functions that pertain to each module are contained within separate CFC files:
Calendar.cfc
Store.cfc
Blog.cfc
Files.cfc
Users.cfc
Each CFC contains functions appropriate for that particular module. For example, the Users.cfc contains functions pertaining to logging users on/off, updating account info etc…
Sometimes a CFC might need to reference a function in another CFC, for example, if the store (Store.cfc) needs to get information from a customer (Users.cfc). However, I'm not sure of the correct way to accomplish this. There are a couple ways that I've been playing with to allow my CFC's to reference each other:
Method 1: Within a CFC, instance the other CFC’s that you’re going to need:
<!--- Store.cfc --->
<cfcomponent>
<!--- instance all the CFC’s we will need here --->
<cfset usersCFC = CreateObject("component","users") />
<cfset filesCFC = CreateObject("component","files") />
<cffunction name="storeAction">
<cfset var customerInfo = usersCFC.getUser(1) />
This approach seems to work most of the time unless some of the instanced CFC’s also instance the CFC’s that instance them. For example: If Users.cfc instances Files.cfc and Files.cfc also instances Users.cfc. I’ve run into problems with occasional dreaded NULL NULL errors with this probably because of some type of infinite recursion issue.
Method 2: Instance any needed CFCs inside a CFC’s function scope (this seems to prevent the recursion issues):
<!--- Store.cfc --->
<cfcomponent>
<cffunction name="storeAction">
<!--- create a struct to keep all this function’s variables --->
<cfset var local = structNew() />
<!--- instance all the CFC’s we will need here --->
<cfset local.usersCFC = CreateObject("component","users") />
<cfset local.filesCFC = CreateObject("component","files") />
<cfset var customerInfo = local.usersCFC.getUser(1) />
My concern with this approach is that it may not be as efficient in terms of memory and processing efficiency because you wind up instancing the same CFC’s multiple times for each function that needs it. However it does solve the problem from method 1 of infinite recursion by isolating the CFCs to their respective function scopes.
One thing I thought of based on things I've seen online and articles on object oriented programming is to take advantage of a “Base.cfc” which uses the “extends” property of the cfcompontent tag to instance all of the CFC's in the application. However, I've never tested this type of setup before and I'm not sure if this is the ideal way to allow all my CFCs to talk to each other especially since I believe using extends overwrites functions if any of them share a common function name (e.g. "init()").
<!--- Base.cfc --->
<cfcomponent extends="calendar store blog users files">
What is the correct "best-practices" method for solving this type of problem?
If each of your CFC instances are intended to be singletons (i.e. you only need one instance of it in your application), then you definitely want to looking into Dependancy Injection. There are three main Dependancy Injection frameworks for CF; ColdSpring, WireBox and DI/1.
I'd suggest you look at DI/1 or WireBox as ColdSpring hasn't been updated for a while.
The wiki page for DI/1 is here:
https://github.com/framework-one/di1/wiki/Getting-Started-with-Inject-One
Wirebox wiki page is here:
http://wiki.coldbox.org/wiki/WireBox.cfm
Essentially what these frameworks do is to create (instantiate) your CFCs (beans) and then handles the dependancies they have on each other. So when you need to get your instantiated CFC it's already wired up and ready to go.
Dependancy Injection is also sometimes called IoC (inversion of control) and is a common design pattern used in many languages.
Hope that helps and good luck!
If your cfcs not related to each other the base.cfc concept does not fit. The inheritance is for classes have common things that can inherit from each other. For example if you have User.cfc and you want to added new cfc called customer.cfc I would inherit from User and override some functionality or add some without touching the actual user.cfc.
So, back to your question, since the CFC are not related or have common between each other and to avoid cross referencing, I will create serviceFactory holds instances of cfcs like this
component name="ServiceFactory"
{
function init(){
return this;
}
public User function getUserService(){
return new User();
}
public Calendar function getCalendar(){
return new Calendar();
}
}
and referencing it by
serviceFactory= new ServiceFactory();
userService = serviceFactory.getUserService();
Keep in mind this approach works only if you have sort of another CFC to manage your logic
you can do the same for all other services. If your functions are static you can save your services in application scope and instantiate it only one time (like singleton).
The third option you have is DI(dependency Injection) framework

Ember-Model init issue

I concatinate my application code from multiple js files into one js file. Therefore I can't control the order, and to be honest would not want to. To specify a custom adapter with ember-model you need to create an instance of it like so:
App.User.adapter = Ember.CustomAdapter.create();
So if the CustomAdapter's code appears after the above statement I get the [Uncaught TypeError: Cannot call method 'create' of undefined] error.
App.User.adapter = App.CustomAdapter.create();
App.CustomAdapter = Ember.Adapter.extend({
// custom
});
Is there a way around this?
The order of code loading is very, very important. That's just a fact of life. You need to either figure out how to make your current tool load things in the order that you want, or you need a new tool.

Fusebox invoking a fuse within the code

Does anyone know if its possible to invoke a fuseaction within a coldfusion template?
(You haven't specified which Fusebox version; this answer applies to Fusebox 5.x)
Your title and question is asking two different things - a fuse and a fuseaction are two distinct things. A fuse is simply a CFML template, whilst a fuseaction represents a bundle of logic that performs a particular action (similar to a function).
Fuses:
To invoke a fuse, simply include the file as you would normally - there's no special FB functionality required for this.
Fuseactions:
To invoke a fuseaction, use the do verb, like so:
<cfset myFusebox.do('circuit.fuseaction') />
To store the result, use the second argument for the content variable:
<cfset myFusebox.do('circuit.fuseaction',varname) />
This is the equivalent of this XML:
<do action="circuit.fuseaction" contentvariable="varname" />
There are other arguments available, see this Fusebox cheat sheet which contains plenty of other useful info too.
With MVC, you should be working through a single entry-point. So only a single fuseaction should be called during your request.
BUT that fuseaction can call some of the other model and view templates as needed. And I believe that Fusebox allows you to refactor that logic into something that can be used by multiple actions. (I'm a bit rusty on my Fusebox functionality though, but I bet some Googling will lead you the way.)
As a dire last resort, you could use <cfhttp> to call a URL within your app that invokes that fuseaction. But why not just run some of the code directly without needing to burden your server with another HTTP call?

attributes.someParam cannot be evaluated in coldfusion

I have in my cfm something like this
<CFModule name="MyModule"
someParam_one="#something.one#"
someParam_two="#something.two#"
someParam_etc="etc_etc_etc"/>
And inside my module, I have an
<CFSet param_name = "someParam_one">
...
evaluate("attributes." & param_name)
On most of our servers, this work. But on one of our servers, I get a
Error resolving parameter ATTRIBUTES.SOMEPARAM_NAME
Any ideas why?
Thanks
Have you verified that someParam_one is actually getting created? I've found, for example, that if I do something like this:
<cfset foo = myObject.getSomething() />
and getSomething returns a void value or runs a Java function that doesn't return anything, that CF will choke on it. The variable will be "defined", or so the application seems to think, but attempting to access it will throw an error. So do the following to track down and catch the problem:
Dump your attributes scope to make sure that what you want is indeed actually there.
Run a StructKeyExists(Attributes, param_name) before attempting to access the variable.
Get rid of the evaluate, and instead use Attributes[param_name]
Tangential to your question, but Evaluate() is evil, and an unnecessary evil in this situation. You can write this instead, and it will be more clear, more secure, and faster:
<cfset param_name = "someParam_one">
...
<cfset param_value = Attributes[param_name]>
A shot in the dark:
There's a bug in CFMX where if you
make a CFMODULE call to a template (or
use custom tag) from within a CFC and
that tempate uses the CALLER scope to
return data, the data is never
available to the CFC function. This is
bug 51067 and it is related to the
VARIABLES scope bug, 45138.
Seen in the user comments in the CFMX 6 docs on CFMODULE.
Ok, we did something really stupid :-)
We had two set of these files deployed and one was updated while the other was not, thus the error.
Thanks for all your help.