Posts with the tag 'coldfusion'


Implementing Master Page concept in ColdFusion

One of the functionality I like in asp.net platform is the master page concept, it really helpful to keep the layout clean and gives really good control to developer in terms of placement of content/data on the rendered page. Having worked on aps.net side of it, I figured it’s fairly easy to implement the similar concept in ColdFusion, let me first explain what master page is.
“Master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.” Reference : http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx (can read more about master page..)

How does master page functionality work

a) Create a master page
You need a master page (i.e. the template) with global layout of your web application, there can be multiple templates if you want different look and feel for different section or can have just one global master page for the entire web app, part of the template you will have to also put in placeholder that can be updated by the developer that will be creating functionality for individual pages.

b) Create content page
Content page is the actual page that gets shown to the user; it’s the combination of template + the content relevant to that page. In this page the developer fills in the master page placeholder with page relevant content and there for have full control over what gets rendered to the end user.

Why is master page required in ColdFusion application?

Before I even answer this question, lets walk through the scenario of how page template are created in most of the ColdFusion application, normally the header and footer or other section gets broken into separate file like Header.cfm, footer.cfm etc etc, and the individual content page like index.cfm will include header.cfm on top and then add some html code for the page and finally include footer.cfm something like this.

<cfinclude template="header.cfm"/>
Some content,  static, via db or other means.
<cfinclude template="footer.cfm"/>

So what’s the big deal?

Normally this is not a problem when you start with the project, but slowly and slowly as the number of pages for the site increases you start to realize that header and footer has to change on page by page basis, and you start introducing variables and start having conditional logic in your header and footer pages, or another situation can be that for some special pages you need to add css or javascript because those pages are doing special ajax stuff, but you don’t want to add that to header, because it will get included for all pages and that will slow down the site, so basically start adding the css and javascript withing the content page and after some time your page looks like javascript and css all over the place, plus your header and footer files have ton’s of conditional logic.
Check out http://www.sys-con.com/ and perform view source, scroll through the html and see how css and javascript is pretty much all over the page, and not consolidated in header section, where it should be right?

How does master page help?

By using master page you get multiple benefits,

  • don’t have to break the layout in multiple files like the header.cfm and footer.cfm earlier
  • the layout logic is clean and does not have to be conditional
  • by providing placeholder at proper places you give the developer an opportunity to put in page related content
  • master page maintains the rendered document structure and can help you comply with w3c standards
  • Other benefits are also possible -)

How to implement Master page in coldfusion

Along with this entry I have also posted sample code, that shows standard way of using template and how that can be implemented as master page in coldfusion. The examples are self explanatory but to provide brief overview the concept is to first define master page somewhat like this (just an example).

Download Code

[The requested file http://www.cfdesignpatterns.com/wp-content/uploads/2008/12/global_masterpage.cfm could not be found]

Important thing to note is the cfif tag followed by the variable.name , basically these are the values that can be supplied by individual page developer and that gets merged when final page is rendered

The content page will look like this

[The requested file http://www.cfdesignpatterns.com/wp-content/uploads/2008/12/index.cfm could not be found]

Another example

[The requested file http://www.cfdesignpatterns.com/wp-content/uploads/2008/12/newupdates.cfm could not be found]

Here you can see the content page have to supply the value to master page placeholder , also to note is that content page does not have to supply all the values, it can omit what it does not care about (that’s why the master page had conditional if logic)

The actual magic of merging master page and template page happens in the onRequestEnd.cfm file where this file basically removes all the previous content and based on setting loads the appropriate template file! Download Code to view files

Conclusion

If the master page approach is used in your web application development, you will end up getting multiple benefits

  • Single template file (though you can multiple template file for certain section of site, all you have to do is create another template file and define a variable on your content page like this
    <cfset request.master_page_template = "the new template/master page name"/> )

  • Using master page you can get rid of empty white space on your page (specially on the very top of generate html page )
  • Master page gives the content page developer flexibility on how to fill in the template
  • Generated html page is clean
  • Don’t have to deal with multiple include files
  • Overall it’s easy to use.

[Update : Most of the Coldfusion MVC framework provides template concept - but the implementation varies]

6 comments December 19th, 2008

Strategy Design Pattern in Coldfusion

In this blog post I will demonstrate the practical use of strategy design pattern in ColdFusion and discuss other possibilities.

So what is Strategy Design Pattern?
Wikipedia : “In computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.
Gang of four : “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

So from the various descriptions it’s clear that this pattern can be used in the situation where there is possibility of having difference/multiple calculation and the application has to choose the right one on the fly.

I am going to use a scenario to build the case on why and how this pattern should be used.

Scenario:

Let’s say there is a web application which has multiple developers working on it, or have multiple teams working on independent section of the application, in such sort of application its fundamental to have core set of components that the developer use and there is also a possibility that they may be used across multiple applications. In such sort of scenario its inherent that core component be stable and least amount of changes should be done on the core components (i.e. cfc’s ) to avoid large scale impacts to other modules/developers.

So let’s say one of the core components that we have is the Customer.cfc it has some properties and also methods which get used by the appropriate section of the web applications


example1.jpg

<cfcomponent name="Customer" output="false">
  <cfscript>
    this.name = "";
    this.address = "";
    this.customerType = 0;
    this.balanceDue = 0;
  </cfscript>
</cfcomponent>
<!--- 
  ideally all the attributes should be in variables scope and have a get/set method defined, 
  but i am skipping that portion, so that i can focus on strategy pattern, and to have 
  less code :-) 
--->

There came a request for business to also start storing the latitude and longitude of customer location in the database and it was decided that we are going to use Google’s reverse lookup service, everybody agreed and the core Customer.cfc got updated to
example2.jpg

<cfcomponent name="Customer" output="false">
  <cfscript>
    this.name = "";
    this.address = "";
    this.customerType = 0;
    this.balanceDue = 0;
    this.latitude = 0;
    this.longitude = 0;
  </cfscript>
  
  <cffunction name="reverseLookup">
    <!--- 
      perform the reverse geocode with google  and return the values back as a string
      and also update the latitude and logitude attribute
    --->
    <cfreturn "">
  </cffunction>
</cfcomponent>

Here you can see two new properties were added and a method was added to perform the reverse lookup.

This worked fine, until business came back and said that they are not pleased with Google’s service and want to use yahoo, the simpler solution would be just remove the Google specific code and replace it with yahoo code, but the architect decided why not have both in place, who know the business may change their mind, so the code updated to.

example3.jpg

<cfcomponent name="Customer" output="false">
  <cfscript>
    this.name = "";
    this.address = "";
    this.customerType = 0;
    this.balanceDue = 0;
    this.latitude = 0;
    this.longitude = 0;
  </cfscript>
  
  <cffunction name="reverseLookup">
    <cfargument name="serviceID" type="numeric" required="true">
    <cfif serviceID EQ 1>
      <!--- google code--->
    <cfelseif serviceID EQ 2>
      <!--- yahoo code--->
    </cfif>
    <cfreturn "">
  </cffunction>
</cfcomponent>

As you can see the core component introduced the notion of serviceID, where the developers or consumer of this component has to supply the service ID i.e. yahooID or googleID. The change was made but it involved much pain because all the developers has to be notified about it and also the other applications that were using the component had to made updates because the interface for the core component got changed.

Now after some time, the business came up with another suggestion they had found this database that can be bought which has all the required data to perform the reverse lookup without going to any third party and wanted the development team to implement it. To accommodate this request the core component had to be again updated, with an additional IF condition
<cfcomponent name="Customer" output="false">
  <cfscript>
    this.name = "";
    this.address = "";
    this.customerType = 0;
    this.balanceDue = 0;
    this.latitude = 0;
    this.longitude = 0;
  </cfscript>
  
  <cffunction name="reverseLookup">
    <cfargument name="serviceID" type="numeric" required="true">
    <cfif serviceID EQ 1>
      <!--- google code--->
    <cfelseif serviceID EQ 2>
      <!--- yahoo code--->
    <cfelseif serviceID EQ 3>
      <!--- db code--->
    </cfif>
    <cfreturn "">
  </cffunction>
</cfcomponent>

As you can see in every situation the core component gets effected, i.e. any time a new vendor is found the core component has to be updated with additional IF logic, which means the core component has to be touched every time and developed team really does not want to do that because of downside impact that may happened if a bug got introduced during the change.

How does Strategy Pattern Solves the above problem?

Strategy Pattern is the perfect solution for the above mentioned scenario, where first of the the calculation/algorithm (i.e. the reverse geocoding) part of the code, gets split into a component of its own, so there will be a .cfc file for each of the reverse geocoding i.e. googleReversGeocoding.cfc , yahooReversGeocoding.cfc and databaseReversGeocoding.cfc and they all will inherit a single interface to perform decoding

example4.jpg
example5.jpg
IReverseLookup.cfc

<cfinterface name="IReverseLookup">
  <cffunction name="decode" returntype="string">
    <cfargument name="address" type="String" required="true">
  </cffunction>
</cfinterface>

GoogleReverseLookup.cfc

<cfcomponent name="GoogleReverseLookup" implements="IReverseLookup">
  <cffunction name="decode" returntype="String">
    <cfargument name="address" type="String" required="true">
    <!--- 
      make calls to google 
      and return the data
    --->
    <cfreturn "1929202.111, 292920.211">
  </cffunction>
</cfcomponent>

YahooReverseLookup.cfc

<cfcomponent name="YahooReverseLookup" implements="IReverseLookup">
  <cffunction name="decode" returntype="String">
    <cfargument name="address" type="String" required="true">
    <!--- 
      make calls to yahoo
      and return the data
    --->
    <cfreturn "0119182781.111, 5111192929.211">
  </cffunction>
</cfcomponent>

DatabaseReverseLookup.cfc

<cfcomponent name="DatabaseReverseLookup" implements="IReverseLookup">
  <cffunction name="decode" returntype="String">
    <cfargument name="address" type="String" required="true">
    <!--- 
      make calls to Database
      and return the data
    --->
    <cfreturn "000002221, 0028289.857">
  </cffunction>
</cfcomponent>

DatabaseReverseLookup.cfc

<cfcomponent name="Customer" output="false">
  <cfscript>
    this.name = "";
    this.address = "";
    this.customerType = 0;
    this.balanceDue = 0;
    this.latitude = 0;
    this.longitude = 0;
  </cfscript>
  
  <cffunction name="reverseLookup">
    <cfargument name="reversLookupStrategy" type="IReverseLookup" required="true">
    <cfreturn reversLookupStrategy.decode(this.address)>
  </cffunction>
</cfcomponent>

example1.cfm

<cfset customer = CreateObject("component", "Customer")>
<cfset customer.address = "410 washington Street, Greely, NC 10001">
<!--- set other properties --->

<!--- code wasts to use google service --->
<cfset strategy = CreateObject("component", "GoogleReverseLookup")>
<cfoutput>#customer.reverseLookup(strategy)#<br></cfoutput>

<!--- code wasts to use yahoo service --->
<cfset strategy = CreateObject("component", "YahooReverseLookup")>
<cfoutput>#customer.reverseLookup(strategy)#<br></cfoutput>

<!--- code wasts to use database service --->
<cfset strategy = CreateObject("component", "DatabaseReverseLookup")>
<cfoutput>#customer.reverseLookup(strategy)#<br></cfoutput>

So with the strategy pattern, now we will have cleaner implementation, where decoding with each vendor/service is done separately and Customer class (cfc) does not care about what vendor we are using as long the object that is being passed to it implements the IReverseLookup interface then that’s all it cares about. With this type of implementation you can add as my vendor and defined the logic in separate CFC (implement the interface) and you will never have to be updated the customer object. This way the code that is using this component can at runtime decide what strategy i.e. calculation to use without effecting the core component.

When can you use the strategy pattern be used?

a) If you have multiple components (CFC) that have structural similarity , but have different behavior (due diligence has to be done)
b) You have algorithm whose calculation can vary depending up the parameters passed to it.
c) Have excessive use of switch or if statement, and you have a desire to clear it up ?
d) You don’t want your core component to updated every time a new strategy is developed or requested.

Download Source Code

2 comments June 28th, 2008

Exploring Data push with Instant Messaging

Have you ever come across the idea of building an application or functionality that notifies the user of some event, I can think of various examples?

  • A Real estate side notifying the user that property matching their criteria just got listed
  • A job side notifying user that a new job matches there keywords
  • Application server error alert send to administrator
  • Notifying that stock prices went down or up

I can think of hundreds of different situation where notification functionality can be use, today’s most of the notification either happens though email or by the fact that user will come to certain section of site to get the updated information, not trying to downplay the fact that there are tools like nagios etc that can pull data from SNMP traps and send notification but that’s require you to implement SNMP protocol in your application which is not a trivial task.

With the every growing popularity of Instant messaging where millions of users are now actively using IM as means of communication both in office and personal environment bring a very promising platform for application development that can provide the notification mechanism that once thought was tough to implement.

Though instant messaging application like MSN, Yahoo Messenger, AOL Instant Messenger, Google Talk etc have implemented their own protocol and don’t cross communicate but there is light at the end of the tunnel. Google Talk uses XMPP protocol for messaging and looks like yahoo and AOL may follow the suite in future.
http://florianjensen.com/2008/01/17/aol-adopting-xmpp-aka-jabber/
http://www.process-one.net/en/blogs/article/after_aol_yahoo_is_also_experimenting_with_xmpp/

XMPP (Extensible Messaging and Presence Protocol) aka Jabber, is a light weight XML based messaging protocol for which various libraries exists and can be used for application development. If all the IM application start supporting XMPP the application development for IM platform will become super simple, but that not the case yet and I think it’s going to be a while before something like this will happen.

Currently Google Talk allows anyone to build application that can operate on XMPP protocol and adhere to their policy, similarly http://code.google.com/apis/talk/open_communications.html

Similarly AOL supports OSCAR protocol and have provided a set of library under the project “Open AIM” to communicate with their platform. http://dev.aol.com/aim

Microsoft and Yahoo are also working on provide a platform that allows developers to integrate with their platform.

As of now I can see two platform (Gtalk, AIM) easily available for integration with more coming in future, with what was available I started playing with these platform and developed a prototype/proof of concept as to how IM instant notification can be useful and demonstrate its power.

To start with what I wanted was to create an application where I could send message to users from a web page and similarly when the user respond back I should be able to receive the message in a web application, so the way I proceeded with this was to create a java application that has a build in HTTP server , where I can send messages from my web page that way the java application can get the data and then it sends it over the message to appropriate user as defined in the http payload (JSON message)

Similarly when the message arrives the Java application Posts the message to a web page where I can go ahead receive and parse the data (very simple)
For proof of concept I added the notification functionality to the Indiankey Gigs section, where it now allows the user to subscribe for IM notification, User can add the notifications that they are interested in i.e. looking for ColdFusion gigs or java gigs etc and can interactively chat with the application using their IM client and finally on the server side I have the ColdFusion code that reads the preferences of the user and sends them the listing that match their criteria on real time basis.
http://www.indiankey.com/jobs/ (link to prototype application)

The benefit I see form the proof of concept is that now the user don’t have to constantly keep coming to the job section to see the new listing they can set the keywords and if they are only they will receive the messages that meet there condition, resulting in low server resource usage and allowing the application to push the data with the IM infrastructure!

IM Use Case

3 comments March 28th, 2008

Webservices AxisFault Handling in Coldfusion 8

Day was going fine, had my morning coffee attended project related meeting by the time I got back to check the mail I saw a chain of message going back and forth between the coldfusion developers and the backed web services developer regarding the AxisFault subject.

The issue started with the changes that backend/services team implemented in development environment, where they were throwing axis fault in error situation so that the calling application can trap that information and perform appropriate action, It was a little different then how it used to be down before. The main issue for the coldfusion developer was that they were not getting the AxisFault object back, instead in the exception object the fault data was back as a string which they parse and search for the error code and description.

After having the discussion with both the group it was clear that services team wanted to keep the functionality but for frontend/coldfusion team it was additional burden for parsing string and looking for information.

axis_4.JPG

frontend developers did not wanted to perform the find/search on the faultString or other exception properties, instead they were looking for coldfusion server to return them the exact AxisFault object.

After knowing the problem I googled for the solution to see if anybody have worked with AxisFault in coldfusion and nothing turned out, so to get frontend developers going I wrote a function that would reconstruct the AxisFault object from coldfusion exception so that they are spared from string search type work.

axis_5.JPG

Here is how the result of getAxisFaultDetail looks like
axis_2.JPG

Download code

This functionality was welcomed by the developers in my company I hope somebody out there might be looking for something similar, so here is the code that transactions faultString to AxisFault object

Add comment February 7th, 2008

Using CFQuery for executing stored procedure

Something that all of us wants to avoid is server slow down and crash in the event of application load and that’s what motivates us to look at code optimization, refactoring, frameworks, database optimization etc.

There are various steps that can be taken for application optimization and to have uninterruptible application availability, but for the moment I am just going to focus on database side. This wont be the first time you are hearing about database/query optimization for having a healthy application, and assuming you have the best optimization done there are still times when unthinkable happens i.e. network connection to database is slow, database transaction log is full, query is running without using a index etc. The point being unforeseen issue can happen with database and it can bring your site to its knees, and your customers have to suffer.

Many of the large scale application uses stored procedure instead of inline SQL queries in CF code and therefore CFStoreproc tag is the ideal choice for running Stored procedure. But one of the biggest disadvantages of using CFStoredproce is the missing timeout attribute, which can lead to slow sites and complete crapping out of server. For whatever reason if the stored procedure executing time goes up then normal expectancy its going to slow down the page processing and eventually result in request queuing for high traffic site and the unavailable server crash.

If you are concerned about Stored procedure taking long time then normal, then use CFQuery tag with “timeout” attribute where you can set the timeout to be the normal expect Query executing time + some extra buffer. When the code gets executed the timeout is going to free the connection if SP takes longer then you have anticipated and you can graciously handle the error, rather then letting the page spin forever. Think about the scenario where the lots of users are hitting the same page (without the timeout), whosoever comes first will have the page still loading and basically holding the CF execution thread and other users request will be queued up in CF server which is going to slow down the server and as the queue size increases the server is going to become unstable. Whereas if the timeout was introduced its going to clear the request immediately with some error message to user, and therefore the server will continue processing request as they arrive.

CFQuery “timeout” attribute should not only be used for stored procedures, it should also be used for regular inline query, doing so will save your application from coming to a screeching hold in case of database outage.

<cfquery name=”name” timeout=”10″>
Query / Store procedure
</cfquery>

4 comments January 2nd, 2008

Prototype Pattern in ColdFusion 8

The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. This article explains how this pattern can be used in coldfusion

I set out tonight to determine if the Prototype design pattern would be useful in object factories in ColdFusion 8. The Prototype pattern, in a nutshell, is to create a new instance of an object by copying an existing object instantiation. The object to copy is an object instantiated once and then used as a blueprint for future objects of the same type. The thought is that copying an object holds a lesser cost than instantiating a new object.

Read the full Article

Add comment December 26th, 2007

DAOs and Gateways in ColdFusion

Brief introduction of DAO and Gateway pattern for coldfusion audience

Data Access Object and Gateways are the names given to ColdFusion components that access information from a database or other external data source. Within the ColdFusion community DAOs and Gateways have pretty much taken on the meaning as follows

Read the full Article

Add comment December 22nd, 2007

Object Factory in Coldfusion

Factory method pattern implementation in coldfusion along with working sample code, This pattern helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate.

For those of you new to this concept, an object factory is nothing but a component whose sole job is to create components. An object factory is quite simple and small. Its main role is to collect the information necessary to create an instance of the intended object’s class and then to invoke that class’s constructor

Read the full Article

Add comment December 16th, 2007

Command Pattern in Coldfusion

Object in command pattern are used to represent action and can be used effectively in coldfusion, this Article explains the command pattern by building a demo application.

The tutorial is simple in its presentation but gets the job done and includes a full working application putting everything to good use. You’ll be creating a home automation Remote Control for the appliances in your house. My remote has simple on/off buttons and and undo button but the tutorial will teach you to do more

Read the full Article

Add comment December 10th, 2007

Implement the State pattern with ColdFusion Components

State Pattern implementation in coldfusion to maintain the various state of an object. The article provides step by step implementation along with downloadable code for future reference.

The introduction of ColdFusion Components (CFCs) in ColdFusion MX opened the door to more object-oriented programming in CF. When application developers start thinking about OOP, the idea of design patterns almost always comes up. In that context, Brian Kotek discusses the State pattern: its purpose, the problems it can solve, and how you can implement it using CFCs.

http://articles.techrepublic.com.com/5100-3513_11-6167539.html

Add comment December 4th, 2007

Older Posts


 Subscribe in a RSS reader


CourseLookup.us - Providing course and conference information to enhance your knowledge base.

Tags

Calendar

February 2012
M T W T F S S
« Dec    
 12345
6789101112
13141516171819
20212223242526
272829  

Posts by Month

Posts by Category