Tour de CF Beta is out now!

Just downloaded the beta Tour de ColdFusion AIR application. If you tried Tour the Flex, than you know what it is all about. Neat application that will help you explore ColdFusion features trough the examples. Thanks for this great news go to Adobe off course, and to Raymond Camden because he was the first to let me know. Gotta check it out if you are a ColdFusion fan. If you want to give feedback, go to public Google group.
Generate JavaScript variables in the loop
I know this can be avoided by using arrays or similar structures, but the other day I stumble on the problem that leaded me to this solution in JavaScript, so I decided to write it down. Here is the short explanation of the problem. Let's say you need to check if input value which is number, must be in more than one range. We do not now how many ranges could appear in the future. Ranges are dependable on the selected date. Because the ranges are quite big, I don't want to go trough each and every one number in range (create union), each time I want to check, on the client side, if the input value belongs to one of this ranges. Here is the solution. First I will generate attributes of the options in select box, in loop. This way I will have all the condition data, when the date (option) is selected from select box and I will show you how easy is to generate variables in ColdFusion. Then I will add one more attribute to options called "counted". When the user enters the value in input and lets say, lose the focus (onBlur), I will invoke JavaScript function that will dynamically generate for me as many variables as there are ranges. Then I will loop trough each dynamically created range variables and compare them with my value from input.
Here you can see how the variables are dynamically created in javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <script language="javascript"> function Check(obj,selectID){ var objVal=$(obj).val()*1; var count=$("#"+selectID+" :selected").attr("counted")*1; var note=""; // Dinamically creating javscript variables for(var i=1;i<=count;i++){ this["minimum"+i]=$("#"+selectID+" :selected").attr("min_"+i); this["maximum"+i]=$("#"+selectID+" :selected").attr("max_"+i); } var mustNotBeSameAsCount=0; for(var i=1;i<=count;i++){ if((objVal< this["minimum"+i]) || (objVal> this["maximum"+i])){ mustNotBeSameAsCount=mustNotBeSameAsCount+1; } } if(mustNotBeSameAsCount==count) note="This number is not in any of ranges for selected date"; else note="This number is found in ranges for selected date"; alert(note); } </script> |
and in this example you can see how easy is to generate variables in loop in ColdFusion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <cfoutput> <cfquery name="qryDates" datasource="Test"> Select Date FROM Dates </cfquery> <cffunction name="getRanges" ReturnType="query" hint="Return ranges"> <cfargument name="Date" required="yes"> <cfquery name="qryRanges" datasource="Test"> Select FirstInRange,LastInRange FROM Ranges where Date='#Date#' </cfquery> <cfreturn "#qryRanges#"> </cffunction> <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <title>Generate JavaScript and ColdFusion variables in the loop</title> </head> <body> <select name="dates" id="dates" onChange=""> <cfloop query="qryDates"> <cfset counter=0> <cfset Ranges=getRanges('#Date#')> <option value="#Date#" <cfloop query="Ranges"> <cfset counter=counter+1> min_#counter#="#FirstInRange#" max_#counter#="#LastInRange#" </cfloop> counted="#Ranges.RecordCount#"> #DateFormat(Date,"mm/dd/yyyy")# </option> </cfloop> </select> <input type="text" id="inpTest" name="inpTest" onBlur="Check(this,'dates');"> </body> </html> </cfoutput> |
You noticed that this["SomeName"] will generate the variable same way like var SomeName would do.
Invoke cffunction from JavaScript
Here is the simple example on how you can use cfajaxproxy to invoke a coldfusion component from JavaScript. First we need to write a coldfusion component. This is the simplest I could think at this moment:
1 2 3 4 5 6 7 8 9 10 11 | <cfcomponent name="TestComponent" hint="Example Component"> <cffunction name="TestFunction" access="remote" returnFormat="json"> <cfargument name="TestParameter1" required="yes" hint="Test param"> <cfargument name="TestParameter2" required="yes" hint="Test param"> <cfif #Arguments.TestParameter1# eq #TestParameter2#> <cfreturn "Values are matching"> <cfelse> <cfreturn "Values are not matching"> </cfif> </cffunction> </cfcomponent> |
I named this Component TestComponent and saved the TestComponent.cfc file in CFC folder in root of my web site. You can see I created cffunction TestFunction as a method of TestComponent. This method receives two parameters which are required in this case, but not necessarily. Very important thing here is to set the access to "remote" so this component could be invoked remotely and set the return format to "json" . JSON is a lightweight replacement for xml which translates native datatypes into across languages. Very neat format when it comes to Ajax. Method itself is not doing much, comparing two variables and returns result string accordingly. Now let's create very simple page and point out the logic from the title of this post. I separated the JavaScript code in js_functions.cfm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <script language="javascript"> var myErrorHandler = function(statusCode, statusMsg){ alert('Status: ' + statusCode + ', ' + statusMsg); } var ValuesChk = function(testparam1,testparam2){ // creating an instance of the proxy class. var e = new jsChkValues(); // Setting a callback handler for the proxy automatically makes // the proxy's calls asynchronous. e.setCallbackHandler(GetResult); // Setting the Error Handler to handle error e.setErrorHandler(myErrorHandler); //Invoke our cold fusion component and pass the parameters e.TestFunction(testparam1,testparam2); } var GetResult = function(returnedValue){ alert(returnedValue); } function TestFunction(){ var param1=document.getElementById("parameter1").value; var param2=document.getElementById("parameter2").value; ValuesChk(param1,param2); } </script> |
And here is the actual cfm display page that contains mostly HTML with small exception at the top, where we are creating cfajaxproxy class named "jsChkValues".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!--- Creating client side proxy for cfc that is located in CFC folder ---> <cfajaxproxy cfc="Tests.CFC.TestComponent" jsclassname="jsChkValues"> <html> <head> <title>Testing Cold Fusion Ajax</title> <!--- Include js_functions.cfm file where javascript is located ---> <cfinclude template="js_functions.cfm"> </head> <body> <h2>Compare Paremeters Using Coldfusion Ajax</h2> <input type="text" name="parameter1" id="parameter1" value="0"/> <input type="text" name="parameter2" id="parameter2" value="0"/> <button name="btn" id="btn" onClick="TestFunction();"> Compare </button> </body> </html> |
First of all we created Javascript function which will generate for us Status Code of Error and appropriate message if an error occur in an asynchronous call. This function will be passed as parameter to a cfajaxproxy method setErrorHandler.
Then we are creating function that receives two parameters and creates the instance (e) of proxy class (jsChkValues) that was created at the top of the display document. To make the proxy's calls asynchronous all we need to do is to set a callback handler function for the proxy. GetResult is also a Javascript functions that is passed as parameter to cfajaxproxy method and gets the value from component for us. To cut the long story short TestFunction is started by button onClick event, this function gets the input field values and pass them to the main function "ValuesChk" where we invoke component using cold fusion ajax. You can return query-es and other structures on the same way.
Working with more than one result sets using MSSQL stored procedure with ColdFusion
Stored procedures can return more than one result set, therefor you need somehow to distinguish these result sets in order to use them. This can be done in ColdFusion very easily by using cfstoredprocedure tag. Here is the simple example of how you can do this. First we need to create stored procedure in MSSQL:
Example of stored procedure that receives two parameters: date and year, first result set should show all the users from x table, second result set should return only users with date of birth matching the input parameter @DateOfBirth, and third result set will show only users that are borned in the year that is passed as second parameter @Year:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- =========================================================== -- Author: Nenad Kostic -- Create date: 06/06/2010 -- Description: Test Procedure returning more than one result set -- =========================================================== CREATE PROCEDURE TestProc @DateOfBirth datetime, @Year varchar (4) AS BEGIN --First Result set SELECT * FROM x IF @@ERROR>0 RETURN 1 --Second Result set SELECT * FROM x WHERE DateOfBirth=@DateOfBirth IF @@ERROR>0 RETURN 2 --Third Result set SELECT * FROM x WHERE CONVERT(varchar(4),datepart(year,DateOfBirth))=@Year IF @@ERROR>0 RETURN 3 END GO |
If this procedure completes with no errors status code will be zero, otherwise we can diagnose where the error occurred depending on status code (1, 2 or 3).
Here is the example of code that will invoke the stored procedure and store three separate result sets in variables RS1, RS2 and RS3. In this example you can see also how you can capture status code of the stored procedure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <!--- Test variables that we are passing to the procedure ---> <cfset DateOfBirth="05/18/1985"> <cfset Year="1985"> <!--- Invoke stored procedure ---> <cfstoredproc procedure="TestProc" datasource="XYZ" returnCode = "yes"> <cfprocparam cfsqltype="cf_sql_date" value="#DateOfBirth#"> <cfprocparam cfsqltype="cf_sql_varchar" value="#Year#"> <cfprocresult name = RS1 resultset="1"> <cfprocresult name = RS2 resultset="2"> <cfprocresult name = RS3 resultset="3"> </cfstoredproc> <!--- Preview RS1 ---> <cfdump var = "#RS1#" expand = "Yes" label = "Result set 1"> <!--- Preview RS2 ---> <cfdump var = "#RS2#" expand = "Yes" label = "Result set 2"> <!--- Preview RS3 ---> <cfdump var = "#RS3#" expand = "Yes" label = "Result set 3"> <!--- Capture Status Code of the stored procedure ---> <cfset StatusCode=#cfstoredproc.statusCode#> <!--- Preview Stored procedure status code ---> <cfoutput> Status Code of TestProc procedure: #StatusCode#</cfoutput> |
You noticed the cfsqltype in cfprocparam. You need to declare type of variable that you are passing to the stored procedure, here you have example of cf_sql_date and cf_sql_varchar. If you want to send integer or any numeric type, cfsqltype would be cf_sql_numeric. All the documentation you need on cfstoredprocedure tag you can find here.
Reveal your code on web page.
If you hit this query in Google you are probably ran in to the problem similar to mine when I first tried to publish HTML code to my blog. You will have to switch all the "<" and ">" signs in your code to "<" and ">", respectively. If you are a word press user, you can use one of many plug-in’s that will help you solve this problem without manually doing this boring task. WP_CodeShield plug-in from Scott Sherrill-Mix for example, will do this job for some of you out there. I would recommend to you nice online tool that was written by Eliot Swan called "postable". Simply enter your code in textbox, press the button "make it friendly" and there you go. Copy-Paste it to your page.
Determine affected rows during update in MSSQL
MSSQL is my favorite database. In case you want to determine exact number of affected rows during update query, use @@ROWCOUNT global variable. This variable will return exact number of affected rows.
1 2 3 4 5 6 | USE DatabaseName UPDATE TableName SET ValueField='Some value' WHERE ValueID=100 IF @@ROWCOUNT = 0 PRINT 'No rows were updated'; ELSE PRINT CAST(@@ROWCOUNT AS varchar)+' rows were updated'; |
Starting the default Internet browser programmatically by using Console C# Application
If from any reason, you need to start default browser and open the desired URL programmatically from console application in C#, you can do this by using Process Class Start Method. This method is static so you don't need the instance of Process class. Simply write:
1 | System.Diagnostics.Process.Start("http://www.google.com"); |
This line will start default browser and open the URL from the string you passed to Start Method. Nicer way to do this is to handle the exceptions if let's say the target computer is not having browser installed or etc.
Here is the complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | using System; using System.Collections.Generic; using System.Text; namespace DefaultBrowser { class Program { static void Main(string[] args) { Console.WriteLine(@"Starting http://www.google.com in default browser"); string target = "http://www.google.com"; try { System.Diagnostics.Process.Start(target); } catch (System.ComponentModel.Win32Exception noBrowser) { if (noBrowser.ErrorCode == -2147467259) Console.WriteLine(noBrowser.Message); } catch (System.Exception other) { Console.WriteLine(other.Message); } } } } |
ErrorCode -2147467259 stands for Unspecified error. Microsoft named it this way for some reason I suppose.
Extract strings from particular character position in MySQL string
This post is result of tweaking wp-xLanguage Word Press plug-in. I would highly recommend this plug-in if you want to have Multilanguage blog or website that is based on Wordpress CMS. This plug-in works well even if you have your PHP on IIS7, like in my case, with no modifications on database structure at all. I’ve had to customize some functions because of version of word press I was using, but everything turned OK at the end.
Problem that I had, occurred because certain plug-in that needed to be translated as well, wasn’t hooked with xLanguage. These left me two choices, either to hack plug-in to implement the hook or find faster solution, write a new query that will extract exactly what I need from string depending on localization.
Let’s say we have table X in XYZ database and we have field Title in this table. Value for this field is “English|French”. We need to write two queries or one, but in this case I will write two. One will extract everything from left side of vertical line sign ‘English’, and second query will extract everything from right side of vertical line sign ‘French’.
Query for left side extraction (English):
1 2 3 4 5 6 7 | SELECT CASE Title REGEXP '[[.|.]]' WHEN 0 THEN Title ELSE LEFT(Title,LOCATE('|',Title)-1) END as Title FROM X |
Query for right side extraction (French):
1 2 3 4 5 6 7 | SELECT CASE Title REGEXP '[[.|.]]' WHEN 0 THEN Title ELSE RIGHT(Title,CHAR_LENGTH(Title)-LOCATE('|',Title)) END as Title FROM X |
Regular expressions are used because I want to determine If the vertical sign is appearing in the string at all. Some words are same on both languages and I don’t want to duplicate these words unnecessary (Help|Help). Regular expression operator works though in byte-wise fashion so you need to put vertical line sign in double brackets with dots '[[.|.]]' or you can write instead '[[.vertical_line.]]'.
See String Regular Expression Operator’s Documentation.
One more important thing on string length is why I used CHAR_LENGTH. French language is having multy-byte characters like é, ê and etc. If I had used LENGTH instead CHAR_LENGTH result for string “é ê” would be 4 and not 2 as it supposed to in my case.
See the String Functions documentation.
Grid buildrrr

Last night I ran in to nice tool called Grid buildrrr. This tool helps you generate grid for your layout. You can enter column count, column width, column margins, outer margins, make measurements with draggable boxes and so on. Very simple and neat. Grid buildrrr