Life After ASP
Ben Forta
Microsoft ASP is one of the most popular scripting languages out there, or rather, it was one of the most popular scripting languages out there. With the introduction of the Microsoft .NET platform, Microsoft is no longer developing ASP; it's investing in ASP.NET instead. ASP.NET is an entirely new language with powerful new capabilities, but it is not ASP.
To be fair, it is important to note that existing applications won't just stop working, and existing ASP applications will likely run for quite a while. It is possible to run both traditional ASP and new ASP.NET applications at once. Installing .NET (and ASP.NET) does not preclude the use of the existing ASP engine. But to leverage the new features and technologies in ASP.NET as it continues to evolve and innovate, developers will need to learn ASP.NET. And learning ASP.NET is not just a matter of learning new language syntax, ASP.NET introduces an entirely new development model and a whole new way to think about building applications. Microsoft is very honest about this, and states the following in an MSDN article on migrating ASP to ASP.NET:
If you have ASP development skills, the new ASP.NET programming model will seem very familiar to you. However, the ASP object model has undergone significant changes to make it more structured and object-oriented, so most existing ASP pages will have to be modified to some extent in order to run under ASP.NET. Major changes to Visual Basic .NET as well mean that existing ASP pages written with Visual Basic Scripting Edition typically will not port directly to ASP.NET.
The truth is, ASP and ASP.NET have little in common besides their names and syntactical similarities to Visual Basic.
Migrating Sooner or Later
With migration, ASP developers must consider the time and effort it will take to learn ASP.NET and then systematically convert their applications to ASP.NET. To their credit, Microsoft has tried to make the process as painless as possible. But even so, migration is not as simple as renaming all files from an ASP extension to an ASPX extension. For example:
- Simple and frequently used objects, like Request have changed in
subtle ways. For example, every reference to
Request.QueryString("var")orRequest.Form("name")must change. - You must change all functions declared in ASP pages. You cannot
simply declare them between
<%and%>; they must now be within the<SCRIPT> </SCRIPT>blocks with theLANGUAGEandRUNAT="server"defined. - Page rendering functions are not supported in ASP.NET. Instead,
all output must be generated using
Response.write(). While this helps enforce separating presentation from content, it is proving to be a major migration hassle for developers who were used to dropping functions into pages as needed. - The Variant data type no longer exists, you must use Object instead and it must be explicitly cast to other data types as needed.
- Parentheses are now required for all method calls, even those that have no arguments (while this brings VB.NET code in line with most other languages, it breaks lots of ASP code from running as is).
- The syntax,
a&b&cis no longer allowed; you must include spaces before and after every & (for examplea & b & c).
The required changes are well documented. As already stated, Microsoft has attempted to make the migration as painless as possible. But trivial it is not, a quick file rename followed by a global search and replace will not cut it.
Which means that at some point, ASP developers may have to migrate from legacy ASP to something else. And if developers are about to embark on a migration journey, they should probably take a step back and ask themselves some important questions:
- ASP.NET has a significant learning curve, far greater than that of ASP itself. What is that expense, can I afford it, and is it worth it?
- What role did ASP play in my development team and process, and will ASP.NET require that to change? And if so, what is the cost of that change?
- If I am going to have to migrate, what are all of my options besides ASP.NET?
- With .NET promoting structured, multi-tiered development, shouldn't I evaluate solutions used in each tier to ensure that I am as effective and as productive as I can be?
- Microsoft officially supports ASP.NET on the Windows platform only (although some developers have ported it to UNIX). Is being dependent on a single platform from a single vendor a wise investment? What alternatives are there?
- What is the real value of .NET? Is it ASP.NET or something bigger?
Or put differently, now that Microsoft has forced developers to deal with migration, doesn't it make sense for those developers to consider all available options so they can make an educated and informed decision?
"But We Are Committed to .NET"
To organizations committed to (or evaluating) .NET, asking the questions in the previous section may seem somewhat heretic. The truth, however, is that this is perfectly in-line with Microsoft thinking. As per the Microsoft .NET homepage:
Microsoft® .NET is a set of Microsoft software technologies for connecting information, people, systems, and devices. It enables a high level of software integration through the use of Web services—small, discrete, building-block applications that connect to each other as well as to other, larger applications over the Internet. … Building solutions with .NET technologies, you can create and connect to an infinite variety of personalized .NET experiences, with industry-standard technologies helping to protect your security and safety. Individuals can enjoy rich, tailored interactions—.NET experiences—when Web services are pulled together, allowing access to information across the Internet and from stand-alone applications, online or offline.
Microsoft, in its own words, says that value of .NET is not ASP.NET or C# or any particular language. Rather, the value proposition of .NET is the mechanism that allows you to build powerful and highly interoperable applications. .NET is far bigger than ASP.NET, just as J2EE is far bigger than JSP; ASP.NET is one way to leverage .NET, but it is not the only way.
So what exactly is .NET? It is a highly ambitious and incredibly powerful platform on which to build applications. At its core lies a foundation built on web services. Again, to quote Microsoft:
.NET is the Microsoft solution for Web services, the next generation of software that connects our world of information, devices, and people in a unified, personalized way. .…. .NET is a comprehensive family of products, built on industry and Internet standards, that provide for each aspect of developing (tools), managing (servers), using (building block services and smart clients) and experiencing (rich user experiences) Web services.
Web services play a vital role in the .NET world. Web services are not a Microsoft creation. Web services technology is built on open standards, like XML and SOAP, and every major player in the industry supports web services, including Macromedia. Web services are the plumbing used to facilitate distributed computing, regardless of the platform, server, or application back-end.
In other words, a commitment to .NET means a commitment to building applications that are open and extensible through SOAP and web services. A commitment to .NET in no way requires that you use any specific development language, not even ASP.NET. In fact, it is perfectly acceptable to mix and match technologies, to create hybrid applications using a mixture of best-of-breed and complimentary components. For example, the following are all valid forms of .NET use:
- .NET servers providing all back-end functionality and all client code written in ASP.NET and VB.NET.
- All back-end code running on a J2EE server, all data and processes exposed as web services written in Java, and client code written in ASP.NET and VB.NET.
- .NET servers (including SQL Server) running on Windows, and client code created using JSP connecting to that database through JDBC.
- .NET servers providing all back-end functionality, all data and processes exposed as web services written in C#, and client code written in Perl or PHP.
There is a pattern here. As articulated so clearly by Microsoft, .NET is all about web services, which means that mixing .NET with any other SOAP-enabled technology is all part of the commitment to .NET. .NET does not require unilateral commitment to Microsoft; .NET only requires a real commitment to the openness of web services and service-oriented development.
Introducing ColdFusion
If you're already using ColdFusion, move on to the Architectural Comparison section below, otherwise, read more about ColdFusion. ColdFusion is the leading commercial cross-platform application scripting technology. ColdFusion is made up of a language called CFML or ColdFusion Markup Language, and a series of runtime services that provide all sorts of features and functionality for developers to take advantage of.
ColdFusion was created in 1994, which makes it the original product in this space, and the very first language created from the ground up for application development on the Internet. ColdFusion predates JSP, PHP, and even ASP. (Actually, it is a little known fact that before acquiring Aspect Software and turning their prerelease Visual Basic scripting language into ASP, Microsoft approached Allaire about buying ColdFusion).
Over six major revisions and close to a decade, ColdFusion has empowered hundreds of thousands of developers to rapidly build powerful Internet and web applications. These developers discovered the key benefits of ColdFusion:
- The shortest learning curve of any language in this space.
- Rapid development (you need less code and less time need to write it).
- Support for all design patterns, n-tier development, and any other development methodologies.
- High performance and scalability.
- Platform supported by servers from Microsoft, IBM, BEA, Sun, and more.
- True portability across Windows, Unix, Linux, Solaris, AIX, and other operating systems too.
- Full support for all major databases (including Microsoft SQL Server).
- Includes runtime services for charting and graphing, full text searching, high performance multi-threaded mail delivery, and more.
- Built-in support for XML and web services.
- Access to COM, CORBA, Java, C/C++, and any operating system specific applications or scripting capabilities.
- Complete client independence, but also provides specific support for integration with client-side Macromedia Flash.
For all these reasons and more, ColdFusion has become the development language of choice for their Internet and web applications. With built-in support for .NET servers and web services, ColdFusion could be the right choice for you too.
Architectural Comparison
To better understand ColdFusion it may help to discuss its architecture, and to compare it to that of ASP and ASP.NET.
ASP is implemented as an ISAPI extension (or application). ASP is a DLL (named asp.dll and usually found in one of the Windows system directories), and IIS maps ASP files to the asp.dll. In this way, the ASP engine processes all requests for ASP pages. Without this mapping and DLL, the server would return ASP code to the browser, rather than the generated results. ASP pages themselves are scripts, combining server-side instructions (usually VBScript) and client-side instructions (usually HTML and JavaScript). ASP pages are very loosely coupled, pages are essentially connected to each other through URL links or form submissions. ASP pages are stored in a directory on the server, typically under the web root, and are requested like any other URL; but unlike other URLs, ASP pages are first processed by the asp.dll before the results are sent to the client.
There is no special relationship between the IIS (the de facto Microsoft Windows web server) and ASP. ASP is connected to IIS through ISAPI, just as many other server extensions are, including ColdFusion. ColdFusion differs from ASP in that it is not a DLL loaded by IIS, rather, it is a high performance multi-threaded Windows service unto itself. ColdFusion is a much bigger application than ASP simply because it does so much more than ASP does, and so it is implemented as a Windows service. The service is always running and you may start or stop it from the Windows Services Control Panel like any other service to provide optimum performance. Like ASP pages, ColdFusion pages are loosely coupled scripts combining server-side instructions (in CFML) and client-side instructions (again, usually HTML and JavaScript). ColdFusion pages have a CFM extension. IIS uses that extension to route ColdFusion requests to ColdFusion through an ISAPI connector.
In other words, both ColdFusion and ASP relate to IIS in exactly the same way. The development model for both is identical (creating script files combining server-side logic and client-side presentation code). What differs is the file extension and the server-side scripting language used.
Figure 1. ColdFusion and ASP relate to IIS in exactly the same way.
From a coder's perspective, ASP and ColdFusion are not that different. But under the hood they are anything but alike. In fact, architecturally, ColdFusion has a lot more in common with ASP.NET than it does with ASP.
ASP.NET is designed to be used with the Microsoft .NET framework. Unlike ASP code, which an interpreter processes, ASP.NET code is just-in-time compiled into MSIL (Microsoft Intermediate Language) before being executed. The compiled ASP.NET code, usually C# or VB.NET code, is executed within a special environment called the CLR (Common Language Runtime). ASP.NET code uses objects, resources, and APIs exposed by the .NET framework all from within the CLR. The CLR manages execution, memory, threads, and more. ASP.NET is still bound to IIS through ISAPI, but instead of all processing occurring within that single DLL, requests are routed for execution within the CLR. Of course, for the most part, all of this is hidden from ASP.NET developers who write ASPX files and place them on the server to execute.
ColdFusion MX is architecturally similar. Instead of running on the Microsoft proprietary Windows-only .NET platform, it runs on the multi-vendor J2EE platform. ColdFusion is a compiler and CFML code is just-in-time compiled into Java bytecode before execution. The compiled code is executed within a special environment called the JVM, or Java Virtual Machine. ColdFusion code uses objects, resources, and APIs exposed by Java and J2EE all from within the JVM, and it is the JVM which manages execution, memory, threads, and more. Of course, for the most part, all of this is hidden from ColdFusion developers who write CFM files and place them on the server to execute. Read more about the compiler in Performance Under the Covers in ColdFusion MX 6.1 .
Figure 2. ASP.NET and ColdFusion process requests in a similar way.
As you can see, architecturally ASP.NET and ColdFusion MX are not that different. The primary difference (aside from the scripting language used) is that ColdFusion leverages J2EE and ASP.NET leverages .NET. However, ColdFusion Java guts are transparent to ColdFusion developers, they can (and do) leverage Java when they want to and can ignore it the rest of the time. In fact, ColdFusion developers are shielded from the application server internals far more than ASP.NET developers are, allowing them to concentrate on being productive within their own code. After all, whereas ColdFusion provides simple tag abstractions, ASP.NET requires that developers tinker with objects, and APIs at a much lower level (a lower level even than that of ASP).
What all this means is that ASP developers can feel quickly at home in ColdFusion, probably more so than they do in ASP.NET. ColdFusion allows developers to leverage an architecture similar to that of ASP.NET, a coding model similar to what they are used to from ASP, access to the vast world of Java and J2EE, while still retaining access to .NET services and web services. And coding in ColdFusion is far quicker, cleaner, and simpler than it is in ASP.NET (as will be demonstrated shortly).
Comparing Languages
ASP capabilities are a significant subset of those of ColdFusion. This is fortunate in that it makes the migration from ASP to ColdFusion much simpler. In ColdFusion, developers can do anything they already do in ASP, usually without needing the third-party add-ons that ASP requires.
CFML is a tag-based language that resembles HTML and XML more than it does traditional programming languages. However, CFML does not skimp on functionality and provides an extensive array of tags and functions for developers to use. To help ASP developers better understand ColdFusion and the CFML language, this next section provides comparisons of common tasks written in both ASP (VBScript) and CFML.
Note: Wherever possible, ASP and ASP.NET code examples are based on code found in Microsoft documentation and online examples and tutorials on http://www.microsoft.com/, http://msdn.microsoft.com/, and http://www.gotdotnet.com/.
Basic Output
ColdFusion uses tags to denote server side scripts, this is similar
to the ASP <% and %> constructs.
ASP
It is currently: <% =now %>
CFML
<CFOUTPUT> It is currently: #Now()# </CFOUTPUT>
Although tag-based, CFML also features a scripting interface that you may use
to perform data manipulation, programmatic flow control, and more. Some
of the examples below utilize CFSCRIPT syntax.
For more granular control, perhaps to display a date in the format mm/dd/yyyy,
a developer may use the following code:
ASP
It is currently: <% =Month(now) %>/<% =Day(now) %><% =Year(now) %>
CFML
<CFOUTPUT> It is currently: #Month(Now())#/ #Day(Now())#/ #Year(Now())# </CFOUTPUT>
or
<CFOUTPUT> #DateFormat(Now())# </CFOUTPUT>
Comments
Both ASP and CFML support embedding server-side comments within code pages.
ASP
<% 'This is a comment %>
CFML
<!--- This is a comment --->
Conditional Processing
ColdFusion implements if statement processing using the CFIF tag.
ASP
<% If myVar=1 Then %> Value is 1 <% Else %> Value is not 1 <% End If %>
CFML
<CFIF myVar IS 1> Value is 1 <CFELSE> Value is not 1 </CFIF>
One very important difference between CFML and ASP if processing is that CFML supports short-circuit processing and ASP does not. In CFML it is possible to write if statements just as you would write them in ASP, but by leveraging CFML short-circuiting, you can improve application performance.
ColdFusion implements case processing using the CFSWITCH and CFCASE tags, or through a switch statement in a CFSCRIPT block, shown below:
ASP
<% Dim num Num = 4 Dim msg msg = "" Select Case num Case 1 To 5 Msg = "Between 1 and 5" Case 6, 7, 8 Msg = "Between 6 and 8" Case 9 To 10 Msg = "Greater than 8" Case Else Msg = "Not between 1 and 10" End Select %>
CFML
<CFSCRIPT>
num=4;
switch (num)
{
case 1, 2, 3, 4, 5: {
Msg="Between 1 and 5";
Break; }
case 6, 7, 8: {
Msg="Between 6 and 8";
Break; }
case 9, 10: {
Msg="Greater than 8";
Break; }
default: {
Msg="Not between 1 and 10";
Break; }
}
</CFSCRIPT>Looping
CFML supports several forms of looping, all of which are implemented using
the CFLOOP tag.
ASP
<% Dim sum sum = 0 For counter = 1 to 100 step 5 sum = sum + counter next %>
CFML
<CFSET sum = 0> <CFLOOP INDEX="counter" FROM="1" TO="100" STEP="5"> <CFSET sum = sum + counter> </CFLOOP>
The CFLOOP tag also supports conditional looping through
a CONDITION attribute, which lets you loop through flexible
conditions.
ASP
<% Dim counter counter = 0 do while count <= 10 count = counter + 1 loop %>
CFML
<CFSET counter = 0> <CFLOOP CONDITION="counter LTE 10"> <CFSET counter = counter + 1> </CFLOOP>
The CFLOOP tag also supports looping over lists and queries,
something not supported by ASP. The following example displays the contents
of a list, one item per line.
ASP
NOT SUPPORTED
CFML
<CFSET list = "apple,pear,orange"> <CFLOOP INDEX="i" LIST="#list#"> <CFOUTPUT>#i#</CFOUTPUT><BR> </CFLOOP>
Looping through database queries is just as easy, you can refer to the loop query columns simply by column name.
ASP
NOT SUPPORTED
CFML
<CFLOOP QUERY="myQuery"> <CFOUTPUT>#column#</CFOUTPUT><BR> </CFLOOP>
Accessing Form Fields and URL Parameters
ColdFusion exposes form fields through a scope named FORM
and URL parameters through a scope named URL.
ASP
Name: <% Request.Form("name") %>
Age: <% Request.Url("age") %> CFML
Name: #FORM.name# Age: #URL.age#
Setting and Retrieving Session Variables
ColdFusion exposes session data through a scope named SESSION
. Session data may be written to and read from as needed by simply referring
to SESSION.variable.
ASP
<%
Session("today")=now
=Session("today")
%> CFML
<CFSET SESSION.today=Now()> <CFOUTPUT>#SESSION.today#</CFOUTPUT>
ColdFusion exposes application scope data the same way, and locking is similarly supported.
ASP
<%
Application.Lock
Application("hits") = Application("hits") + 1
Application.Unlock
%> CFML
<CFLOCK SCOPE="application"> <CFSET APPLICATION.hits = APPLICATION.hits + 1> </CFLOCK>
Setting and Retrieving Cookies
ColdFusion exposes cookies through a scope named COOKIE
, and provides a special tag named CFCOOKIE to set, update,
and expire cookies.
ASP
<%
response.Cookies("visit")=now
lastvisit= response.Cookies("visit")
%>CFML
<CFCOOKIE NAME="visit" VALUE="#Now()#"> <CFSET lastvisit=COOKIE.visit >
Querying a Database
Querying a database is one of the most frequently performed operations in web applications. ColdFusion pioneered simple tag abstractions for database operations way back in ColdFusion 1, and remarkably the CFML tags still provide the cleanest database abstractions by far (far simpler than both ASP shown here and ASP.NET shown further below). The following code simply retrieves all rows from a table.
ASP
<%
Dim conn
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connectionString
const sql = "SELECT * FROM table"
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open sql, conn
%> CFML
<CFQUERY DATASOURCE="Dsn" NAME="myQuery"> SELECT * FROM table </CFQUERY>
The CFQUERY tag supports all ODBC and JDBC data sources, provides
built-in support for query caching, and also facilitates in memory query
manipulation. You can also query existing queries and even combine disparate
queries with the cfquery tag.
Calling a Stored Procedure
You can invoke stored procedures as simple database queries using the
CFQUERY tag, or through the CFSTOREDPROC tags.
The latter provides greater control and provides access to input and
output parameters, as well as multiple result sets.
ASP
<%
Dim sales_cutoff
sales_cutoff = 1000
set conn = server.createobject("adodb.connection")
conn.open myDSN
Dim rs
set rs = server.createobject("adodb.recordset")
rs.Open "Exec GetTopSellers " & sales_cutoff , conn
%>CFML
<CFSET sales_cutoff = 1000> <CFSTOREDPROC DATASOURCE="dsn" PROCEDURE="GetTopSellers"> <CFPROCPARAM TYPE="in" VALUE="#sales_cutoff#" CFSQLTYPE="CF_SQL_INTEGER"> </CFSTOREDPROC>
Outputting Query Data
You can use the CFOUTPUT tag to loop over the rows in a query.
ASP
<%
While Not rs.EOF
Response.Write rs("column") & <BR>
rs.MoveNext
Wend
rs.Close
%>CFML
<CFOUTPUT QUERY="myQuery"> #column#<BR> </CFOUTPUT>
The CFOUTPUT tag also supports partial displays so as to
provide for paging type interfaces.
File Access
ColdFusion provides a complete range of file and directory tags and functions. The following example contains the code needed to read and display a text file.
ASP
<%
Set fs = CreateObject("Scripting.FileSystemObject")
Set fl=fs.OpenTextFile("c:\myfile.txt")
filedata=fl.ReadAll
fl.close
response.write(filedata)
%>CFML
<CFFILE ACTION="read" FILE="c:\myfile.txt" VARIABLE="filedata"> <CFOUTPUT>#filedata#</CFOUTPUT>
The CFFILE tag also provides support for accepting uploaded
files, something not supported in ASP (unless you use a third-party
extension).
ASP
NOT SUPPORTED
CFML
<CFFILE ACTION="upload" FILEFIELD="formfield" DESTINATION="c:\">
Additional tag actions and functions allow for checking whether a file or directory exists, creating temporary files, reading file directories, and more.
Invoking COM Objects
Although ColdFusion MX is built on top of underlying Java, it still provides access to COM and COM objects in much the same way ASP does. This example uses COM to create a new Microsoft Word document.
ASP
<%
Set objWord = CreateObject("Word.Application")
objDoc=objWord.Documents
newDoc=objDoc.Add
%>CFML
<CFSCRIPT>
objWord=CreateObject("COM", "Word.Application");
objDoc = objWord.Documents;
newDoc = objDoc.Add();
</CFSCRIPT>The key here is that CFML can do everything that ASP does, and a whole lot more. And the CFML syntax is almost always cleaner, simpler, and less lines of code too. As such, ASP developers will find learning ColdFusion to be remarkably quick and painless.
Beyond ASP
The examples thus far attempted to compare common coding tasks in both CFML and ASP. But ColdFusion can do a whole lot more. In fact, many tasks that would require you to use of third-party components in ASP are built-in core features in CFML. This next section briefly explores some of these features, demonstrating the scope of the ColdFusion integrated runtime services.
Charting and Graphing
ColdFusion features a robust charting and graphing engine that can
generate business charts in numerous formats. The charting engine is
exposed through the CFCHART family of tags, which support
close to 100 attributes for incredible chart control. Read about the
full scope of the cfchart tag in Charting
and Graphing in ColdFusion MX.
CFML
<!--- Obtain department and average salary--->
<CFQUERY DATASOURCE="dsn" NAME="DeptSalaries">
SELECT Dept_Name, AVG(Salary) AS AvgByDept
FROM Employees
GROUP BY Dept_Name
</CFQUERY>
<!--- Bar chart --->
<CFCHART XAXISTITLE="Department" YAXISTITLE ="Salary Average">
<CFCHARTSERIES TYPE="bar"
QUERY="DeptSalaries"
VALUECOLUMN="AvgByDept"
ITEMCOLUMN="Dept_Name">
</CFCHART>Full Text Searching
ColdFusion includes a version of Verity search technology, which is both a client-only implementation and a high-performance client-server implementation). Interaction with Verity is encapsulated within a series of tags, as shown here.
CFML
<!--- Reindex all Microsoft Word documents --->
<CFINDEX ACTION="update"
COLLECTION="documents"
TYPE="file"
KEY="c:\my documents\"
EXTENSIONS="*.doc"
RECURSE="yes">
<!--- Obtain all documents containing ASP and CFML --->
<CFSEARCH NAME="results"
COLLECTION="documents"
CRITERIA= "asp AND cfml" >Page Output Caching
Dynamically-generated pages written in ColdFusion, ASP, ASP.NET, or any other language necessarily execute slower than static content; they do more, and doing more takes time, it's that simple. To improve the execution speed of dynamically-generated content, ColdFusion features several forms of caching you can use to speed up performance.
To cache an entire page so that you generate content dynamically and then served
it without regenerating for a specified interval, you use the CFCACHE
tag on a page.
CFML
<!--- Cache for 1 hour ---> <CFCACHE TIMESPAN="#CreateTimeSpan(0,1,0,0)#"> <!--- Page then starts here --->
The CFCACHE tag supports both server and client-side caching,
making it safe to use with personalized content.
For more granular caching, ColdFusion you can cache specific blocks
of code by simply enclosing them within a CFSAVECONTENT
tag, which also supports caching database queries, as seen here.
CFML
<CFQUERY DATASOURCE="dsn"
NAME="users"
CACHEDWITHIN="#CreateTimeSpan(0,0,30,0)#">
SELECT firstName, email FROM users
</CFQUERY>You may use database query caching relative or absolute intervals and they are completely safe to use with dynamic data-driven queries. You use once-cached queries like any other queries; the fact that your app has read the query from a cache instead of reread from the database is completely transparent.
ColdFusion vs. ASP.NET
Thus far it has been demonstrated that ColdFusion can do everything ASP can do and a lot more, is architecturally not that different from ASP.NET, and that ASP development (the page based model, how code is broken up, how scripts are used) is quite similar to that of ColdFusion. This all means that ASP developers will be comfortable and productive using ColdFusion in a very short time. But what about ASP.NET? Why should an ASP developer choose ColdFusion over the ASP.NET, the perceived migration path to ASP.NET?
You use both ASP.NET and CFML at an application's presentation layer, where productivity is a primary goal. As already stated, the incredible productivity using ColdFusion comes from the CFML language and all the integrated runtime services. This next section provides side-by-side comparisons of common programming tasks in both CFML and ASP.NET (VB.NET).
Parameterized Queries
Both ColdFusion and ASP.NET recommends using parameterized queries instead of embedding SQL. This is both faster and more secure. The following compares the use of parameterized queries.
ASP.NET
Dim sales_cutoff As Integer = 1000
Dim myConnection As SqlConnection = New SqlConnection("connection_string")
Dim myCommand As SqlCommand = myConnection.CreateCommand()
myCommand.CommandText = "SELECT title_id, title, ytd_sales FROM
titles WHERE ytd_sales >= @sales ORDER BY ytd_sales DESC"
myCommand.Parameters.Add("@sales", SqlDbType.Int).Value
= sales_cutoff
Dim SqlDataAdapter myAdapter = New SqlDataAdapter(myCommand)
Dim topSellers As DataSet = New DataSet()
myAdapter.Fill(topSellers, "titles")CFML
<CFSET sales_cutoff = 1000>
<CFQUERY NAME="topSellers"
DATASOURCE="dsn">
SELECT title_id, title, ytd_sales
FROM titles
WHERE ytd_sales >=
<CFQUERYPARAM VALUE="#sales_cutoff#" CFSQLType="CF_SQL_INTEGER">
ORDER BY ytd_sales DESC
</CFQUERY>Generating E-Mail
Developers often need to programmatically generate e-mail messages. ASP provided
no built in SMTP support and required that you use COM objects, but
ASP.NET corrects this deficiency. ColdFusion comes with a powerful mail
delivery engine, and CFML provides sophisticated SMTP support through
the CFMAIL tag. The following snippets compare generating
a simple e-mail message.
ASP.NET
Dim myMail As MailMessage = New MailMessage() myMail.From = "foo@bar.com" myMail.To = "bar@foo.com" myMail.Subect = "Test Message" myMail.Body = "This is a test message." SmtpMail.Send(myMail)
CFML
<CFMAIL TO="foo@bar.com"
FROM="bar@foo.com"
SUBJECT="Test Message">
This is a test message
</CFMAIL>The CFMAIL tag supports multiple MIME types in a single message,
secure SMTP login, and more.
But the real power of the CFMAIL tag comes from performing complex
operations, like sending personalized e-mail to a mailing list which
involves retrieving a list of names and e-mail addresses from a database,
and then generating an SMTP message for each user. The following code
examples compare this process. As you can see, the ASP.NET code is more
than just convoluted; it requires complex low-level plumbing code to
perform what ColdFusion does with just two tags.
ASP.NET
Dim connString as String
connString = "..."
Dim objConnection as OleDbConnection
objConnection = New OleDbConnection(connString)
objConnection.Open()
Dim strSQL as String = "SELECT firstName, email FROM users"
Dim objCommand as OleDbCommand
objCommand = New OleDbCommand(strSQL, objConnection)
Dim objDataReader as OleDbDataReader
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
Dim myMail As MailMessage = New MailMessage()
myMail.From = "foo@bar.com"
myMail.To = objDataReader("eMail")
myMail.Subect = "Test Message"
myMail.Body = "Dear" & objDataReader("firstName") & " ..."
SmtpMail.Send(myMail)
objDataReader.Close()CFML
<CFQUERY DATASOURCE="dsn"
NAME="users">
SELECT firstName, email FROM users
</CFQUERY>
<CFMAIL QUEREY="users"
TO="#email#"
FROM="bar@foo.com"
SUBJECT="Test Message">
Dear #firstname#, ...
</CFMAIL>ColdFusion Enterprise features a high performance multi-threaded mail delivery engine capable of delivering over 1,000,000 messages an hour and redundant SMTP servers; mass mailing is not just easy, it is also highly scalable. Read more about mail improvements in Making the Most of E-Mail with the cfmail Tag Enhancements in ColdFusion MX 6.1 .
Server-Side HTTP
Server-side HTTP support is a core feature of CFML exposed by the CFHTTP
tag.
ASP.NET
Dim myWebClient As System.Net.WebClient
myWebClient = New System.Net.WebClient()
Dim buffer As Byte()
buffer = myWebClient.DownloadData("http://www.macromedia.com/")
Dim content As String
content = System.Text.Encoding.UTF8.GetString(buffer)
Response.Write(Server.HtmlEncode(content))CFML
<CFHTTP URL="http://www.macromedia.com/" METHOD="GET"> <CFOUTPUT>#CFHTTP.FileContent#</CFOUTPUT>
XML Parsing
ColdFusion MX features a powerful integrated XML engine. Parsing an XML document is as simple as using the XMLParse() function. This comparison parses a simple block of XML and displays the value of the first child node.
ASP.NET
<% Dim xml as String xml = "<book ISBN='1-861001-57-5'> <title>Pride And Prejudice</title> <price>19.95</price> </book>" Dim doc As New XmlDocument() doc.LoadXml(xml) Dim root As XmlNode = doc.FirstChild =root.FirstChild.OuterXml %>
CFML
<CFSET xml="<book ISBN='1-861001-57-5'> <title>Pride And Prejudice</title> <price>19.95</price> </book>"> <CFSET doc=XMLParse(xml)> <CFOUTPUT> #doc.book.XmlChildren[1].XmlText# </CFOUTPUT>
The XMLParse() function returns a structure containing
the entire XML document that you may access directly (as just seen)
or manipulate using standard CFML functions. You may apply XSL transformations
using the XMLTransform() function, and you can execute
XPath searches using the XMLSearch() function.
Creating Web Services
ColdFusion components (CFCs) are objects that you create and expose using CFML tags. CFCs form the basis of structured tiered applications and are designed to facilitate code reuse and separate presentation from content.
You can also expose CFCs as web services by simply setting the attribute
ACCESS="remote". WSDL generation is automatic
and all SOAP manipulation is transparent.
The following is complete code for two web services, one to convert Celsius to Fahrenheit and the other Fahrenheit to Celsius.
ASP.NET
<WebMethod()> _ Public Function Celsius2Fahrenheit( _ ByVal Temp As Double) As Double Return Temp * 9 / 5 + 32 End Function <WebMethod()> _ Public Function Fahrenheit2Celsius( _ ByVal Temp As Double) As Double Return (Temp - 32) * 5 / 9 End Function
CFML
<CFCOMPONENT>
<CFFUNCTION NAME="Celsius2Fahrenheit"
RETURNTYPE="numeric"
ACCESS="remote">
<CFARGUMENT NAME="temp"
REQUIRED="yes"
DATATYPE="numeric">
<CFRETURN temp * 9 / 5 + 32>
</CFFUNCTION>
<CFFUNCTION NAME="Fahrenheit2Celsius"
RETURNTYPE="numeric"
ACCESS="remote">
<CFARGUMENT NAME="temp"
REQUIRED="yes"
DATATYPE="numeric">
<CFRETURN (temp – 32) * 5 / 9>
</CFFUNCTION>
</CFCOMPONENT>Invoking Web Services
Creating a CFML web service is quite similar to that of ASP.NET. But compare the way you invoke the web service below.
ASP.NET
Simple web service invocation is not really supported. ASP.Net requires that you first generate a proxy and then write code to connect to the web service through the proxy.
CFML
<!--- Start with 38 degrees Celsius --->
<CFSET tempc=38>
<!--- Invoke web service --->
<CFINVOKEWEBSERVICE="http://host/tempconf.cfc?wsdl"
METHOD="Celsius2Fahrenheit"
TEMP="#tempc#"
RETURNVARIABLE="tempf>
<!--- Display temp in Fahrenheit --->
<CFOUTPUT>
#tempc# Celsius = #tempf# Fahrenheit
</CFOUTPUT>It is somewhat ironic you can invoke web services so much easier with ColdFusion than with ASP.NET, a language built for .NET and web services. You can use the CFML code above to invoke any web services, including both the CFML and VB.NET examples seen previously.
Development Methodologies
As already explained, ColdFusion and ASP are remarkably similar when it comes to application design and development methodologies. Like ASP, ColdFusion does not have a built-in application framework or integrated support for methodologies and design patterns.
In this respect, ColdFusion and ASP both differ greatly from ASP.NET which leverages the .NET framework to ensure good application design. Enforced frameworks and structured development are both a blessing and a curse; while they encourage using best-practices and thus promote the creation of better applications, they can also get in the way of application development, often complicating development projects.
So does this mean that ColdFusion applications are automatically inferior? No, not at all. Like any language, including ASP and ASP.NET, you can use ColdFusion to write highly scalable and well designed applications, just as you can abuse it and write poorly-designed and implemented code. ColdFusion is a tool, and how you use it is entirely up to you. ColdFusion provides the language features needed to build highly scalable, structured, n-tiered applications. These include ColdFusion components—a form of object support data persistence, inheritance, and other object-based technologies, and support for all major reusable components, such as COM, CORBA, Java objects, and more.
In addition, while ColdFusion itself has no integrated application framework (deliberately and by design), you may indeed use frameworks and methodologies in ColdFusion application development. Two important initiatives are:
- Fusebox, a highly popular framework and methodology (http://www.fusebox.org/)
- Mach-II, an application framework implementing the popular MVC or Model View Controller pattern, based on Implicit Invocation Architecture (http://www.mach-ii.com/)
The key is that ColdFusion is designed for rapid development and unsurpassed productivity. This makes the language and technology highly accessible. At the same time, structured development is fully supported and encouraged. Rather than get in the way, ColdFusion is designed to empower developers in whatever way suits them best.
Well-designed applications are tiered. Developers write back-ends in COM, CORBA, .NET components, Java, EJBs, web services, and database stored procedures. Developers script presentation front-ends in rapid and productive development languages. ASP is primarily used as the presentation tier in web applications, just as is ColdFusion, where productivity is a primary objective.
.NET has an important place in the enterprise, as does Java and J2EE. Both provide solid and powerful platforms on which to build secure, reliable, and scalable applications. And thanks to open standards like SOAP and XML, both allow for a range of options at the presentation level. And that's a good thing, especially when ASP developers must consider migrating to a new platform and language, because that is less productive than what they had before in ASP.NET.
ColdFusion has proven itself to be the most code efficient and productive development environment in the space. Built on an underlying robust J2EE engine, ColdFusion gives developers the power of Java, access to the world of web services and .NET, true portability, multi-platform support, and unsurpassed productivity.
Developers with an investment in Microsoft technologies and the .NET platform will find ColdFusion to be a powerful and cost-effective addition to their development toolbox. And organizations already committed to ColdFusion can continue to take advantage of the original web development language while leveraging the power of .NET, J2EE, and more.
Power and productivity without compromising. You really can have it all.
About the author
Ben Forta is Macromedia's senior product evangelist and the author of numerous books,including ColdFusion 5 Web Application Construction Kit and its sequel, Advanced ColdFusion 5 Development. Ben is working on several new titles on ColdFusion MX. For more information visit www.forta.com.
You can contact Ben at mailto:ben@forta.com.