ColdFusion Code as failing on if condition - coldfusion

Working with cfscript code in ColdFusion, The following seems correct to me, if client_discount is either 0 or NULL, just do not generate the UniqueKey, use existing else use new one. But it does work somehow, I am not sure what I am missing here, trying different cflib UDF's also:
Here is my code:
f = structnew();
f.discountoffered = '#arguments.structform.client_discount#';
writedump(arguments);
result = structFindKeyWithValue(f,f.discountoffered,"0","ALL");
writedump(result);
if((arguments.structform.client_discount EQ 0)
OR (arguments.structform.client_discount NEQ "")) {
f.orderunique = generateRandomKey();
}
else {
f.orderunique = '#arguments.structform.orderunique#';
}

NULL is kind of wonky in ColdFusion.
I would handle this by paraming the value so it gets a value I decide if it does not exist.
Add this code under f = structNew() - or at the beginning of the function, does not really matter.
param name="arguments.structForm" default="#structNew()#;
param name="arguments.structForm.client_discount" default="0";
This way if client_discount is not present, it is set to 0 - the first line is to make sure that structform exists in arguments and if not, sets it to an empty struct.
Then your if statement need only check if it is 0.
if( arguments.structForm.client_discount == 0 ){
f.orderunique = generateRandomKey();
}
else{
f.orderunique = arguments.structform.orderunique;
}
Of course...you would need to verify that arguments.structForm.orderunique exists before using it.

I think that's what you are trying to do
<cfscript>
f = structnew();
if(not isnull(arguments.structform.client_discount)){
f.discountoffered = '#arguments.structform.client_discount#';
result = structFindKeyWithValue(f,f.discountoffered,"0","ALL");
if((arguments.structform.client_discount EQ 0))
f.orderunique = generateRandomKey();
else
f.orderunique = '#arguments.structform.orderunique#';
}
else {
f.orderunique = '#arguments.structform.orderunique#';
}
</cfscript>

Related

How to edit list elements in kotlin or add to second list?

I tried to edit a list in-place but wasn't able to get it working. Now trying to edit individual elements and add them to a second list. However the second list remains null and does not get updated. Any help would be appreciated.
var localFiles: MutableList<String> = File(localPath).list().toMutableList()
var localFileDates: MutableList<String>? = null
val iterateLocal = localFileDates?.listIterator()
for (item in localFiles) {
var date = item.takeLast(10).take(6)
if (date.matches("[0-9]+".toRegex()) and (date.length == 6) and (date != null) and (date != "null")) {
iterateLocal?.add(item.takeLast(10).take(6))
}
}
println(networkFiles) // prints correct outpu
println(localFileDates) // prints null
You need init localFileDates variable:
var localFileDates = MutableList()
var localFiles: MutableList<String> = File(localPath).list().toMutableList()
var localFileDates = MutableList<String>()
val iterateLocal = localFileDates?.listIterator()
for (item in localFiles) {
var date = item.takeLast(10).take(6)
if (date.matches("[0-9]+".toRegex()) and (date.length == 6) and (date != null) and (date != "null")) {
iterateLocal?.add(item.takeLast(10).take(6))
}
}
println(networkFiles) // prints correct outpu
println(localFileDates) // prints correct
It is better to use map{..} function to create a copy of the list with updated values.
val localFiles = File(localPath).list()?.toMutableList() ?: listOf()
val localFileDates = localFiles.mapNotNull { item ->
val date = item.takeLast(10).take(6)
if (date.matches("[0-9]{6}".toRegex()) {
date
} else {
null
}
}
println(localFiles)
println(localFileDates)
I use the mapNotNull{..} function calls the block for every element of the list and builds the new list only from non-null values.
You do not need var in your code, explicit type names can be omitted too.
The condition can be simplified - no need for the null check, the regular expression filters our the data == "null" case, the length check can be included into the regex too. The date variable can be re-used too.
A more idiomatic (and readable) way:
val localFileDates = File(localPath).list().map { it.takeLast(10).take(6) }.filter {
it.matches("[0-9]+".toRegex()) && (it.length == 6) && (it != "null")
}
Also I suggest you create a named function for takeLast(10).take(6) and the condition to make it clear what is the intent of these lines of code.

Jsoup to post data and parse alternative URLs on CFscript

I need to get and parse a page from primary_URL using Jsoup in CFscript.
If page status is not OK or data is corrupt or empty, I should try an alternative page from secondary_URL.
primary_URL accepts POST requests only and I don't know how do it in cfscript
secondary_URL accepts GET by default
This is an idea:
<cfscript>
jsoup = createObject("java", "org.jsoup.Jsoup");
response = jsoup.connect(primary_URL).userAgent("#CGI.Http_User_Agent#").timeout(10000).method(Connection.Method.POST).execute(); // How to use Method.POST in this case???
if(response.statusCode() == 200)
{
doc = response.parse();
theData = doc.select("div##data");
...
`some other parsing and SQL UPDATE routine`
}
else
{
response = jsoup.connect(secondary_URL).userAgent("#CGI.Http_User_Agent#").timeout(10000).execute(); // default is GET
if(response.statusCode() == 200)
{
doc = response.parse();
theData = doc.select("div##same_data");
...
`some other parsing and SQL UPDATE routine`
}
}
</cfscript>
How to jump to the secondary_URL in case the response is OK but the data appears to be currupt or empty? A kind of goto operator?
Running ColdFusion 11.
How to jump to the secondary_URL in case the response is OK but the data appears to be currupt or empty? A kind of goto operator?
Instead of checking the statusCode only, call a function. Inside this function perform all necessary checks (corrupted data, empty data ...).
<cfscript>
function IsValid(response) {
// Perform all the tests here...
// Return TRUE on success or FALSE otherwise
return true;
}
jsoup = createObject("java", "org.jsoup.Jsoup");
response = jsoup //
.connect(primary_URL) //
.userAgent("#CGI.Http_User_Agent#") //
.timeout(10000) //
.post(); // Simply call the post() method for posting...
if( IsValid(response) ) {
} else {
response = jsoup //
.connect(secondary_URL) //
.userAgent("#CGI.Http_User_Agent#") //
.timeout(10000) //
.get(); // Make your intent clear
if ( IsValid(response) ) {
// ...
}
}
</cfscript>

How to create application variables in application.cfc

I'm new to using the application.cfc file in our application and some of these don't seem to be working and I can't figure out why. I have tried to cfdump "application". I get Application.DSN, Application.USERNAME, Application.Password, but not Application.SYSTEMPATH or Application.ACCOUNT
<cffunction name="onApplicationStart">
<cfscript>
Application.availableResources=0;
Application.DSN = "XXX";
Application.USERNAME = "XXX" ;
Application.PASSWORD = "XXX";
Application.SYSTEMPATH = "http://example.com/"; // This doesn't work
Application.ACCOUNT = XXX; // This doesn't work.
Application.counter1=1;
Application.sessions=0;
</cfscript>
</cffunction>
I think you want this:
Application.SYSTEMPATH = GetDirectoryFromPath(GetCurrentTemplatePath());
This will work too:
Application.SYSTEMPATH = expandPath( './' );
Now this...
Application.ACCOUNT = XXX; // This doesn't work. (because it is assuming XXX is a variable).
You need this:
XXX = 'something'; or XXX = 1; or Remove it altogether because it serves no purpose.
Then when you call:
Application.ACCOUNT = XXX; it won't give you errors.
Or you can just skip it and do this:
Application.ACCOUNT = 'something'; (a string)
Application.ACCOUNT = 1; (a number)
Then it won't fall apart (Because XXX is a variable not a value and you can't call a variable that doesn't exist).
So, if you have a 'variable' it has to have a 'value' (variable/value pair) or at least set a placeholder like XXX=0; or XXX=''; if you must have it.
Have I killed this variable/value dead horse to death??? Lol... :D
Jokes aside let us know if you have another question about your Application variables because some seem unnecessary (can't judge for sure though).

How do I retrieve the current value of enablecfoutputonly?

We are using Coldfusion 9.
Is there a simple way to know if enablecfoutputonly has been set to true during a particular request?
I cannot test with CF9 right now, but in CF10 it is accessible from getPageContext() by checking the output object:
<cfscript>
out = getPageContext().getOut();
// Is the cfsetting enablecfoutputonly value currently true?
isSettingEnabled = out.getDisableCount() > 0;
WriteOutput("isSettingEnabled="& isSettingEnabled &"<br>");
// Is output currently allowed?
isOuputtingEnabled = out.getDisableCount() == 0 || out.getOutputCount() > 0;
WriteOutput("isOuputtingEnabled="& isOuputtingEnabled &"<br>");
</cfscript>
.. or using reflection:
<cfscript>
out = getPageContext().getOut();
internalMethod = out.getClass().getDeclaredMethod("isOutputEnabled", []);
internalMethod.setAccessible( true );
isOuputtingEnabled = internalMethod.invoke( out, [] );
// is output currently allowed?
WriteOutput("isOuputtingEnabled="& isOuputtingEnabled);
</cfscript>

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.