EzDevInfo.com

coldfusion interview questions

Top coldfusion frequently asked interview questions

ColdFusion SOAP response with attachments

I am using Coldfusion9 to interact with a 3rd party SOAP service with which I need to both send and receive SOAP with attachments. I am having no issue in receiving the SOAP which may or may not have binary attachments by using ToString() around the HTTP content to convert the SOAP Body into a usable string, however the service requires that I send my response back using attachments as well which is where I am coming undone. I've just never done this in ColdFusion and i'm not exactly sure how I should be presenting this to the originating service so that the SOAP body is referenced via an ID.

Below is the parsing of the incoming SOAP data with attachments:

<cfset soapData = GetHttpRequestData()>

<!--- Loop over the HTTP headers and dump the SOAP content into a variable --->
<cfsavecontent variable="soapContent">
<cfoutput>      
    <cfloop collection = #soapData.headers# item = "http_item">
    #http_item#: #StructFind(soapData.headers, http_item)# #chr(10)##chr(13)# 
    </cfloop>
    request_method: #soapData.method# #chr(10)##chr(13)# 
    server_protocol: #soapData.protocol# #chr(10)##chr(13)# 
    http_content --- #chr(10)##chr(13)#  
    #toString(soapData.content)#
</cfoutput>
</cfsavecontent>

<!--- Save file to flat file --->
<cffile action = "write" 
    file = "#expandPath('../')#logs/#dateFormat(now(),'dd-mm-yyyy')#_#timeFormat(now(),'HHmmss')#.txt" 
    output = "#soapContent#">

Now I am currently presenting the response as a full SOAP XML response containing the body as inline XML with the required STATUSCODE (see below).

<cfsavecontent variable="strResponse">
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
    <SOAPENV:Body>
        <ns1:processResponse xmlns:ns1="urn:TripFlow" SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
            <STATUSLVL>00</STATUSLVL>
        </ns1:processResponse>
    </SOAP-ENV:Body>
</SOAPENV:Envelope>
</cfsavecontent>

<!--- Strip all whitespace between tags --->
<cfset strResponse = trim(ReReplaceNoCase(strResponse,'(>[\s]*<)','><','ALL'))>

<!--- Output the XML response to the soap service --->
<cfoutput>#strResponse#</cfoutput>

The above response is throwing an error because the SOAP service requires the response to be sent referencing the body message as an attachment exactly like follows from the documentation:

HTTP/1.1 200 OK
Date: Thu, 01 Apr 2010 09:30:25 GMT
Server: Jetty/5.1.4 (Windows XP/5.1 x86 java/1.5.0_15
Content-Type: multipart/related; boundary=soaptestserver; type="text/xml"; start="<theenvelope>"
SOAPAction: ""
Content-Length: 796
Connection: close

--soaptestserver
Content-ID: <theenvelope>
Content-Transfer-Encoding: 8bit
Content-Type: text/xml; charset=utf-8
Content-Length: 442

<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAPENV="
http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"><SOAPENV:
Body><ns1:processResponse xmlns:ns1="urn:TripFlow" SOAPENV:
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><message
rel='nofollow' href="cid:thecontentmessage"/></ns1:processResponse></SOAP-ENV:Body></SOAPENV:
Envelope>

--soaptestserver
SOAP Interface
www.travelsolutions.com 123
travel solutions online V14.0 External System Integration
Content-ID: <thecontentmessage>
Content-Transfer-Encoding: 8bit
Content-Type: text/xml; charset=utf-8
Content-Length: 65

<?xml version="1.0" encoding="UTF-8"?><STATUSLVL>00</STATUSLVL>
--soaptestserver--

Any help would be greatly appreciate as i'm really hitting my head up against a wall on this one. Thanks!


Source: (StackOverflow)

Can I get a query row by index in ColdFusion?

I want to get a specific row in a ColdFusion Query object without looping over it.

I'd like to do something like this:

<cfquery name="QueryName" datasource="ds">
SELECT *
FROM    tablename
</cfquery>

<cfset x = QueryName[5]>

But it's giving me an error saying that the query isn't indexable by "5". I know for a fact that there are more than 5 records in this query.


Source: (StackOverflow)

Advertisements

Join Two Arrays in ColdFusion

Is there a built-in way to join two arrays in ColdFusion, similar to JavaScript's array.concat()?


Source: (StackOverflow)

Upload Files To Google Drive Using ColdFusion

*NEW UPDATED FOR BETTER SECOND PART - NOW GETS TO "308 Resume Incomplete", even though file should be just one upload!

I am using the foundation of cfgoogle from Ray Camden. But Google has deprecated the code for document uploads. The new standard is Resumable Media Uploads.

I have this part working (up to and including the "Initiating a resumable upload request") in the above referenced Google document.

Calling Page:

<cfset application.cfc.Google                   = createObject('component','#path_cf_cfc#Google') />
<cfset application.cfc.GoogleDocs               = createObject('component','#path_cf_cfc#GoogleDocs') />

<cfset gtoken = application.cfc.GoogleDocs.authenticate(emailaddress,password)>

<CFSET testdoc = "a\filepath\documentname.doc">
<CFSET FileType = "application/msword">
<CFSET FileTitle = "test_001">

<cfset temp = application.cfc.GoogleDocs.upload_auth("#Application.Map.DocStorage##tv.testdoc#",FileType,FileTitle)>  

<CFSET uploadpath = Listgetat(Listgetat(temp.header,ListContains(temp.header,"https://docs.google.com","#chr(10)#"),"#chr(10)#"),2," ") >  

<cfset temp2 = application.cfc.GoogleDocs.upload_file("#Application.Map.DocStorage##tv.testdoc#",FileType,FileTitle,uploadpath)>

The code works up to and including the cfset temp line (getting the unique upload URI)

Here is the code for upload_auth:

<cffunction name="upload_auth" access="public" returnType="any" hint="I get a uniqu URI from Google API." output="false">
<cfargument name="myFile" type="string" required="true" hint="filepath to upload.">
<cfargument name="myType" type="string" required="true" hint="application/msword"> 
<cfargument name="myTitle" type="string" required="true" hint="name of doc"> 

<cfset GoogleUrl = "https://docs.google.com/feeds/upload/create-session/default/private/full">
<cfset GoogleVersion = 3> 
<cfset FileSize = createObject("java","java.io.File").init(myFile).length()>

<cfhttp url="#GoogleUrl#" method="post" result="diditwork" resolveurl="no">
<cfhttpparam type="header" name="Authorization" value="GoogleLogin auth=#getAuth(variables.docservice)#">
<cfhttpparam type="header" name="GData-Version" value="#GoogleVersion#">
<cfhttpparam type="header" name="Content-Length" value="0">
<cfhttpparam type="header" name="X-Upload-Content-Type" value="#myType#">
<cfhttpparam type="header" name="X-Upload-Content-Length" value="#FileSize#">
<cfhttpparam type="header" name="Slug" value="#myTitle#">

</cfhttp>

<cfreturn diditwork>
</cffunction>

OK - So Far So Good. But here is where it breaks down:

Running upload_file returns "308 Resume Incomplete" (A lest it's not a 400!) from Google. Arrgh!!

Here is the upload_file -

<cffunction name="upload_file" access="public" returnType="any" hint="I upload the document." output="false">
<cfargument name="myFile" type="string" required="true" hint="filepath to upload.">
<cfargument name="myType" type="string" required="true" hint="like application/msword"> 
<cfargument name="myTitle" type="string" required="true" hint="name of doc"> 
<cfargument name="myAuthPath" type="string" required="true" hint="call auth"> 

<cfset FileSize = GetFileInfo(myFile).size >
<CFSET tv.tostartwithzero = FileSize - 1>

<CFFILE action="read" file="#myfile#" variable="FileText">

<cfhttp url="#myAuthPath#" method="put" result="diditwork" resolveurl="no" multipart="yes" charset="utf-8" >
<cfhttpparam type="header" name="Authorization" value="GoogleLogin auth=#getAuth(variables.docservice)#">
<cfhttpparam type="header" name="GData-Version" value="#variables.GoogleVersion#">
<cfhttpparam type="header" name="Content-Length" value="#FileSize#">
<cfhttpparam type="header" name="Content-Range" value="bytes 0-#tv.tostartwithzero#/#FileSize#">
<cfhttpparam type="header" name="Content-Type" value="#myType#">

<cfhttpparam type="body" value="#trim(FileText)#">

</cfhttp>

<cfreturn diditwork>
</cffunction>

So, there we have it - where I am stuck. I can get the unique URI, but (maybe because it is late at night) I'm brain dead on what I am doing wrong otherwise to complete the file upload.

All help is appreciated.


Source: (StackOverflow)

cfqueryparam with like operator in ColdFusion

I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <cfqueryparam> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?

If my query looks like this:

select * from Foo where name like '%Bob%'

what should my <cfqueryparam> tag look like?


Source: (StackOverflow)

ColdFusion: More efficient structKeyExists() instead of isDefined()

Which of these is more efficient in ColdFusion?

isDefined('url.myvar')

or

structKeyExists(url, 'myvar')

Source: (StackOverflow)

How to reload printers in coldfusion without restarting service?

This is my basic understanding of how to make a printer available to use in ColdFusion.

  1. Remote into the server running CF using the account that the CF service is running under.
  2. Open the windows control panel and add the printer.
  3. Restart the CF service.

My question: is there any way to reload the printers without restarting the CF service?

This is the issue we are trying to troubleshoot. CF error detail:

Error: Printer \\(server)\(printerName) is not available. Available printers are: , şៈ᠘, , , , 凙ᜀᚈ, , 疠쐵䚏, , .

Restarting the CF service fixes this but it seems to be happening pretty often lately. I am wondering if there is some java code to reload the printers so it can be done automatically. We are using CF9.


Source: (StackOverflow)

How do I correctly pass the string "Null" (an employee's proper surname) to a SOAP web service from ActionScript 3?

We have an employee whose last name is Null. Our employee lookup application is killed when that last name is used as the search term (which happens to be quite often now). The error received (thanks Fiddler!) is:

  <soapenv:Fault>
   <faultcode>soapenv:Server.userException</faultcode>
   <faultstring>coldfusion.xml.rpc.CFCInvocationException: [coldfusion.runtime.MissingArgumentException : The SEARCHSTRING parameter to the getFacultyNames function is required but was not passed in.]</faultstring>

Cute, huh?

The parameter type is string.

I am using:

  • WSDL (SOAP).
  • Flex 3.5
  • ActionScript 3
  • ColdFusion 8

Note that the error DOES NOT occur when calling the webservice as an object from a ColdFusion page.


Source: (StackOverflow)

Select one column DISTINCT SQL

Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator)

Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example:

**Table**
Value A, Value L, Value P
Value A, Value Q, Value Z

I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of).

Here's what I've got so far, although it doesn't work obviously:

SELECT value, attribute_definition_id, value_rk
FROM attribute_values
WHERE value IN (
	SELECT value, max(value_rk)
	FROM attribute_values
)
ORDER BY attribute_definition_id

I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value_rk is my big problem since every value is unique but I only need one.

NOTE: value_rk is not a number, hence this DOES NOT WORK

UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value_rk for the value that matches. Like so:

<cfquery name="queryBaseValues" datasource="XXX" timeout="999">
    SELECT DISTINCT value, attribute_definition_id
    FROM attribute_values
    ORDER BY attribute_definition_id
</cfquery>

<cfoutput query="queryBaseValues">
    <cfquery name="queryRKValue" datasource="XXX">
        SELECT TOP 1 value_rk
        FROM attribute_values
        WHERE value = '#queryBaseValues.value#'
    </cfquery>
    <cfset resourceKey = queryRKValue.value_rk>
    ...

So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)


Source: (StackOverflow)

How to suppress the file corrupt warning at Excel download?

I have a web page which links to an Excel 2007 worksheet. It is a .xls file and not .xlsx file. When I click on the link I get the usual dialog box to either open/save the Excel file. On clicking 'Open', I get the following warning message-

The file you are trying to open, 'filename.xls' is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

Can I some how suppress this warning message programmatically (i.e. to hide it or prevent it from showing up?) I'm using ColdFusion for web development.


Source: (StackOverflow)

Trying to find a syntax highlighter for ColdFusion in Notepad++

I use CFEclipse for most of my projects and heavy lifting but sometimes I find the need to do a quick fix on pages outside the project scope that is easier to accomplish in a simple text editor.

I have googled but can't seem to find an answer so either a link to a download or a link to how to build my own would be awesome. thanks.


Source: (StackOverflow)

White Space / Coldfusion

What would be the correct way to stop the white space that ColdFusion outputs?

I know there is cfcontent and cfsetting enableCFoutputOnly. What is the correct way to do that?


Source: (StackOverflow)

How to sort an array of structs in ColdFusion

I have an array of structs in ColdFusion. I'd like to sort this array based on one of the attributes in the structs. How can I achieve this? I've found the StructSort function, but it takes a structure and I have an array.

If this is not possible purely in ColdFusion, is it possible in Java somehow (maybe using Arrays.sort(Object[], Comparator))?


Source: (StackOverflow)

Is there a way to 'listen' for a database event and update a page in real time?

I'm looking for a way to create a simple HTML table that can be updated in real-time upon a database change event; specifically a new record added.

In other words, think of it like an executive dashboard. If a sale is made and a new line is added in a database (MySQL in my case) then the web page should "refresh" the table with the new line.

I have seen some information on the new using EVENT GATEWAY but all of the examples use Coldfusion as the "pusher" and not the "consumer". I would like to have Coldfusion both update / push an event to the gateway and also consume the response.

If this can be done using a combination of AJAX and CF please let me know!

I'm really just looking to understand where to get started with real-time updating.

Thank you in advance!!

EDIT / Explanation of selected answer:

I ended up going with @bpeterson76's answer because at the moment it was easiest to implement on a small scale. I really like his Datatables suggestion, and that's what I am using to update in close to real time.

As my site gets larger though (hopefully), I'm not sure if this will be a scalable solution as every user will be hitting a "listener" page and then subsequently querying my DB. My query is relatively simple, but I'm still worried about performance in the future.

In my opinion though, as HTML5 starts to become the web standard, the Web Sockets method suggested by @iKnowKungFoo is most likely the best approach. Comet with long polling is also a great idea, but it's a little cumbersome to implement / also seems to have some scaling issues.

So, let's hope web users start to adopt more modern browsers that support HTML5, because Web Sockets is a relatively easy and scalable way to get close to real time.

If you feel that I made the wrong decision please leave a comment.

Finally, here is some source code for it all:

Javascript:

note, this is a very simple implementation. It's only looking to see if the number of records in the current datatable has changed and if so update the table and throw an alert. The production code is much longer and more involved. This is just showing a simple way of getting a close to real-time update.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript" charset="utf-8">

var originalNumberOfRecsInDatatable = 0;
var oTable;

var setChecker = setInterval(checkIfNewRecordHasBeenAdded,5000); //5 second intervals

function checkIfNewRecordHasBeenAdded() {

        //json object to post to CFM page
        var postData = {
        numberOfRecords:  originalNumberOfRecsInDatatable 
        };

        var ajaxResponse = $.ajax({
        type: "post",
        url: "./tabs/checkIfNewItemIsAvailable.cfm",
        contentType: "application/json",
        data: JSON.stringify( postData )
        })

        // When the response comes back, if update is available
        //then re-draw the datatable and throw an alert to the user
        ajaxResponse.then(
        function( apiResponse ){

         var obj = jQuery.parseJSON(apiResponse);

         if (obj.isUpdateAvail == "Yes")
         {              
            oTable = $('#MY_DATATABLE_ID').dataTable();
            oTable.fnDraw(false);

            originalNumberOfRecsInDatatable = obj.recordcount;

            alert('A new line has been added!');
         }

        }
        );

    }
</script>

Coldfusion:

<cfset requestBody = toString( getHttpRequestData().content ) />

<!--- Double-check to make sure it's a JSON value. --->
<cfif isJSON( requestBody )>

<cfset deserializedResult = deserializeJSON( requestBody )>

<cfset numberOFRecords = #deserializedResult.originalNumberOfRecsInDatatable#>


<cfquery  name="qCount" datasource="#Application.DBdsn#" username="#Application.DBusername#" password="#Application.DBpw#">
    SELECT COUNT(ID) as total
    FROM myTable
</cfquery>

<cfif #qCount.total# neq #variables.originalNumberOfRecsInDatatable#>
    {"isUpdateAvail": "Yes", "recordcount": <cfoutput>#qCount.total#</cfoutput>}
<cfelse>
    {"isUpdateAvail": "No"}
</cfif>


</cfif>

Source: (StackOverflow)