Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Jun 25, 2010

jQuery week calendar

Hi there, a short post to annonce that I'm the new jquery week calendar's lead developper. so, if you are looking for an event calendar or a planner, have a look to it !

Jun 30, 2008

Vista gadget transparent background

  1. Introduction
  2. Single part background
  3. Multi part background
  4. Conclusion

As you may know, i've been working on Vista sidebar's gadgets for a while now, and i had to deal with a lot of specifics problems. Indeed, gadget development is very similar to IE web browser programing, but Microsoft thought it was smart to add some specificities, just as if they had no way to modify the IE7 rendering engine nor the win32 API to fit the gadget needs.
Well, now it is the way it is, the only solution is to deal with the given platform.

If you ever tried to create a partially transparent background gadget, you may have experienced one of following problem:

  • pink effect: the pink outline around images or text over transparent parts
  • black background: a black background coming from nowhere

If you didn't, you're lucky, if you did and didn't find a workaround, i'll try to give a method in this article.

Table of content

To have a single part background, you'll need an empty gadget and a png image representing your gadget background. I assume you already have all this.

First to show your gadget background, you need to define an HTML element to receive the image. This element is a Microsoft specific tag called g:background. You can find the specifications and documentation in this page.

Be carefull, as we use the g:background tag, don't use a doctype and especialy no xhtml doctype !

So, now you page should look like this:

<html>
 <head>
 </head>
 <body style="width:150px;height:200px;" >
  <g:background id="background" align="center" style="z-index:999;position:absolute;top:0;left:0;width:150px;height:200px;" src="./path/to/your/background" />
  <div id="content">
   
  </div>
 </body>
</html>

This should be enough to have it working.
You may have note that it I fixed the background and the body sizes, it is mandatory to avoid any unwanted effect I mentioned in the introduction. Please make sure that those sizes are the same as your background image.

If you added some content, you should have noticed that the result isn't the expected one. That's because we didn't position the content correctly. let's add some rules in the css stylesheet:

#content{
width:100%;
height:100%;
padding:0;
margin:0;
position:absolute;
top:0;
left:0;
}

Well, it is now exactly as we expected, isn't it ?
NO ? Damn, why does the text over the transparent area has a pink border ?
Well, I don't know, and the only way I found to add some text on the transparent area is to use the g:background addTextObject method. Otherwise, just try not to write anything in the transparent area :).

Ok, we now have a fixed size and single part background, but what can I do if I want to resize my gadget ? should I embed a background image per size ? let's go further to play around a bit.

Table of content

I assume that if you reached this paragraph you want extensible transparent background, so let's dive into the subject.
First of all, you'll need a blanc gadget with the same code as previous paragraph.
As the background image isn't the same anymore, let's replace the g:background source with a transparent image of 1px square. You may now have following index html file:

<html>
 <head>
  <script type="text/javascript">//<![CDATA[
   /**
    * @description
    * gadget initialization function
    */
   function init()
   {
    /* your initialization code */
   }
   /**
    * @description
    * changes the background size and images
    *
    * @param {Number} height the new gadget height
    * @param {String} headerUrl the new gadget header image url
    * @param {String} midleSliceUrl the new gadget middle repeat slice 1px height
    * @param {String} footerUrl the new gadget footer image url
    */
   function setBackground( height, headerUrl, midleSliceUrl, footerUrl )
   {
    /* code given in the article will come here */
   }
  //]]></script>
 </head>
 <body onload="init()">
  <g:background id="background" align="center" style="z-index:999;position:absolute;top:0;left:0;width:150px;height:200px;" src="./path/to/transparent.png" />
  <div id="content">
   
  </div>
 </body>
</html>

So, let's see how to fill in those functions.

Table of content

To achieve our goal, we'll separate the background into 3 parts, the top one, a repeating slice and the bottom. An improvement (for speed reason) could be to introduce a 4th image, that is a 10 or 20 pixel height image for the middle slice you will repeat, and for the last part use the 1px height slice. I'll let you do this improvement.

  • An image for the header, i'll call it header.png
  • A 1px height middle slice i'll call middleSlice.png. It will be repeated as many time as needed
  • A footer image, i'll call it footer.png

Table of content

So, everything is ready to code, let's go.
First of all we'll code the resizing part, as we've seen before the body and the background has to be the same size, and most important the same size as the images.

// resize part

// parses the height as integer, just in case
var _nHeight = parseInt(height, 10);
var _body = document.body || document.documentElement;
var _background = document.getElementById('background');

_body.style.height = _nHeight + 'px';
_background.style.height= _nHeight + 'px';

So, now we've got the gadget at the right size, next step is to add the images to fill the background:

// fill the background image

//load the images to get the sizes
var _headerHeight, _sliceHeight, _footerHeight,
    _headerImg = new Image(), _sliceImg = new Image(), _footerImg = new Image();

_headerImg.onerror=function(){System.Debug.outputString('header not loaded')};
_sliceImg.onerror=function(){System.Debug.outputString('slice not loaded')};
_footerImg.onerror=function(){System.Debug.outputString('footer not loaded')};

_headerImg.src= headerUrl;
_sliceImg.src= midleSliceUrl;
_footerImg.src= footerUrl;

// set the sizes
_headerHeight = _headerImg.height;
_sliceHeight = _sliceImg.height;
_footerHeight = _footerImg.height;

var _top = 0;

// add the header
_background.addImageObject(headerUrl, 0, _top);
_top+= _headerHeight;

//calculate the middle part height
var _middlepartHeight = _nHeight - _headerHeight - _footerHeight;

// and append the slice as many time as needed
for(var _i=0; _i<_middlepartHeight; _i+=_sliceHeight)
{
   _background.addImageObject(headerUrl, 0, _top);
   _top+= _sliceHeight;
}

// now add the footer
_background.addImageObject(footerUrl, 0, _top);

// That's all folk !

Here we are, we've got our resize function ! let's do the call into the init function:

 setBackground( 300, './path/to/header.png', './path/to/middleSlice.png', './path/to/footer.png')

Table of content

As usual i'll give some documentation link for fast find:

And also an hint, add a bigger slice (for instance 30px) to avoid too much iteration, and use the 1px slice to fill the difference. have fun !

Table of content

Jan 12, 2008

Adding helpers to JST

  1. Introduction
  2. Creating helpers
  3. Helpers and templating automation
    1. Declare the namespaces
    2. Parser wrapper
    3. templateObject overlay
    4. Helpers definition
  4. Conclusion

As I said in this article, I recently used JST. After playing around with it for 2 or 3 days, I came up with the conclusion that an abstraction layer is needed, except if you want to rewrite the whole code every time !

Table of content

JST documentation about the templateObject.process function says :

Note that the '''contextObject''' can contain any JavaScript object, including strings, numbers, date, objects and functions. So, calling ${groupCalender(new Date())} would call contextObject.groupCalender(new Date()). Of course, you would have to supply the groupCalender() function, which should return a string value.

So, we've got a way to define our helpers !
Let's try it :

// As usual our namespace
var App = App || {};

/**
 * a little binding utility relying on closure.
 * 
 * This function can be improved by handling the 
 * merge of given parameters on binding and given 
 * parameters on call so that :
 * <pre>
 *   var myBindedFunc = App.bind( myFunc, myContext, param1, param2 );
 *   myBindedFunc ( param3 );
 * <pre>
 * results being the same as :
 * <pre>
 *   var myBindedFunc = App.bind( myFunc, myContext );
 *   myBindedFunc ( param1, param2, param3 );
 * <pre>
 * or, using the call utility :
 * <pre>
 *   myFunc.call( myContext, param1, param2, param3 );
 * <pre>
 *
 * @param {Function} afCallback function to apply
 * @param {Object}   aoContext the context to apply the function in
 *
 * @return {Function}
 */
App.bind = function( afCallback, aoContext  ){
  /* make a copy */
  var _fCallback = afCallback;
  var _oContext = aoContext;

  /* create the closure */
  return function(){
    return _fCallback.apply(_oContext, arguments);
  };
}

//let's define our helpers
App.Helpers = {
  /**
   * used as an helper, writes 'foo'
   */
  test:function(){
     return 'foo';
  },
  /**
   * increments a value, to demonstrate 
   * the binding necessity for helpers
   * that needs to access main context
   */
  count:App.bind(function(){
    App._counter = App._counter || 0;
    return App._counter++;
  },window)
};



/* parse and process */
function parse_and_process(){
  var dest = document.getElementById('jst_add_helpers_template_test_1_dest');
  var tpl = document.getElementById('jst_add_helpers_template_test_1_template');
  dest.innerHTML = TrimPath.parseTemplate( tpl.innerHTML).process( App.Helpers );
}

Ready to test ?

Give it a try !

Here will come the processed template

So, It seems that works, but why the hell did I use a binding ?
Well, it's all about contexts, the template is executed in process function's first parameter context. That means you are enclosed in this context, so you can't access the other variables ( such as App in the count helper's case ).

So, whenever we need to create an helper that has to access other namespaces, it is necessary to bind it to needed context. Application field of such a technique can be:

  • Internationalization (to access datas that are not presents)
  • add custom events
  • register or modify variables
  • ...

Well, That's cool, we've done with helpers definition understanding, but it can be exhausting to select helpers every-time you call a template, let's see how to make it simple.

Table of content

As usual, automation means a new layer. We will need as usual a main namespace, and following sub-namespace.

App
What a surprise ! Just the same as usual :-). Well, the main namespace
App.Templates
The template engine wrapper namespace
App.Templates.Helpers
the templates helpers namespace
App.Templates.templateObject
Our templateObject overlay

Table of content

The parser wrapper needs first to keep a trace of our parsed templates, so let's have a storage facility :

/* namespace */
var App;
App.Templates = App.Templates || {};

/* utilities */
/**
 * copy all the properties from aoSource to aoDestination
 * @param {Object} aoDestination
 * @param {Object} aoSource
 * @return {Object}
 */
App.extend = function(aoDestination, aoSource){
 for (var property in aoSource) 
          aoDestination[property] = aoSource[property];
 return aoDestination;
};

/* storage utilities */
App.Templates.stored = {};
/**
 * stores a template
 * 
 * @param {String} asTemplate the template name
 * @param {OGF.Templates.templateObject} asTemplate the parsed template
 * 
 * @return {OGF.Templates.templateObject}
 */
App.Templates.store = function( asTemplateName, aoTemplate ){
 return App.Templates.stored[asTemplateName] = aoTemplate;
};
/**
 * reads a template
 * 
 * @param {String} asTemplate the template name
 * 
 * @return {OGF.Templates.templateObject}
 */
App.Templates.find = function( asTemplateName ){
 return App.Templates.stored[asTemplateName];
};

Easy isn't it ? Now the parsing layer :

/* parser */
/**
 * parses a template
 * this function is a wrapper for the template.
 * 
 * @param {String} asTemplate the template string to parse
 * 
 * @return {OGF.Templates.templateObject}
 */
App.Templates.parse = function( asTemplate ){
 return new App.Templates.templateObject( TrimPath.parseTemplate(asTemplate) );
};
/**
 * parses a template and store it.
 * This function main goal is to be binded on the request return.
 * 
 * @param {String} asTemplate the template string to parse
 * 
 * @return {OGF.Templates.templateObject}
 */
App.Templates.parseAndStore = function( asName, asTemplate ){
    App.Template.store(
   asName, 
   App.Templates.parse( asTemplate )
 );
};

Well, you maybe noticed that we used an undeclared class called App.Templates.templateObject. Let's declare it.

Table of content

This class is our abstraction layer over the TrimPath template object.
It just adds our helpers definition to the evaluation context.

/**
 * @constructor
 * @classDescription the template object wrapper for OGF
 * @param {templateObject} aoTemplate the template object
 */
App.Templates.templateObject = function(aoTemplate){
 this.initialize(aoTemplate);
}
App.Templates.templateObject.prototype = {
 /**
  * the template object reference
  * @var {templateObject}
  */
 _template:null,
 /**
  * initializes the object
  * @param {templateObject} aoTemplate the template object 
  */
 initialize:function(aoTemplate){
  this._template = aoTemplate;
 },
 process:function( aoDatas ){
  var _oDatas = {};
  if(App.Templates.Helpers)
  {
   _oDatas = App.extend( _oDatas, App.Templates.Helpers);
  }
  
  _oDatas = App.extend( _oDatas, aoDatas || {});
  return this._template.process(_oDatas);
 }
};

You maybe noticed I deported the initialization function to one in the prototype, it's a simple trick to be able to port it later on your favorite class implementation (such as Dean Edwards' base / base2, prototype class implementation or any other )

Table of content

Well, to define helpers you just need to add them to the App.Templates.Helpers namespace. Here are some of mine :

App.Templates.Helpers = {
  /**
   * include an already compiled template
   *
   * @param {Object} asTplName
   * @param {Object} context
   */
  include:(function( asTplName, aoContext){
    return App.Templates.find(asTplName).process(aoContext);
  }).bind(window),
  /**
   * write a tag opening with the given tagname and the given properties
   * example :
   * ${%open_tag('div', {id:"foo",class:"bar",style:{width:'50%',background:'#000',color:'#fff'}})%}
   * I'm currently looking for a solution to make it more readable
   */
  open_tag:function( asTagName, aoProperties ){
    var _oProperties = aoProperties || {};
    var _aProperties = [asTagName];
 
 for( var _i in _oProperties)
 {
   var _val = '';
   if(typeof(_oProperties[_i]) == 'object')
   {
     _val = [];
     for(var _j in _oProperties[_i] )
  {
     _val.push(_j+':'+_oProperties[_i][_j]);
  }
  _val = _val.join(';');
   }
   else
   {
     _val = _oProperties[_i];
   }
   
   _aProperties.push(_i+'="'+_val+'"');
 }

    return '<'+_aProperties.join(" ")+'>';
  }
}

To conclude, I'll say that I use this for the binding when I include libraries into a closure (As I do for every code in this blog) to avoid polluting the main namespace with utilities functions or prototype extensions (just as used in the JST code with the array prototype for IE5 bugfix)

Table of content

Some improvements can be done, such as utilities functions to register new helpers or a function to update the element with template result (and optionally evaluate scripts).
You can also allow some options to determines which modifiers to use, to auto-load them...

Table of content

Jan 8, 2008

Extend the elements

  1. Introduction
  2. How to extend the elements : available possibilities
    1. Prototype extension
    2. Extension when selecting
    3. Create a wrapper class
  3. Conclusion

It can sometimes be hard to make cross platform applications because of the different implementations. Attaching an event on a object can become hell if you don't use an abstraction layer. First of all, let's see the normal cross-browser approach :

function myEventFunc ( aeEvent )
{
  // just get the event if we are using IE
  var _eEvent = aeEvent || window.event ;
 
  // now do what we want to do
  /* ... */
}

/* now attach this function on the elements */
if( document.getElementById )
{
 var _eElt = document.getElementById ('myElement');
 if( _eElt.addEventListener ) // W3C (Gecko, webkit, Opera)
 {
   _eElt.addEventListener( "myEventName", myEventFunc, false );
 }
 else if( _eElt.attachEvent ) // MSIE
 {
    _eElt.attachEvent ( "myEventName", myEventFunc, false );
 }
 else
 {
   throw new Error('Your browser is very old ! please upgrade.');
 }
}
else
{
 throw new Error('Your browser is very old ! please upgrade.');
}

Well, let's see what solutions we have to avoid such a big amount of code.

Table of content

Every library used a way to get rid of such compatibility problems, and are using a single interface to do stuff.

First thing that comes to mind to add new behavior to an existing class is the prototype extension. Even if it can pose problems sometimes (such as for arrays), it can be a nice way to achieve our goal. The HTML elements class is supposed to be HTMLElement, so extending the HTMLElement.prototype should do the trick.

If quite every browser allows this extension, Internet Explorer doesn't like to make web developer's life easy, so this can do the stuff in quite every case, except for the major browser.

You can find more informations and workaround at following locations :

Table of content

As the prototype extension isn't supported natively for every browser, let's see another way. We still need to extend elements, so when will be the perfect time ? When using them of course. Which process is always used before using an HTMLElement ? selection !

To extend elements we'll need a namespace with all our functions and a selection function. Let's have a piece of code to illustrate :

/**
* the application namespace
*/
var App = {};
/**
* the element functions namespace
*/
App.HTMLElement = {
   addEvent: function(aElement, asEvent, acCallback, abBubbles){
     var _bBubbles = abBubbles || false;
     if(aElement.addEventListener ) // W3C (Gecko, webkit, Opera)
     {
       aElement.addEventListener( asEvent, acCallback, _bBubbles );
     }
     else if( aElement.attachEvent ) // MSIE
     {
        aElement.attachEvent ( 'on'+asEvent, acCallback, _bBubbles );
     }
     else
     {
       throw new Error('Your browser is very old ! please upgrade.');
     }
   }
};
/**
* our simple selector
* @param {String} asElementId the id of the element
* @return {HTMLElement}
*/
App.get = function(asElementId){
   var _eElement = document.getElementById(asElementId);
   if( ! _eElement.extended )
   {
     for(var _i in App.HTMLElement)
     {
       _eElement[_i] = (function(aMethod,eElement){
          var _method = aMethod;
          var _elt = eElement;
          return function(){
             /* transforms the arguments into an array */
             var _args = [_elt];
             for(var _j in arguments)
             {
                _args.push( arguments[ _j ] );
             }
             /* forces the context */
             return _method.apply( _elt, _args );
          }
       })(App.HTMLElement[_i], _eElement);
     }
      _eElement.extended = true;
   }
   return _eElement;
};

Well, this piece of code should work, let's try it :

Pass the mouse over me.

Here is the code I used to set this behavior up

 
/**
 * load event to initialize the div
 */
function extends_elts_test1_init(){
  App.get('extend_elts_test_1').addEvent('mouseout', extends_elts_test1_out).addEvent('mouseover',extends_elts_test1_over);
}
/**
 * function attached to the mouseout event of the element
 */
function extends_elts_test1_out(){
  App.get('extend_elts_test_1').style.backgroundColor = "#ff0";
}
/**
 * function attached to the mouseover event of the element
 */
function extends_elts_test1_over(){
  App.get('extend_elts_test_1').style.backgroundColor = "#0ff";
}

/* now register the load event */
if(window.addEventListener)
{
  window.addEventListener('load',extends_elts_test1_init,false);
}
else if(window.attachEvent)
{
  window.attachEvent('onload',extends_elts_test1_init,false);
}

To conclude on the elements extension, let's say that's prototype's way of doing. You can improve this code by mixing it with the HTMLElement.prototype extension. Just call the namespace HTMLElement, declare it as a new object and extend the prototype if it isn't natively done.

Well, this method is nice, but making a closure for every function every time an object is extended seems to be a bit a heavy way isn't it ? let's see what else can be done.

Table of content

Previous approach was based on selection, let's keep it, but this time we'll build a complete wrapper around it, a wrapper that references our element and implements our new methods.

/**
 * our namespace, as usual
 */
var App = {};
/**
 * the elements methods
 */
App.Element = function( anElement ){
  this._element = anElement ;
};
App.Element.prototype = {
  /**
   * the element instance
   * @var {HTMLElement}
   */
  _element : null,
  /**
   * cross-platform event observer
   * @param {String}   asEvent    the event name
   * @param {Function} acCallback the callback
   * @param {Boolean}  abBubbles  the bubbling flag [optionnal]
   *
   * @return {App2.Element}
   */
  addEvent: function( asEvent, acCallback, abBubbles){
     var _bBubbles = abBubbles || false;
     if(this._element.addEventListener ) // W3C (Gecko, webkit, Opera)
     {
       this._element.addEventListener( asEvent, acCallback, _bBubbles );
     }
     else if( this._element.attachEvent ) // MSIE
     {
        this._element.attachEvent ( 'on'+asEvent, acCallback, _bBubbles );
     }
     else
     {
       throw new Error('Your browser is very old ! please upgrade.');
     }
     return this;
  },
  /** 
   * set a style property. needed for the demo.
   * @param {String} asProperty the property name
   * @param {String} asValue    the new property value
   *
   * @return {App2.Element}
   */
  setStyle:function( asProperty, asValue ){
    this._element.style[asProperty] = asValue ;
    return this;
  }
};
/**
 * once again the selection function
 * @param {String} asElementId the element to select id
 * @return {App.Element}
 */
App.get = function( asElementId ){
  var _Element = document.getElementById( asElementId );
  return new App.Element( _Element );
}

Want a try ? let's go using quite the same code as earlier, except for the style property setting, I used the newly created wrapper.

Pass the mouse over me.

This way is cleaner, but needs more code to be done, because you have to implement every method, none are given by default !
This approach is the one chose by Ext framework, and seems to be the fastest at execution time ( I'm still impressed with the result they achieved with this framework ).

Table of content

Any method you choose, first improvement will be to add a method for registering new "native" methods. Whatever, except if you are embarrassed with some library functionalities (such as prototype Array extension), or if application is so specific that no library fit your needs, it is always better to rely on existing maintained code.

Table of content

Jan 7, 2008

Javascript template engine : why and which ?

  1. Introduction
  2. State of art
  3. The choice
  4. Playing around

Hi there, as I needed a template engine for one of my customer, I looked around to find the one that was the best fitting my needs. My requirements where the following :

  • Cross-browser
  • Easy to learn
  • Allow easy internationalization
  • Library independent
  • Well documented and maintained
  • Possibility to add custom helpers and modifiers
  • Process relies on a compilation (to avoid multiple compilation)

Well, let's see what's on the place.

Table of content

Several client side templates engines are available, here are some that kept my attention :

Table of content

I finally decided to use JST that seemed to be the one that best fits my needs. MModifiers are simple to declare and to use for variables modification (such as upper-case or html sanitize-ing), and macros seems to be the way to declare helpers.
For the Internationalization, as I am using JSON datas it seems to be a simple workaround that can be achieved using a little layer aver the templateObject.

An other point that kept my attention is that syntax is most likely the same as the Javascript one, and that's a good point not to have to learn a new syntax.
Last but not least, it is possible to use inline JavaScript statements.

Table of content

Here comes the interesting part, it's time for tests ;-)
I'll keep you in touch with further posts including some of my code, but for now, I'll just give the documentation link

Table of content

Nov 24, 2007

Ant scripting

Table of contents

  1. Introduction
  2. Define the project
  3. Define entry points
  4. Code snippets
    1. Use ant as a template engine
    2. Use ant to auto-compress your code
  5. Ressources

Introduction

Hy there, I just started to use Ant build, and I figured out that starting learning it wasn't as obvious as expected.
I first read the Manual homepage but it wasn't clear enought for a stupid guy as I am, so I decided to create this post with some Javascript dedicated code snippets and a (very) quick introduction to ant scripting. I hope it will be usefull to someone ^^

Table of content

Define the project :

Ant script as every XML document has to declare a root node. This root node is a project node and can take following arguments :

name :
your build project name
default :
your build default entry point
basedir :
the directory used as base for path evaluation

You can add to your script a description via the description tag, just put plain text as done here

<project name="yourProjectName" default="defaultTask" >
 <description>
   This project does....
 </description>
</project>

Table of content

Define the entry points :

An entry point in an Ant script is a stand alone task. It is represented with a target node. This node can accept following attributes :

name :
your task / entry point name
depends :
more or less the scripts to execute before.

So as an ant build is generally used to create or deploy a project, let's assume there is at least the two following tasks : CLEAN and DEPLOY. So our script now looks like :

<project name="yourProjectName" default="defaultTask" >
 <description>
   This project does....
 </description>

 <target name="CLEAN">
    <!-- include your tasks here -->
 </target>

 <target name="DEPLOY">
    <!-- include your tasks here -->
 </target>

</project>

So, here is our first ant script with two tasks. You can run it in any eclipse environnement by dragging this xml file to the ant view and double-clicking on one of the created tasks name.

Before going further, let's see 2 usefull functionnalities : how to call a task within your tasks and print a message.

To print a message use the echo tag. Two ways are possible :
Just print your message between the node like this :

<echo>
  Your message to print
</echo>
or use the message attribute :

<echo message="Your message to print" />

Now to call a task while processing an other, just use the antcall tag.
For example to call clean while processing the deploy task, just modify previous code with following :

<target name ="DEPLOY">
    <!-- include your tasks here -->
    <antcall target ="CLEAN">
 </target>

Easy isn't it ?
Well before giving some usefull(?) code snippets for Javascript developpement, here is the ant core functions references

Table of content

Code snippets:

Use ant as template engine:

Didn't you dream of a world in which you can define the version of your project in only one place ? A world where you can change your library namespace as many time as you want ?
So, Ant makes it possible whatever the platform you're working on !

First of all, you have to define all your variables in a myFile.properties file. Then, everywhere you want thoose variables to be replaced, just write it into dollar baces :

  • ${myVar}
  • ${PROJECT_VERSION}

Then in your myFile.properties file, define your values in following way :

  • myVar=MyVarReplaced
  • PROJECT_VERSION=1.0

It is recommended you externalizes the variables used for input and output :

  • destDir=absolute/path/or/relative/to/basedir
  • sourceDir=absolute/path/or/relative/to/basedir

So, here we are ready to process the datas using following code :

<target name="REPLACE_VAR" >

   <loadproperties srcfile="myFile.properties">

   <copy todir="${destDir}" overwrite="true" includeEmptyDirs="true" >
     <fileset dir="${sourceDir}" />
       <filterchain>
          <expandproperties/>
       </filterchain>
   </copy>

 </target>

To go further, just visit the filterChain manual page and especially the expandproperties section.

Table of content

Use ant to auto-compress your code:

Javascript is a a script language, so it is delivered as you publish it with comments and whitespaces. Well what if I tell you that you can compress it up to 80% ! Let's see how to do that ;)

First, you need to install some JAR files defining the functions we need ANT to use. I'm using Eclipse 3.3, so I will detail how to do with this platform. If you uses something else, just search the web !

  1. open the window > preferences pannel
  2. Choose the Ant > Ressources in the left box
  3. Select the ClassPath tab and click on global entries to enlight the line
  4. Press the Add external JARs... button
  5. select your JAR file and validate. You're now ready to use the newly intalled library !

I choosed the DOJO compressor ( relying on rhino ) you can download on the lcasoft website.
Just add rhino.jar and compress-js.jar to your ant libraries to make the compress-js function available in your ant build.
Let's see an example on how to use it :

 <!-- Import the task -->
 <taskdef name="compress-js" classname="com.webpanes.tools.ant.taskdefs.CompressJS" classpathref="cp"/>

 <target name="COMPRESS_CODE">
    <compress-js file="myFile.js" tofile="myCompressedFile.js"/>
 </target>

To go further you can read the compress-js documentation

Table of content

Ressources :

Ressources :

Jar files :

Table of content

Nov 23, 2007

Ouverture

Ca y est, j'ai enfin décidé d'ouvrir un blog. Le but est de faire partager mes expériences de programmation, publier les quelques bouts de code que je développe, et surtout concentrer en un seul lieu l'ensemble des articles que je trouve intéressants. bonne lecture à tous ! (bon ok, bonne lecture à moi ;p) Ce premier article est en francais, mais comme tout outil technique, les prochains postes seront en anglais.