Showing posts with label ColdFusion 9. Show all posts
Showing posts with label ColdFusion 9. Show all posts

Saturday, October 12, 2013

Post Parameters Exceeds Maximum Limit

In sometime I was making a “POST” AJAX request to server and it was working fine but latter I had to add few new form elements and then I made the POST AJAX call. Suddenly I got the error:

HTTP Error 500.0 - Internal Server Error
The page cannot be displayed because an internal server error has occurred.


I was using ColdFusion – 9 with IIS. After few searching I found that the problem is with no of form parameters present in the “POST” request. By default ColdFusion provides a default form element limit as “100”. If the no of parameter will exceed to that then we will get error message.

I run the same code in ColdFusion – 10 with Apache and I got the following error message:
POST parameters exceeds the maximum limit.

Then the question arises:

                    Will I get the same error for “GET” request?
                    How can I increase the limit in ColdFusion?

Will I get the same error for “GET” request?

No, for “GET” request you will not get such error . “GET” request depends on the URL length. I mean when you make any “GET” request all parameters are appended to the base URL and they pass in URL scope. Each browser have some limit to length of the URL it can process, if the URL length in “GET” request will exceed to that then you may get some error message or some unwanted result.

How can I increase the limit in ColdFusion?

            In ColdFusion – 9:
Go to {ColdFusion-Home}/lib for Server Installation
or
{ColdFusion-Home}/WEB-INF/cfusion/lib for Multiserver or J2EE installation.
Open file neo-runtime.xml, after the line.

<var name='postSizeLimit'><number>100.0</number></var>

add the below line and you can change the number 100 to your desired limit.
<var name='postParametersLimit'><number>100.0</number></var>

            In ColdFusion – 10:
Adobe has added an option in ColdFusion Admin to control the number of form elements. Go to
Settings”, you will see a screen like below:



You can change the highlighted section value from “100” to your desired form element limit.



NOTE: After doing all these you will see if you have provided “100” limit then you are able to pass only “99” form elements in post request I.e. 1 element less than the limit. Because when do any form post ColdFusion automatically added a field called “FIELDNAMES”.

Wednesday, July 03, 2013

The processing instruction target matching "[xX][mM][lL]" is not allowed.

I was doing some operation on some XML document and I got a strange error :
"The processing instruction target matching "[xX][mM][lL]" is not allowed. "
I just regenerated the error with the following code sample.



Then I searched in web I found that this is not related to any specific language, this is related to the XML declaration format.

According to the XML spec we can't have anything at all before the XML prolog. In our XML we are staring with XML declaration. So, that XML declaration should be the first character in our XML document no white space or any special characters are allowed before our XML document declaration.

So, the question is how we can avoid this in our above code?

- Use trim before parsing the XML string like below
   <cfset mydoc = XmlParse(trim(request.x))>

So, trim function will remove any extra spaces present in the document before starting the XML declaration.

- Write XML declaration as the first character of your XML text. No white space or any other characters at the starting position.

- Remove your XML declaration from the XML text.


Hope it will save your time...

Tuesday, July 02, 2013

Restart your Application without restarting your ColdFusion Server

I was working in a old application where the object instantiate was done in onApplicationStart method of Application.cfc. To solve few hot fixes I modified the cfc and pushed into live but the code which I had modified was not working. As I have to reset that application variables which holds the Old component object.

So, I thought use ApplicationStop function which was introduced in ColdFusion-9. Before that I have never used ApplicationStop in any of my previous applications. I had read the documentation that this function basically used in ColdFusion ORM to reload the ORM objects. So, I just did some testing how exactly this function behaves in normal condition.

So, here is my Application.cfc for testing.

Here is index.cfm

If you will notice here in this Application.cfc I just doing file append operation in onApplicationStart(), onSessionStart(), onSessionEnd(), onApplicationEnd() and also inside onRequestEnd() when we want to refresh our application.

When the very first time I run the application I got the following output in file write:
Application started on :- {ts '2013-07-02 18:28:04'}
Session started on :- {ts '2013-07-02 18:28:04'}

And for index.cfm I got the following output:
Testing Application Stop 
10
20

Next time I just passed a URL parameter "appReset" so that I can reset the application. Then I got the following output in file write:
Application stop is going to execute on :- {ts '2013-07-02 18:28:49'}
Application ended on :- {ts '2013-07-02 18:28:49'}

And in index.cfm I got the following output:
Testing Application Stop 
10
20

So, here we observed that ApplicationStop() executed and then onApplicationStop() executed but onSessionEnd() was not executed.


On third time I just removed the URL parameter for Application reset. Then I got the following output:

In log file:
Application started on :- {ts '2013-07-02 18:29:04'}

And in index.cfm:
Testing Application Stop 
10
Error Message:
Element MYVAR is undefined in APPLICATION.

So, when we are calling ApplicationStop it doesn't affect any session scope variables. Session scope variables remain unchanged and also it doesn't creates a new session. It simply uses the old session scope but reset all application scope variables.

So, if we want to put any object instantiation code in onApplicationStart() then we can reinstantiate that using   ApplicationStop().


If someone will ask that why can't we follow simply by calling onApplicationStart() in onRequest() as per our requirements.
Yes, we can do that but it depends on your logic you have implemented in your Application.

If someone doesn't wants to reset  all application scope variable then directly call onApplicationStart(). But, if someone wants to reset all application scope variables or using ORM in the Application then ApplicationStop() will work.

Still exploring more on this...

Wednesday, June 20, 2012

CFX(Java) Custom tags in ColdFusion-9(Part-1)

For  ColdFusion - 9 some sample java source files are present in “{ColdFusion_Root}/cfx\java\distrib\examples\” for windows and in “{ColdFusion_Root}/cfx/java/examples” directory for linux system.

<cfx_HelloColdFusion name="Mr. X">

Take the example of “CFX_HelloColdFusion” from the specified source codes present. If you directly execute that CFX tag with the above code without doing anything to the server you will get the following error message.

"Error processing CFX custom tag CFX_HelloColdFusion.
The CFX custom tag CFX_HelloColdFusion was not found in the custom tag database. You must add custom tags to the database before using them. If you have added your tag to the database, check the spelling of the tag within your template to ensure that it matches the database entry."

So you need to follow the following steps in order to install that source code as a CFX tag.

  1. Compile the source code ("HelloColdFusion.java") file  from the sample files of the ColdFusion installation  by using the command prompt or by using any IDE and generate the "HelloColdFusion.class" file.
  2. For testing the CFX tag place the  HelloColdFusion.class  file in “cf_root/wwwroot/WEB-INF/lib” in Server configuration and place in “cf_webapp_root/WEB-INF/lib” for J2EE configuration. In this place when you make any changes to the java code you only need to replace the new .class file with the existing one. You don't need to restart the ColdFusion server on each changes to the .class built.
  3. You can also place your .class files in your specific directory by changing the Class path settings in ColdFusion administrator.(Server Settings->Java and JVM -> ColdFusion Class Path). After that you need to restart your ColdFusion server.
  4. Then you need to register your CFX tag in ColdFusion admin:
  • Go to Extensions =>CFX Tags => Click Register Java CFX in ColdFusion admin. You will see a screen like below. 
  •  CFX tag name starts with the prefix "cfx_" then the class name of the java code in our case the class name is "HelloColdFusion". So the vale for tag name input will be "cfx_HelloColdFusion".
  •  In Class Name field we need to provide the class name without any .class extension. e.g-"HelloColdFusion".
  •  In Description text area we need to add some description for that tag. e.g-This tag shows greeting message. This field is Optional we can skip it. But, it helps us when we have very large no of CFX tags.
After all these steps if I will run the CFX code which I have written on the top of this page, I will get the following message as the output.
"Hello, Mr. X"

For more details on CFX(java)  in ColdFusion-9 have to wait for the next post. Thanks :)

1. CFX Custom Tag Part II

Saturday, June 09, 2012

ColdFusion Query Of Queries and local scope

Few days ago I was working with  QueryOfQuery and I faced one situation where I got stucked for few hour . After few Googling I found the silly mistake I was making.

I am just trying to generate the same situation with some sample code below.

<cfset local.qryGetArtists = queryNew("") />
<cfset local.qryGetSelctedArtist = queryNew("") />

<cfquery name="local.qryGetArtists" datasource="cfartgallery">
    SELECT ARTISTID, FIRSTNAME, LASTNAME, EMAIL, PHONE FROM ARTISTS
</cfquery>
<cfdump var="#local.qryGetArtists#">

<cfquery name="local.qryGetSelctedArtist" dbtype="query">
    SELECT * FROM local.qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'
</cfquery>
<cfdump var="#local.qryGetSelctedArtist#">

In this code, the first dump give the query Object which contains the list of artist details and after that I am just filtering that query object using Query Of Queries(QoQ) and dumping that result.

For the second dump, I got one big error message:


"Query Of Queries syntax error. Encountered "local"

Where and Why We Got This Error?
The error is due to the local scope as per the error message then why this error. In ColdFusion there are some reserved keywords are there and we can't use that reserve keyword  inside Query Of Queries directly.

This is also mentioned in the ColdFusion Documentation here.

How To Solve This Issue?

The solution is escape the reserve keyword like this:

"SELECT * FROM [local].qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'"


So, the final Code for the Query Of Queries will be like below.

<cfquery name="local.qryGetSelctedArtist" dbtype="query">
    SELECT * FROM [local].qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'
</cfquery>
<cfdump var="#local.qryGetSelctedArtist#">


For more details about Query Of Queries go to the ColdFusion live document. (ColdFusion Query Of Queries)

Friday, June 08, 2012

Extract Tar File In ColdFusion

In ColdFusion it doesn't have any built in function to extract a ".tar" or any ".gz" Compression. For ".gz" compression I have already posted a tip. Now, I am just going to give show you a ColdFusion function using which can be used to extract tar files. This function uses Apache java library to extract the ".tar" file.
Lets start:

<cfscript>
    /*
    @inTarFilePath = input tar file absolute path
    @outExtractPath = The out put directory to which the files will be extract.
    
    Example:
    tarExtract("D:\Temp\pics-leaserental-20120530.tar", "D:\Temp\TarResult\");
    */
    function tarExtract(inTarFilePath, outExtractPath)
    {
        var fileInStream = createObject("java", "java.io.FileInputStream");
        var fileOutStream = createObject("java", "java.io.FileOutputStream");
        var tarInStream = createObject("java", "org.apache.tools.tar.TarInputStream");
        var tarEntry = createObject("java", "org.apache.tools.tar.TarEntry");
        var destFileName = "";

        try{

            //Read tar stream
            fileInStream.init(arguments.inTarFilePath);
            tarInStream.init(fileInStream);
            tarEntry = tarInStream.getNextEntry();

            //Loop each tar entry and write in the specific directory
            while(! isNull(tarEntry)){
                destFileName = arguments.outExtractPath & '/' & tarEntry.getName();

                //If the tar entry is not a directory(means it is a file) then write write that in a file
                if(! tarEntry.isDirectory()){
                    fileOutStream.init(destFileName);
                    tarInStream.copyEntryContents(fileOutStream);
                    fileOutStream.close();
                }
                tarEntry = tarInStream.getNextEntry();

            }

            //Close all opened file streams
            fileInStream.close();
            tarInStream.close();

            return true;
        } catch(Any e){
            return false;
        }
    }
</cfscript>


Hope it will help you in sometime...

Wednesday, April 04, 2012

Working with .net dll Object in ColdFusion

Usually in a ColdFusion Application we do all the logic implementation using ColdFusion. There is no need of any other server side language. But sometimes we need to access the library created by some other languages like .net, java etc . ColdFusion runs on java platform so there is no issue in consuming the java library. The question here is how we can use the .net library.

The answer is by creating a "dll" in .net. Then ColdFusion will access the methods of the dll file by creating Object of that dll.

Example:
Now, I am going to create a Calculator library in .net(a dll file) which will have two methods addition and subtraction using the following .net code.

using System;
namespace Calculator
{
    public class Calculator
    {
        public int addition(int a, int b)
        {
            return a + b;
        }

        public int subtraction(int a, int b)
        {
            return a - b;
        }
    }
}


Then, I wrote the following lines of ColdFusion code to create object of that ".dll" file.

 <cfscript>
   variables.dotNetObject = createObject("dotnet", "Calculator", "#expandPath('./Calculator.dll')#").init();
   WriteDump(variables.dotNetObject);
</cfscript>

But, I got the one error message:

"DotNet Side does not seem to be running. Ensure that the DotNet agent is running and you have provided the correct host and port information "



Solution:

1. Go to the window services viewer and see whether  "ColdFusion  .NET Service" service is running or not. If not running then start the service. If the service is not Present then go to step 3.
2. After that check whether the code is again throwing the same error or not.
3. If it again throwing the same error then go to "http://help.adobe.com/en_US/ColdFusion/9.0/Installing/WSc3ff6d0ea77859461172e0811cdec18969-7ff1.html" and follow the instructions to reinstall/install the ColdFusion .net Service.

After, following  all the instructions and reinstalling the ColdFusion .net Service I again run the code. I got the following error:

"Class Calculator not found in the specified assembly list.The assembly that contains the class must be provided to the assembly attribute. "



Solution:-

In the above ColdFusion code, in the function createObject we are passing the class name as "Calculator" in the argument. Our class name in the above .net code is aslo "Calculator". Then what is the cause of the problem???

While creating a .net class we have to specify the name space of that class, if you are not specifying the name space then the Project will be taken as the default name space.
So, in the .net code our name space will be "" and during accesing the class we must have to sppecify the name space like this:"<name-space>.<class>".
In ColdFusion code instead of passing "Calculator" we have to pass "Calculator.Calculator". The out put of the Dump will be as follow:



The dump shows the object have two function addition and subtraction. Now, we can perform the operation like general ColdFusion Object.

NOTE: If you want to download the "Calculator.dll" then you can download it from this url:

https://docs.google.com/open?id=0B2GDR5_Jv000NUR2ZXMxeWhTbm0yQWZ0NUozVjRkZw



Tuesday, March 06, 2012

Export cfgrid Data or Table Data in Excel, Pdf and CSV Format(ColdFusion - 9)

Export cfgrid Data or Table Data in Excel, Pdf and CSV Format(ColdFusion - 9)

Below I have posted the sample code for exporting a table data in Excel/Pdf/CSV format. The code contains the comment line for each of the action. I think it will help you to understand.

<!--- The format to Which you want to Export the Data --->
<cfparam name="url.format" default="csv" />

<cftry>
    <cfset request.qryGetData = queryNew("") /><!--- The Query Object. To Which we will Export --->
    <cfset request.queryResult = structNew() /><!--- Result set of the Query Object --->
   
    <!--- Query to get data from the specified DSN. This DSN created when the ColdFusion is installed in your machine--->
    <cfquery name="request.qryGetData" datasource="cfdocexamples" result="request.queryResult">
        SELECT * FROM EMPLOYEES
    </cfquery>
   
    <!--- Check the format Requested to download and Prepare the Document Accordingly --->
    <cfif url.format EQ "csv">
       
        <!--- Preparing the CSV Document --->
        <cfset request.strCSVString = "" />
       
        <!--- Storing the comma separated column name in a string Object and Appending chr(13) and chr(10) for line break and carriage return--->
        <cfset request.strCSVString = request.strCSVString & "#request.qryGetData.columnList#" & chr(13) & chr(10) />
        <cfset request.rowArray = arrayNew(1) />
        <cfloop query="request.qryGetData">
            <cfset request.rowArray = arrayNew(1) />
            <cfset request.columnCntr = 1 />
           
            <!--- Stroing the row of a query object into an array--->
            <cfloop list="#request.qryGetData.columnList#" index="colname">
                <cfset request.rowArray[request.columnCntr] = request.qryGetData[colname][request.qryGetData.currentRow]>
                <cfset request.columnCntr += 1 />
            </cfloop>
           
            <!--- Converting the array into a list. So that the entire row will be converted into a comma separated  list--->
            <cfset request.strCSVString = request.strCSVString & arrayToList(request.rowArray) & chr(13) & chr(10) />
        </cfloop>
       
        <!--- Convert the comma separated string content into a CSV file(download.csv) and this file will be downloaded.--->
        <cfcontent type="application/csv">
        <cfheader name="content-disposition" value="inline; filename=download.csv">
        <cfoutput>#request.strCSVString#</cfoutput>
    <cfelseif url.format EQ "excel">
   
        <!--- Preparing the Query Object into tabular format --->
        <cfsavecontent variable="request.exportContent">
            <table>
                <tr>
                <cfoutput>
                   
                    <!--- Writting all Column Names as table header--->
                    <cfloop index="columnName" list="#request.queryResult.COLUMNLIST#">
                        <th>#columnName#</th>
                    </cfloop>
                </cfoutput>
                </tr>
               
                <!---Loop over the query object and get the column name dynamically from the result set and fetch the cell
                    value of table and write it in the string object--->
                <cfoutput query="request.qryGetData">
                    <tr>
                        <cfloop index="columnName" list="#request.queryResult.COLUMNLIST#">
                            <td>#evaluate("request.qryGetData.#columnName#")#</td>
                        </cfloop>
                    </tr>
                </cfoutput>
            </table>
        </cfsavecontent>
       
        <!--- Convert the tabular string data into an excel document(download.xls)--->
        <cfcontent type="application/msexcel">
        <cfheader name="content-disposition" value="inline; filename=download.xls">
        <cfoutput>#request.exportcontent#</cfoutput>
    <cfelseif url.format EQ "pdf">
   
        <!--- Preparing the Query Object into tabular format --->
        <cfsavecontent variable="request.exportContent">
            <table>
                <tr>
                <cfoutput>
                   
                    <!--- Writting all Column Names as table header--->
                    <cfloop index="columnName" list="#request.queryResult.COLUMNLIST#">
                        <th>#columnName#</th>
                    </cfloop>
                </cfoutput>
                </tr>
               
                <!---Loop over the query object and get the column name dynamically from the result set and fetch the cell
                    value of table and write it in the string object--->
                <cfoutput query="request.qryGetData">
                    <tr>
                        <cfloop index="columnName" list="#request.queryResult.COLUMNLIST#">
                            <td>#evaluate("request.qryGetData.#columnName#")#</td>
                        </cfloop>
                    </tr>
                </cfoutput>
            </table>
        </cfsavecontent>
       
        <!--- Convert the tabular string data into a pdf document(download.pdf)--->
        <cfheader name="content-disposition" value="inline; filename=download.pdf">
        <cfdocument format="pdf">
            <cfoutput>#request.exportcontent#</cfoutput>
        </cfdocument>
    <cfelse>
        Error in Preparing the Document.
    </cfif>
    <cfcatch>
        Error In Preparing the Document.
    </cfcatch>
</cftry>

By using the above code we can export a Query Object Data into different format.

Then how we will export cfgrid data with  a particular page no??
Ans:
 Just you have to pass two another parameter in the URL. i.e

<cfparam name="url.pageNo" default="1" />
<cfparam name="url.pageCount" default="100" />

Now, when we are looping over the query object for creating CSV/Tabular string we have to set the start and end value. Like the below:

<cfset request.start = ((url.pageNo - 1) * url.pageCount) + 1 />
<cfset request.end = (request.start - 1) + url.pageCount />

<cfloop 
    query = "query name"  //request.qryGetData
    startRow = "row number" // request.start
    endRow = "row number" //request.end
</cfloop>


Hope you will enjoy with the code. :)

Other Grid related topics:
1. Starting with CFGRID( part - 1 )
2. Starting with CFGRID( part - 2 )(Auto Refreshing CFGRID)
3. Conditionally Change the Color Of a Cell Text In cfgrid
4. Search Functionality in CFGRID
5. Export Query Object in Spreadsheet using spreadsheet object.


Wednesday, February 22, 2012

File Write Operation on a Shared Path on Different Computer in ColdFusion


  Generally file operation in ColdFusion is very simple, we only need a ColdFusion tag "CFFILE" to do the file operation like read,write,append and delete etc.

To make a simple file write Operation in ColdFusion we will write the code as follows:

<cffile action="write" file="D:/test.txt" output="Testing" />

To write this file(test.txt) in some shared directory like "\\192.168.10.208\Photos\", we will write the code as :

<cffile action="write" file="\\192.168.10.208\Photos\text.txt" output="Testing">

But, this code will give an error message:

"An error occured when performaing a file operation write on file \\192.168.10.208\test.txt.
The cause of this exception was: java.io.FileNotFoundException: \\192.168.10.208\Photos\test.txt (Access is denied)."

 

After getting this message I tried by creating "Map Network Drive" and also by creating a "Map Network Location" but all the testing was in vein.

The main Cause of the Error:
         The ColdFusion application doesn't have enough permission to access the shared directory. But, the user by which you have login to the system have rights to access the shared directory.
 
 
How we will give Permission to Our ColdFusion Server to Access the Network Shared Directory:

           The ColdFusion runs in Windows as a service and if we look ino all the services of the machine we will find as follow:

Here, you can notice that for ColdFusion service the LogOnAs value is "LocalSyatem". It means ColdFusion service is started as "LocalSystem" login and this login doesn't have enough permission to do any operation on network. So, in order to make the required file operation in the Shared Directory we will have to change the LogOnAs value for ColdFusion service.

How we will change the LogOnAs value for ColdFusion(or any window service):
  1. Right Click on the ColdFusion Service then click on "properties".
  2. Click on "Log On" tab. Then you will see a screen like this:


  1. Select "This account" radio button .Then click on "Browse" button and select the user by which you want to start the service. You should choose the user who have sufficient permission to create file on the shared directory and also have required permission in local.
  2. After the set up you can see the effect as follow(sample example): 
Here, you can notice the change in the "Log On As" value. But we have to restart the ColdFusion Service for the changes to effect.

After restarting, the code will work and we can able to write the file in a Shared directory of some other computer.

Followers