Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS 

Directory Compare

ColdFusion - Compare two directories and report:
1. What files exist in folder A, but not B.
2. What files exist in folder B, but not A.
3. What files exist in both, but appear different.

<cfsetting requesttimeout="9999">

<cfparam name="FORM.DevelopmentDirectory" default="/kkkkkk/lllll/bbbb/ccc">
<cfparam name="FORM.ProductionDirectory" default="/mmmmmm/ggggg/bbbb/ccc">
<cfparam name="FORM.CommonDirectory" default="/ccc">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Directory Compare</title>
</head>

<body>

<h3>Directory Compare</h3>
<form name="directoryCompare" action="index.cfm" method="post">
<table>
	<tr>
    	<td>Development Directory</td>
        <td><input name="DevelopmentDirectory" id="DevelopmentDirectory" type="text" value="<cfoutput>#FORM.DevelopmentDirectory#</cfoutput>" size="70"></td>
    </tr>
	<tr>
    	<td>Production Directory</td>
        <td><input name="ProductionDirectory" id="ProductionDirectory" type="text" value="<cfoutput>#FORM.ProductionDirectory#</cfoutput>" size="70"></td>
    </tr>
	<tr>
    	<td>Common Directory</td>
        <td><input name="CommonDirectory" id="CommonDirectory" type="text" value="<cfoutput>#FORM.CommonDirectory#</cfoutput>" size="40"></td>
    </tr>
    <tr>
    	<td>&nbsp;</td>
        <td><input type="submit" name="submit" value="submit"></td>
    </tr>
</table>
</form>

<cfif isdefined('FORM.submit')>

<cfdirectory action="list" directory="#FORM.ProductionDirectory#" name="prodDir" recurse="yes">
<!--- <cfdump var="#prodDir#"> --->
<cfdirectory action="list" directory="#FORM.DevelopmentDirectory#" name="devDir" recurse="yes">
<!--- <cfdump var="#devDir#"> --->


<!--- Need common directory base to compare --->
<cfset dev_strip = Mid(FORM.DevelopmentDirectory,1,FindNoCase(FORM.CommonDirectory,FORM.DevelopmentDirectory))>
<cfset prod_strip = Mid(FORM.ProductionDirectory,1,FindNoCase(FORM.CommonDirectory,FORM.ProductionDirectory))>


<!--- o = Output Container --->
<cfset o = StructNew()>
<cfset o.keys = ArrayNew(1)>


<cfloop query="prodDir">

	<!--- Put array string in the order that will sort correctly --->
	<cfset L = prodDir.TYPE & "|" & ReplaceNoCase(prodDir.DIRECTORY,prod_strip,"","all") & "/" & prodDir.NAME >
	<!--- Turn the type/dir/name into something that makes a valid variable name --->
	<cfset k = "K" & cfusion_encrypt(L,"key")>

	<!--- Have we encountered this entry before? --->
	<!--- This also filters duplicates between the two queries. --->
	<cfif not StructKeyExists(o,k)>
		<!--- Add to list of valid values --->
		<cfset ArrayAppend(o.keys,L & "|" & k)>
        <cfset o[k] = StructNew()>
		<cfset o[k].prod_path = "">
		<cfset o[k].prod_type = "">
		<cfset o[k].prod_size = "">
		<cfset o[k].dev_path = "">
		<cfset o[k].dev_type = "">
		<cfset o[k].dev_size = "">
	</cfif>

	<cfset o[k].prod_path = prodDir.DIRECTORY & "/" & prodDir.NAME>
	<cfset o[k].prod_type = prodDir.TYPE>
	<cfset o[k].prod_size = prodDir.SIZE>

</cfloop>
<!--- <cfdump var="#o#"> --->


<cfloop query="devDir">

	<!--- Put array string in the order that will sort correctly --->
	<cfset L = devDir.TYPE & "|" & ReplaceNoCase(devDir.DIRECTORY,dev_strip,"","all") & "/" & devDir.NAME >
	<!--- Turn the type/dir/name into something that makes a valid variable name --->
	<cfset k = "K" & cfusion_encrypt(L,"key")>

	<!--- Have we encountered this entry before? --->
	<!--- This also filters duplicates between the two queries. --->
	<cfif not StructKeyExists(o,k)>
		<!--- Add to list of valid values --->
		<cfset ArrayAppend(o.keys,L & "|" & k)>
        <cfset o[k] = StructNew()>
		<cfset o[k].prod_path = "">
		<cfset o[k].prod_type = "">
		<cfset o[k].prod_size = "">
		<cfset o[k].dev_path = "">
		<cfset o[k].dev_type = "">
		<cfset o[k].dev_size = "">
	</cfif>

	<cfset o[k].dev_path = devDir.DIRECTORY & "/" & devDir.NAME>
	<cfset o[k].dev_type = devDir.TYPE>
	<cfset o[k].dev_size = devDir.SIZE>

</cfloop>
<!--- <cfdump var="#o#"> --->


<cfset ArraySort(o.keys,"textnocase","asc")>


<cfoutput>
<table cellspacing="0" border="0" cellpadding="3">
	<tr>
        <th>Development</th>
    	<th>Production</th>
    </tr>
	<cfloop index="i" from="1" to="#ArrayLen(o.keys)#">
	    <cfset k = ListLast(o.keys[i],"|")>
	<tr>
    	<!--- DEV --->
        <td style="border-bottom:1px solid ##CCCCCC;">
        	<cfif o[k].prod_path EQ "">
            	<!--- On Dev NOT on Prod --->
				<span style="color:##0000FF; font-weight:bold;">
            <cfelse>
            	<cfif o[k].prod_size NEQ o[k].dev_size>
                	<!--- On Dev and On Prod, but Differnet --->
					<span style="color:##FF9900; font-weight:bold;">
                <cfelse>
                	<!--- On Dev and On Prod and The Same (probably) --->
					<span>
				</cfif>
			</cfif>
        	#o[k].dev_path#&nbsp;
            </span>
			<cfif o[k].dev_path NEQ "">
            <span style="font-size:smaller; color:##999999;">(#o[k].dev_size#)</span>
            </cfif>
        </td>
        <!--- PROD --->
    	<td style="border-bottom:1px solid ##CCCCCC;">
        	<cfif o[k].dev_path EQ "">
            	<!--- On Prod NOT On Dev --->
				<span style="color:##FF0000; font-weight:bold;">
            <cfelse>
            	<cfif o[k].prod_size NEQ o[k].dev_size>
                	<!--- On Dev and On Prod, but Differnet --->
					<span style="color:##FF9900; font-weight:bold;">
                <cfelse>
                	<!--- On Dev and On Prod and The Same (probably) --->
					<span>
				</cfif>
			</cfif>
        	#o[k].prod_path#&nbsp;
            </span>
			<cfif o[k].prod_path NEQ "">
            <span style="font-size:smaller; color:##999999;">(#o[k].prod_size#)</span>
            </cfif>
        </td>
    </tr>
    </cfloop>
</table>
</cfoutput>
</cfif>

</body>
</html>

Email a JavaScript Error using ColdFusion

This script emails an administrator when an error occurs, and could easily be adapted to log the error instead

/*
wwJsError (requires prototype.js)
		send:	sends javascript error output email via coldfusion
		--------------------
			path:		relative path from the calling page to the coldfusion
					email handler for this application (usually processJSerror.cfm)
			funcname:	name of the JavaScript function that threw an error
			name:		JavaScript error name (usually e.name in a catch block)
			message:	JavaScript error message (usually e.message in a catch block)
*/
var wwJsError = {
	send: function(path,funcname,name,message) {
		try {

			var url = path;

			var pars = 'message=' + escape(message) + '&name=' +
					escape(name) + '&funcname=' + escape(funcname);
			
			var httpMail = new Ajax.Request (
				url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: Prototype.emptyFunction
				}
			);
	
		} catch (e) {
			//if sending the email fails, just die quietly w/ no browser error
			Prototype.emptyFunction();
		}
	}
}; //end wwJsError

Sample server-side script in ColdFusion
<cfmail to="#application.administratoremail#" from="#application.administratoremail#"
		subject="#application.apptitle# Error" type="HTML">
	<strong>JavaScript Error:</strong> #form.funcname# threw the following error:<br />
	<br />
	<strong>Error name:</strong> #form.name#<br />
	<strong>Error:</strong> #form.message#
</cfmail>

Generate the error
function makeError() {
	try {
		alert(anError);
	} catch(e) {
		wwJsError.send('cf/processJSerror.cfm','makeError()',e.name,e.message);
	}
}

Result by email

JavaScript Error: makeError threw the following error:

Error name: TypeError
Error: 'anError' is undefined

Current year

// outputs current year

#year(now())#.

Clean magic quoting in ColdFusion 5 and later

I'm updating my weblog software and needed some code to properly convert typewriter quotes to proper typographer's quotes.

<cfscript>
function magicQuote(txt) {
    // Left quotes
    txt = REReplace(txt, "(^|[ " & Chr(9) & Chr(10) & Chr(13) & "'])""", "\1&##8220;", "ALL");
    txt = REReplace(txt, "(^|[ " & Chr(9) & Chr(10) & Chr(13) & "]|&##8220;)'",  "\1&##8216;", "ALL");

    // Right quotes
    txt = Replace(txt, """",        "&##8221;",  "ALL");
    txt = Replace(txt, "'&##8220;", "'&##8221;", "ALL");
    txt = Replace(txt, "'",         "&##8217;",  "ALL");

    return txt;
}
</cfscript>

ColdFusion 5 has problems with \s, and the character class is a workaround for this.

My ColdFusion Tagging Engine/Library

//via:http://www.whatspop.com/blog/2005/12/my-coldfusion-tagging-enginelibrary.cfm

<cfset tags_list = " CaMELCaSE comma, 'singlequoted' <b>bold</b> ""doublequoted"" double double this should be over the limit now " />

<cfset amount = 10 />
<cfset length = 20 />

<cfset tags_list = trim(tags_list) />
<cfset tags_list = lcase(tags_list) />

<cfset tags_struct = structnew() />
<cfloop index="tag" list="#tags_list#" delimiters=" ">
<cfset tags_struct[tag] = "" />
</cfloop>
<cfset tags_list = structkeylist(tags_struct," ") />
<cfset tags_list = listsort(tags_list, "textnocase", "asc", " ") />

<cfif tags_list neq "">
<cfif listlen(tags_list," ") lte amount>
<cfset amount = listlen(tags_list," ") />
</cfif>
<cfloop from="1" to="#amount#" index="tag">
/* Perform a database upload here */
<cfoutput>#htmleditformat(left(listgetat(tags_list,tag," "),length))#</cfoutput>
</cfloop>
<cfelse>
Sorry, you need to provide at least one tag
</cfif>

Customtag to remove blank lines

// description of your code here
Coldfusion output has a lot of useless blank lines and makes the HTML code hard to read. I use this customtag to remove the blank lines.

<cfif thisTag.ExecutionMode IS "end">
	<cfset thisTag.generatedContent =  ReReplaceNoCase(thisTag.generatedContent, '(?m)^\s+\r\n', '', "ALL")>
</cfif>

Creating a PDF using iText and ColdFusion

// description of your code here

<cfscript>
// create document
document 		= CreateObject("java", "com.lowagie.text.Document");
document.init();

// writer
fileIO 			= CreateObject("java", "java.io.FileOutputStream");
fileIO.init(pdf_path);
writer 			= CreateObject("java", "com.lowagie.text.pdf.PdfWriter");
writer.getInstance(document, fileIO);
document.open();

// newsinfo header image
Image 			= CreateObject("java", "com.lowagie.text.Image");
jpg 			= Image.getInstance(header_image);
jpg.setAbsolutePosition(28, 713);
jpg.setDpi(300,300);
document.add(jpg);

// top margin; dumb i know but i was in a hurry
paragraph = CreateObject("java", "com.lowagie.text.Paragraph");
paragraph.init(" ");
for (i=0; i lt 9; i=i+1) {
	document.add(paragraph);
}

// the fonts
FontFactory 	= createobject("java", "com.lowagie.text.FontFactory");
Font 			= createObject("java", "com.lowagie.text.Font");
TimesLargeBI 	= Font.init(Font.TIMES_ROMAN, 14.0, Font.BOLDITALIC);
TimesNormal 	= Font.init(Font.TIMES_ROMAN, 12.0);

// all the text
paragraph 		= CreateObject("java", "com.lowagie.text.Paragraph");

paragraph.init("Hello World!", TimesLargeBI);
paragraph.setIndentationLeft(indentation_left);
paragraph.setIndentationRight(indentation_right);
document.add(paragraph);

paragraph.init("#dateFormat(now(), 'long')#", TimesNormal);
paragraph.setIndentationLeft(indentation_left);
paragraph.setIndentationRight(indentation_right);
document.add(paragraph);

document.close();
</cfscript> 

Coldfusion Whois component

A whois cfc for querying a whois client.

whois.cfc
<cfcomponent name="WhoIs" output="true">

   <!--- the host to connect to --->
   <cfset variables.server = "">
   <!--- port on server to connect to --->
   <cfset variables.port = "">
   <!--- the whois query to run --->
   <cfset variables.whoisQuery = "">
   <!--- socket timeout in seconds --->
   <cfset variables.connTimeout = 0>
   <!--- the result of the server response --->
   <cfset variables.response = "">

   <cffunction name="init" access="public" returntype="WhoIs" hint="">
      <cfargument name="server" type="string" default="whois.geektools.com"/>
      <cfargument name="port" type="numeric" default="43"/>
      <cfargument name="connTimeout" type="numeric" default="30" hint="Socket timeout in seconds"/>
      
      <cfscript>
         variables.server = arguments.server;
         variables.port = JavaCast("int",arguments.port);
         variables.connTimeout = (arguments.connTimeout * 1000);
         
         //create before use          variables.connection = createObject("java","java.net.Socket").init(variables.server,variables.port);
         
         //dump(variables.connection,true);       </cfscript>
      
      <cfreturn this>
   </cffunction>
   
   <cffunction name="lookup" access="public" returntype="any" hint="">
      <cfargument name="whoisQuery" type="string" required="true"/>
      <cfset var line = "">
      <cfset var eof = false>
      
      <cfscript>
         variables.whoisQuery = arguments.whoisQuery;
         variables.connection.setSoTimeout(JavaCast("int",variables.connTimeout));
         out = createObject("java","java.io.PrintStream").init(variables.connection.getOutputStream());
         //send the query to the server          out.println(variables.whoisQuery);
         variables.response = variables.response & "Connection made to: " & "[" & variables.server & ":" & variables.port & "]";
         
         instream = createObject("java","java.io.BufferedReader").init(createObject("java","java.io.InputStreamReader").init(variables.connection.getInputStream() ));
         
         
         try {
            //output results             while(not eof) {
               line = instream.readLine();
               variables.response = variables.response & line & "#chr(10)#";
            }
         }   
         //coldfusion cant check for null so check for an UndefinedVariableException          catch(coldfusion.runtime.UndefinedVariableException exception) {
               eof = true;
         }
         catch(Any e){
            writeOutput("Catch All Exception: " & e);
         }
         out.close();
         instream.close();
         variables.connection.close();
      </cfscript>
      
      <cfreturn variables.response>
      
   </cffunction>
   
   
   <cffunction name="dump" access="public" returntype="void" output="true" hint="">
      <cfargument name="var" type="any" required="true"/>
      <cfargument name="abort" type="boolean" default="false"/>
      
      <cfdump var="#arguments.var#" label="#arguments.var#">
      <cfif arguments.abort><cfabort></cfif>
   </cffunction>
   

   
</cfcomponent>


index.cfm
<cfscript>
   wi = createObject("component","WhoIs").init("whois.geektools.com",43,10);
   results = wi.lookup("google.com");
   writeOutput(htmlCodeFormat(results));
</cfscript>

Simple Cold Fusion Script That Generates HTML Select List Combo


<!-- ## Simple Cold Fusion Script That Generates HTML Select List Combo ## -->
<!-- ## That Allows User To Enter Date Of Birth ## -->
<!-- ## Uploaded by James Cullin (james.cullin@humber.ca) ## -->
<!-- ## http://jamescullin.com ## -->

<cfoutput>

<select>
	<option> - Month - </option>
	<cfloop index="m" list="January, February, March, April, May, June, July, August, September, October, November, December" delimiters=",">
	<option value="#m#">#m#</option>
	</cfloop>
</select>

<select>
	<option> - Day - </option>
	<cfloop index="d" from="1" to="31" step="1">
	<option value="#d#">#d#</option>
	</cfloop>
</select>

<select>
	<option> - Year - </option>
	<cfloop index="y" from="2004" to="1900" step="-1">
	<option value="#y#">#y#</option>
	</cfloop>
</select>

</cfoutput>

Alternate table cell background color

BGCOLOR="###IIF(currentrow MOD 2, DE ('FFFFCC'), DE ('FFFFFF'))#"
« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS