Creating a new instance from within CFC - coldfusion

Now this would seem to be something very straight forward, but seemingly not so in ColdFusion. I need to create an instance of a CFC from within itself as in var a = new this() but this obviously does not work. The CFC name can't be used as it is a base that will be extended so I am attempting a hack around the issue with the following:
component {
public function subQuery (required string table) {
var classPath = getMetaData(this).fullname;
return createObject("component", classPath).init(table, this.dsn);
}
}
This would be acceptable but the class path returned from getMetaData(this).fullname is incorrect. The CFC is within a folder named with a hypen as in my-folder and the returned path looks like my.-folder.myCFC with a period inserted before the hyphen. Obviously I could manipulate this string with a Regex but that is just not a road I want to go down.
Hoping someone has a cleaner approach, thanks.

You should be able to do it without any context on the object name in theory, as it will be being executed from within itself and it should check its current directory.
The following should therefore do the job you need
var classPath = ListLast(getMetaData(this).fullname,'.');
return createObject("component", classPath).init(table, this.dsn);
This way it doesn't matter what the directory names are, and it will work on any objects that extend that one regardless of directory structure, or for a complete example
public function cloneMe() {
return CreateObject('component', ListLast(getMetaData(this).fullname,'.')).init(argumentCollection=arguments);
}
This way any arguments passed in will be passed through into the init. I.e. an extending CFC may redefine the method as the following (if you want errors when the init arguments aren't supplied)
public function cloneMe(required string table) {
return super.cloneMe(table=arguments.table,dsn=this.dsn);
}

Related

Sitecore: Glass Mapper Code First

It is possible to automatically generate Sitecore templates just coding models? I'm using Sitecore 8.0 and I saw Glass Mapper Code First approach but I cant find more information about that.
Not sure why there isn't much info about it, but you can definitely model/code first!. I do it alot using the attribute configuration approach like so:
[SitecoreType(true, "{generated guid}")]
public class ExampleModel
{
[SitecoreField("{generated guid}", SitecoreFieldType.SingleLineText)]
public virtual string Title { get; set; }
}
Now how this works. The SitecoreType 'true' value for the first parameter indicates it may be used for codefirst. There is a GlassCodeFirstDataprovider which has an Initialize method, executed in Sitecore's Initialize pipeline. This method will collect all configurations marked for codefirst and create it in the sql dataprovider. The sections and fields are stored in memory. It also takes inheritance into account (base templates).
I think you first need to uncomment some code in the GlassMapperScCustom class you get when you install the project via Nuget. The PostLoad method contains the few lines that execute the Initialize method of each CodeFirstDataprovider.
var dbs = global::Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
Furthermore I would advise to use code first on development only. You can create packages or serialize the templates as usual and deploy them to other environment so you dont need the dataprovider (and potential risks) there.
You can. But it's not going to be Glass related.
Code first is exactly what Sitecore.PathFinder is looking to achieve. There's not a lot of info publicly available on this yet however.
Get started here: https://github.com/JakobChristensen/Sitecore.Pathfinder

cfscript component function with object types in arguments and returntypes

I have a feeling this is a bug in CF9, from looking at this: How to specify argument attributes in CFscript? (CF9)
However, if not, I'm writing a cfscript component in CF9 (pure), and attempting to pass an argument as a type of user defined cfc.
public function init(required _lbr._core._sharing._access.accessLinkDAO oAccessLinkDAO) returntype="_lbr._core._sharing._access.accessLinkBusiness" {
But CF keeps coming back with:
You cannot use a variable reference with "." operators in this context
is this something broken with CF9 pure?
I have confirmed this is a bug in CF9.0 (and fixed in one of CF9.0.1 or CF9.0.2; probably 9.0.1).
However the fix is easy. The problem is only with the dotted paths, and as #ScottStroz points out, you don't need them. This works fine:
component {
public accessLinkBusiness function init(required accessLinkDAO oAccessLinkDAO) {
return this;
}
}
I've moved the return type simply because that's just the normal place for it: it'll work as attribute too (but that syntax is just awful).
If the CFCs you are referencing as return types or argument types aren't in the same dir as the CFC using them, use an import statement, eg in this case:
import _lbr._core._sharing._access.*;

Luabind objects disapearing when I enter a new file

I'm using Luabind to bind my Lua scripts to my C++ engine. (it uses lua 5.1.4)
I added a new lua script called "controller.lua" which my entities script, called "cat.lua", will reference and use. One the c++ calls the method "Update" it's all in the hands of Lua.
But once I try to pass my binded c++ methods to the new script file, it feels like all the bindings from that c++ object disapear. I get the following error:
Expression: scripts/controller.lua:5(method MoveUp)
scripts/controller.lua:5: attempt to call method 'GetComponent' (a nil value)
Here is some C++ snippets
// Definitions
module(luaState)
[
class_<Entity>("Entity")
.def("GetComponent", &Entity::GetComponent)
class_<Component>("Component")
.enum_("eComponentTypes")
[
value("Steering", kComponentType_Steering)
],
class_<SteeringComponent>("SteeringComponent")
];
// The script components update
void ScriptComponent::Update() {
const Entity* owner = this.GetOwner();
mLuaDataTable["Update"](owner); // Executes the Update function on the script Cat.lua
}
The entities code being called by c++ (When it executes it returns the Cat table to c++.)
-- Cat.lua
local controller = loadfile("scripts/controller.lua")
local Cat = {}
function Cat.Update(entity)
steeringComponent = entity:GetComponent(Component.Steering) -- Works fine
controller:MoveUp(entity)
end
return Cat
and the Controller
--controller.lua
local up = vec2(0.0, 1.0)
local Controller = {}
function Controller.MoveUp(entity)
steeringComponent = entity:GetComponent(Component.Steering) -- Fails
end
return Controller
Bonus points:
When I make a change to the controller that doesn't work (like if I just threw an s character anywhere), the controller loads up nil, no warnings. Is there some way to make it throw warnings?
Is there a better way I should be doing to "link" to other lua files, like the way im working with Controller?
Thanks to ToxicFrog on Freenode chat for helping me figure this one out.
Basically: I was calling controller MoveUp like so:
controller:MoveUp(entity)
which of course translates into
controller.MoveUp(controller, entity)
and the function was defined as
function Controller.MoveUp(entity)
this "entity" was accepted as the first parameter, controller, while the actual entity is discarded per spec.
http://lua-users.org/wiki/ObjectOrientationTutorial

JToolBarHelper :: DeleteList - Does not work

I created a Joomla 2.5 custom component and load data to grid on administrator side. All data loaded and adding and editing work well. But deleting is not working. It gives following error.
Fatal error: Call to a member function delete() on a non-object in
C:\wamp\www\Joomla\libraries\joomla\application\component\controlleradmin.php on line 131
In view class I used JToolBarHelper for delete action as follows.
JToolBarHelper::deleteList('', 'regions.delete', 'JTOOLBAR_DELETE');
I had this problem myself, and I've just figured it out. Look into your file corresponding to admin/controllers/helloworlds.php, there should be this line:
public function getModel($name = 'HelloWorld', $prefix = 'HelloWorldModel')
The first param's default value is the name of a single item (in your case, probably Region) and the second one contains the name of the component. So it should be:
public function getModel($name = 'Region', $prefix = 'NameOfYourComponentModel')
I hope this helps also in your case. In the HelloWorld example, they use HelloWorld all over the code, both as the name of the component and the main view, so it's sometimes hard to distinguish which one is what.

Storing an INI file in memory

I am writing an application that uses an ini file to store all status codes (errors, success codes, etc.) A very simple version is this:
[success]
000=Status code not found.
[error]
000=Error code not found.
001=Username/Password not found.
And my CF Component to work with that uses the following code:
component hint="Set of tools to interact with status codes."{
public function init(string codefile) any{
this.codefile = Arguments.codefile;
}
public function getCodeString(string type, string code) string{
var code = getProfileString(Variables.codefile, Arguments.type, Arguments.code);
return code;
}
}
What I assume happens when I call the getProfileString is that Railo opens the file, searches for the key and returns the value. So as my application grows and I have a lot more codes, I expect that this process will slow down. So is there a way that I can open the file in my init method and read it all into the variables scope, and call the getProfileString from there?
You can even parse your ini file in onApplicationStart and push the data into application scope like recommended for a XML file by #Sergii, if you want to stick with the .ini approach.
Do something like that:
var sections = getProfileSections(variables.codeFile);
var sectionEntries = [];
var indx = 0;
for (key in sections){
sectionEntries = listToArray(sections[key]);
application[key] = {};
for (indx=1; indx <= arraylen(sectionEntries); indx++){
application[key][sectionEntries[indx]] = getProfileString(variables.cfgFile,key,sectionEntries[indx]);
}
}
haven't tested this on Railo, but it should work on ColdFusion 9 at least
Because you are using Railo there's possibly easiest solution: put the file into the RAM filesystem.
So full path to the file will look like ram:///some/path/to/config.ini.
Obviously, you need to write the file into the RAM first, possibly on first request.
So slightly modified version of the component may look this way:
component hint="Set of tools to interact with status codes."{
public function init(string codefile, string.ramfile) any{
variables.codefile = arguments.codefile;
variables.ramfile = arguments.ramfile;
}
public function getCodeString(string type, string code) string{
if (NOT fileExists(variables.ramfile)) {
fileCopy(variables.codefile, variables.ramfile);
}
return getProfileString(variables.ramfile, arguments.type, arguments.code);
}
}
Please note that I've changed this.codefile to the variables.codefile in the init.
Any way, I'm also not sure ini file is the most handy and maintainable solution. You need to parse it each time any way, right? If you need a file config, use XML. Just parse it in onApplicationStart and push the data into the application scope.