Archivos de Categoría: Coldfusion - Paginas 3

Custom tags de coldfusion

Cada vez se usan menos porque se tiende a usar funciones pero no hay que olvidarse de las posibilidades que pueden llegar a dar.

Para el que no sepa muy bien de lo que van, las custom tags (como su nombre indica) son etiquetas personalizadas que se pueden crear para hacer una determinada funcionalidad. A diferencia de los includes que son bloques de código, las custom tags pueden recibir parámetros directamente. Pero vayamos al ejemplo practico directamente.

Imaginemos que queremos crear formularios en serie que funcionen todos de la misma forma. Una forma de hacerlo sería hacer una custom para que cree una tabla, las etiquetas del formulario y el submit:

<!--- formulario.cfm --->
<cfparam name="Attributes.formName" type="string" default="miform">

<cfoutput>
<cfif ThisTag.ExecutionMode EQ "Start">
  <!--- cuando se ejecute el inicio de la custom tag --->
  <table cellspacing="0" cellpadding="0" border="0">
  <form name="#Attributes.formName#" method="Post">
<cfelse>
   <!--- cuando se ejecute el final de la custom tag --->
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Enviar"></td>
  </tr>
  </form>
  </table>
</cfif>
</cfoutput>

También podríamos crearnos una custom tag para los campos de los formularios:

<!--- campo.cfm --->
<cfparam name="Attributes.fieldName" type="string">
<cfparam name="Attributes.size" type="numeric">
<cfparam name="Attributes.maxLength" type="numeric">
<cfparam name="Attributes.label" type="string" default="#Attributes.fieldName#">

<cfoutput>
<tr>
  <td>#Attributes.label#&nbsp;&nbsp;</td>
  <td>
    <input
      type="text"
      name="#Attributes.fieldName#"
      size="#Attributes.size#"
      maxlength="#Attributes.maxlength#" >
  </td>
</tr>
</cfoutput>

De esta forma, crear un formulario sería tan sencillo como:

<cf_formulario formName="formu"> 
	<cf_campo fieldName="campo" size="50" maxLength="50" label="El campo1">
	<cf_campo fieldName="campo2" size="50" maxLength="50" label="El campo2">	
</cf_formulario>

Calcular dimensiones de una imagen subida

Ahora con el cfimage es bastante sencillo el tratamiento de imágenes pero antes tocaba pelearse con algo de java para poder hacerlo. Por ejemplo, comprobar que una imagen que acabas de subir tiene ciertas dimensiones:

<!--- --->
<cffile action="UPLOAD" filefield="imagen" destination="#GetDirectoryFromPath(GetCurrentTemplatePath())#" nameconflict="OVERWRITE">
	
	<cfset fichero = GetDirectoryFromPath(GetCurrentTemplatePath()) & File.ServerFile>
	
	<cfscript> 
        function imagen(fichero){
       		var oImage = createObject('java','java.awt.Toolkit');     
			var pk=oImage.getDefaultToolkit().getImage(fichero);    
			ancho = pk.getWidth(); 
   			alto = pk.getHeight();    
			return alto;   
		}	
	</cfscript> 
	
	<cfdump var = "#imagen(fichero)#">

Lo dicho, ahora con el cfimage se hace tan sencillo como:

<!---  --->
<cfimage source="imagen.jpg" action="info" structName="viatoInfo">
<cfdump var="#viatoInfo#">

<cfoutput>
    <p>height: #viatoInfo.height# pixels</p>
    <p>width: #viatoInfo.width# pixels</p>
</cfoutput>

Comprobar los DSN dados de alta en el servidor de coldfusion

Hace años navegando por internet me encontré estas interesantes funciones que sirven para sacar en una estructura de datos las distintas DSN dadas de alta en el servidor de coldfusion.

<cfset this = StructNew() >
<!--- ************************************************************ ---> 
<!--- ::
Name:	makeFactory
	* make a cffactory object
	* @return boolean of factory status
	:: --->		
	<cffunction name="makeFactory" returntype="boolean" hint="If possible create this.factory for cf service factory">
	     <cftry>
	        <cflock name="serviceFactory" type="exclusive" timeout="10">
                 <cfset this.factory = CreateObject("java", "coldfusion.server.ServiceFactory")>
			</cflock>
		    <cfcatch>
		      <cfthrow message="Could not create service factory object" type="Any" errorcode="0">
			   <cfreturn FALSE > 
		   </cfcatch>
		   </cftry>
            <cfreturn TRUE > 
	</cffunction>
<!--- ************************************************************ ---> 


<!--- ************************************************************ ---> 
<!--- ::
Name:	getAllDataSources
	* Get all the DSN details that CF can use
	* @return 	struct 	a struct of stucts that details the cf dsn
	:: --->		
		
	<cffunction name="getAllDataSources" returntype="boolean" hint="Creates this.datasources of  all data sources">
	    <cfif NOT isDefined("this.factory")>
		   <cfset makeFactory() >
		</cfif>
	      <cftry>
	        <cflock name="serviceFactory" type="exclusive" timeout="10">
                 <!--- factory.DataSourceService.getDatasources()is a struc of stucs that details the cf dsn  --->
				 <cfset this.AllDataSources = this.factory.DataSourceService.getDatasources() >
               </cflock>
		    <cfcatch>
		      <cfthrow message="Could not create data sources structure from factory." type="Any" errorcode="0">
			   <cfreturn FALSE > 
		    </cfcatch>
		    </cftry>
		    <cfreturn TRUE > 
	</cffunction>
<!--- ************************************************************ ---> 

<!--- ************************************************************ ---> 
<!--- ::
Name:	showAllDataSources
	* Shows all cffactory data sources
	* @return 	struct
	:: --->		
		
	<cffunction name="showAllDataSources" returntype="any" hint="Shows all cffactory data sources">
	      <cfset getAllDataSources() >
		  <cfreturn this.AllDataSources > 
	</cffunction>
<!--- ************************************************************ ---> 

<cfdump var="#showAllDataSources()#" label="showAllDataSources" expand="no">

Otra opción bastante más sencilla usando algo de java:

<cfscript>
function getDSNs() {
	var factory = createObject("java","coldfusion.server.ServiceFactory");
	return factory.getDataSourceService().getNames();
}
</cfscript>

<cfdump var="#getDSNs()#">

No es que se use a menudo pero si me sirvió para darle un tirón de orejas a uno de sistemas que decía haber creado una DSN a una base de datos y demostrarle al muy zote no es lo mismo hacerlo desde el administrador de coldfusion que desde DSN de sistema…..