Monday, June 30, 2008

A CAPTCHA Server Control for ASP.NET

I'm sure everyone reading this is familiar with spam. There are two schools of thought when it comes to fighting spam:
1.Bayesian filtering, such as POPFile.
2.Challenge/response human verification, such as SpamArrest.
Both of these approaches have their pros and cons, of course. This article will only deal with the second technique: verifying that the data you are receiving is coming from an actual human being and not a robot or script. A CAPTCHA is a way of testing input to ensure that you're dealing with a human. Now, there are a lot of ways to build a CAPTCHA, as documented in this MSDN article on the subject, but I will be focusing on a visual data entry CAPTCHA.
There's already a great ASP.NET article on a CAPTCHA control here on CodeProject, so you may be wondering what this article is for. I wanted to rebuild that solution for the following reasons:
more control settings and flexibility
conversion to my preferred VB.NET language
abstracted into a full blown ASP.NET server control.
So, this article will document how to turn a set of existing ASP.NET web pages into a simple, drag and drop ASP.NET server control -- with a number of significant enhancements along the way.
The first thing I had to deal with was the image generated by the CAPTCHA class. This was originally done with a dedicated .aspx form-- something that won't exist for a server control. How could I generate an image on the fly? After some research, I was introduced to the world of HttpModules and HttpHandlers. They are extremely powerful -- and a single HttpHandler solves this problem neatly.
All we need is a small Web.config modification in the



<add verb="GET" path="CaptchaImage.aspx"
type="WebControlCaptcha.CaptchaImageHandler, WebControlCaptcha" />

This handler defines a special page named CaptchaImage.aspx. Now, this "page" doesn't actually exist. When a request for CaptchaImage.aspx occurs, it will be intercepted and handled by a class that implements the IHttpHandler interface: CaptchaImageHandler. Here's the relevant code section:

Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) _
Implements System.Web.IHttpHandler.ProcessRequest
Dim app As HttpApplication = context.ApplicationInstance

'-- get the unique GUID of the captcha;

' this must be passed in via querystring

Dim strGuid As String = Convert.ToString(app.Request.QueryString("guid"))

Dim ci As CaptchaImage
If strGuid = "" Then
'-- mostly for display purposes when in design mode

'-- builds a CAPTCHA image with all default settings

'-- (this won't reflect any design time changes)

ci = New CaptchaImage
'-- get the CAPTCHA from the ASP.NET cache by GUID

ci = CType(app.Context.Cache(strGuid), CaptchaImage)
End If

'-- write the image to the HTTP output stream as an array of bytes

ci.Image.Save(app.Context.Response.OutputStream, _

'-- let the browser know we are sending an image,

'-- and that things are 200 A-OK

app.Response.ContentType = "image/jpeg"
app.Response.StatusCode = 200

End Sub

A new CAPTCHA image will be generated, and the image streamed directly to the browser from memory. Problem solved!
However, there's another problem. There has to be communication between the HttpHandler responsible for displaying the image, and the web page hosting the control -- otherwise, how would the calling control know what the randomly generated CAPTCHA text was? If you view source on the rendered control, you'll see that a GUID is passed in through the querystring:

<img src="CaptchaImage.aspx?guid=99fecb18-ba00-4b60-9783-37225179a704"

This GUID (globally unique identifier) is a key used to access a CAPTCHA object that was originally stored in the ASP.NET Cache by the control. Take a look at the CaptchaControl.GenerateNewCaptcha method:

Private Sub GenerateNewCaptcha()
LocalGuid = Guid.NewGuid.ToString
If Not IsDesignMode Then
HttpContext.Current.Cache.Add(LocalGuid, _captcha, Nothing, _
DateTime.Now.AddSeconds(HttpContext.Current.Session.Timeout), _
TimeSpan.Zero, Caching.CacheItemPriority.NotRemovable, Nothing)
End If
Me.CaptchaText = _captcha.Text
Me.GeneratedAt = Now
End Sub

It may seem a little strange, but it works great! The sequence of ASP.NET events is as follows:
1.Page is rendered.
2.Page calls CaptchaControl1.OnPreRender . This generates a new GUID and a new CAPTCHA object reflecting the control properties. The resulting CAPTCHA object is stored in the Cache by GUID.
3.Page calls CaptchaControl1.Render; the special tag URL is written to the browser.
4.Browser attempts to retrieve the special tag URL.
5.CaptchaImageHandler.ProcessRequest fires. It retrieves the GUID from the querystring, the CAPTCHA object from the Cache, and renders the CAPTCHA image. It then removes the Cache object.
Note that there is a little cleanup involved at the end. If, for some reason, the control renders but the image URL is never retrieved, there would be an orphan CAPTCHA object in the Cache. This can happen, but should be rare in practice-- and our Cache entry only has a 20 minute lifetime anyway.
One mistake I made early on was storing the actual CAPTCHA text in the ViewState. The ViewState is not encrypted and can be easily decoded! I've switched to ControlState for the GUID, which is essential for retrieving the shared Captcha control from the Cache -- but by itself, it is useless.

CaptchaControl Properties:

Many of these properties have to do with the inherent tradeoff between human readability and machine readability. The harder a CAPTCHA is for OCR software to read, the harder it will be for us human beings, too! For illustration, compare these two CAPTCHA images:

The CAPTCHA on the left is generated with all "medium" settings, which are a reasonable tradeoff between human readability and OCR machine readability. The CAPTCHA on the right uses a lower CaptchaFontWarping, and a smaller CaptchaLength. If the risk of someone writing OCR scripts to defeat your CAPTCHA is low, I strongly urge you to use the easier-to-read CAPTCHA settings. Remember, just having a CAPTCHA at all raises the bar quite high.
The CaptchaTimeout property was added later to alleviate concerns about CAPTCHA farming. It is possible to "pay" humans to solve harvested CAPTCHAs by re-displaying a CAPTCHA and giving the user free MP3s or access to pornography if they solve it. However, this technique takes time, and it doesn't work if the CAPTCHA has a time-limited expiration.
Now u can create a simple yet effective CAPTCHA image class. Now that I've wrapped it up into an ASP.NET server control, it should be easier than ever to simply drop on a web form, set a few properties, and start defeating spammers at their own game!

Friday, June 27, 2008



1. Human friendly membership system - can handle 1 to 100,000 users and more
2. User profile - extensible according to the requirements
3. Search Engine Friendly - can get top rankings by Google, Yahoo and MSN
4. Sensible Categorization system - to create categories or classification of contents
5. Many types of content - not just text, but can handle audio, video, PDF, HTML,
6. SEARCH function - each term and name inside may be searchable, minimum 3 characters (example: ICT, or 123)
7. Human friendly and readable URLs - good for both human and Google
8. Syndication ready, RSS Feed and Live Bookmarking for readers and users, and other websites
9. Title, name of website, and slogan should be displayed in the web browser header
10. No default META TAG (because it will affect Google ranking negatively)
11. Easily read and indexed by Google, and able to be ranked in top search result pages, fast and definitive link from Google (usually less than 1 week to enter Google index)
12. Free from proprietary licensing, free to be used, modified, developed, and enhanced
13. Free from advertising and `Powered by ****' - you should have 100% freedom from the CMS logo and links; can put copyrights, own links and logos in the footer
14. Statistics and referrers - to see how people find your websites, what keywords, names, what ranking by Google, Yahoo and many search engines, who put links to your website
15. Contact form - at least 1 working properly to send feedback and inquiries to web owner or person in charge. No which gets spammed
16. User activities and logs - can see what users look for (search), who registers and logins, time and date, errror messages, content management
17. Easy to change logo, icon and links (without having to edit theme template)
18. Wealth of modules - easy to install, setup, and update - Additional modules to add functionality
19. Redirection
Instead of `Page not found - 404 or 403 error message' - the CMS must have a `Redirect' ready - sort of a `good butler' who shows the guests to the right entrance
20. Flexibility
- Can be used for different applications: Organization, E-Commerce, News, Blogs, Membership portal, Audio, Video Listening and Watching station, Information and Knowledge Center, Online Real-time Interaction, Fan sites, Downloads, Community, Club, Online Reservation system, Customer / Client Relationship Management *Example: Broadcast and video chat using third-party software by displaying the HTML or Java applets (LiveSite, U-Broadcast)
1 user to 100,000 users
-Don’t have to be programmer or hire anybody - you can learn and help yourself to the wealth of modules freely available
(see No. 18)
21. User access control
Accomplished by what is commonly called the `Access Control List'. It should be easy to add a group of users with permissions to access, use, read, edit, delete.
22. Out of the box FORUM
- Forum is a Bulletin Board, a place where users or members can post their articles, questions, suggestions. It is a place where you can interact with members, or amongst themselves. It is a safe avenue to interact and for a democratic type of online presence.
- There are still many organizations with websites but WITHOUT even a simple Forum
Another out of the box module useful to a community site is POLL. You should be able to create polls - a form of multiple choice questions where users can click on which answer, the results also display statistics bar.
23. No Session IDs
What is a Session ID? For a user, it is nothing useful. But for the website, Session ID can be a bane by affecting Search Engine ranking negatively. The absence of Session ID is the key to Search Engine friendliness.
Long and weird URL generated for the `Login' link - this will confuse the Search Engine spider.
You should have all the ingredients to treat your special guest right - the Search Engine `spiders' - if they like your website, they will return high ranking. (No Session ID, no irrelevant meta keywords; Friendly URLs, Title and Name for each page and section) Not only for Search engine spiders, `Clean URLs' and no Session IDs are also good to human eyes.
24. Small basic package - lean and mean
Basic package should be compressed as .tar.gz to about 500 KB, small enough to fit in a diskette plus additional power modules. There should be no Text and HTML Editor included. This is not a disadvantage. The small size means that it can be downloaded quickly and distributed easily for example by giving out free diskettes to those that want to install and learn it themselves. We usually pack additional modules to be around 800 KB which include nifty modules such as webform, video, flexinode, image, notify, and newsletter'.
25. Multi-site capabilites
Each and every site, if linked from the main site, should be independent, separated, and can get ranked high by Search Engines. Your website is like a huge library, each section can have different theme and layout.
26. Multi-language capabilities
Should support UTF-8 which means that your web browser can display non-English letters correctly (Arabic, Chinese, Japanese letters are supported by UTF-8). And you can just type in UTF-8 letters using your keyboard program, or copy and paste non-English UTF-8 texts from other websites or desktop software to display them correctly. Bear in mind that your PC should also have TrueTypeFonts (TTF) which support the language you want. Windows XP users for example have new Courier TTF which can display Arabic and Eastern fonts quite nicely.
27. Allowing for Future Extension. Immediate deployment of Functionalities.
CMS must NOT limit what you can and want to achieve online. For example the user should be able to create an online quiz.
28. Compliance with W3C. Independent of proprietary or heavy system on user side.
Websites should be able to be displayed correctly and accessible by using different web browsers (Mozilla Firefox, Konqueror, IE, Opera, Netscape).
29. User friendly to the writer / publisher; Worry free, stress free for new users (website owners)
- The second thing after creating the first account and logging in is `Create content'
- Even without going further and confused about system configuration, a writer can just click on `Create content' he/she sees on the left column, and starts publishing articles (default content types are page, story, book ....)
- He/she needs not worry so much on the first day using the CMS. He knows that the content gets across the Internet and somebody somewhere can access it (Example: CEO wants to see reports, Potential clients want to see company profile - supply them with the correct URL and let them access the Internet)
(No need to wait to create categories, that can be done later)
- No need to hire a Webmaster or IT officer whose task is to publish contents - the writer can do it himself
(Write, copy & paste, Submit, Publish)
- No need for the website owner to hire programmers or pay more to CMS provider.
He/she can venture on his own but of course can get pointers and help from the CMS user community whether in person or online.
30. Safe and secure CMS
- In general, there is no CMS, whether free, open source, or proprietary CMS based on any language that is hacker-proof
- But the CMS must be inherently strong and difficult to be hacked by irresponsible people by whatever tools
- The CMS is designed with safety and security top priority

31. User friendly to the visitors and web browsers

- Some PHP-based websites are just dysfunctional, notwithstanding nice graphics and public & media hypes
- Some websites have persistent problems and webmasters are either ignorant, unaware of, or just cannot repair or improve
- Clean URLS are commended. No Session IDs. Easy bookmarking. Easily remembered URLs.
32. Lean and fast
- Must not have `inherent' problem when site gets heavy uses (many visitors, users, activities)
- Can have a `throttle' module to disable certain functionalities so that heavy load is not going to make the site crashes or goes blank or user see `Document contains no data'
CMS should have an UPLOAD feature which enables a file to be uploaded as attachment to an article. The attachment can be txt, pdf, xls, doc, odp, bmp, image files, mp3, wav, compressed or executable file. The number of attachments can be more than 1. User access permission can be set to determine who will be able to see the list of attachments and download them. The uploading feature is also a quick way to store files into a website or portal. Again, file storage can be configured so that whether it is accessible by public or private, or known only by the owner.
This UPLOAD feature should also be used to upload PICTURES (Images, jpg, gif, png, Animated GIFs) and if you don't have additional modules specifically for `Image',`Album'`Gallery',`Picture'. You should be able to display the uploaded picture by using HTML code anywhere.
34. Each and every category level should gain good SEO
Even if you are `lazy', you will be impressed that your website can get good ranking for keywords in your categories. By `lazy' we mean that you didn't create URL Alias and you didn't put articles yet. Even if left empty, people will find your website from Google, Yahoo, MSN, or other search engines which refer searches to exact or close matchings of keywords with categories.
35. Trustworthy and serious effort by the developers
Open source and easy compatibility with 3rd party tools.
Should have an out-of-the-box BLOG module which is powerful and fulfills the definition of a Weblog.
Blogging can be such that each person's blog will have its own RSS feed, or it can also be put into specific categories, separated from other content types, and the category in turn has its own RSS feed. You can subscribe to just one's blogs, or you can subscribe to many blogs in one category that you like. You can do `Live Bookmarking' using your web browser, and you can display the `syndicated content' in your own website which has the `Aggregator' tool
37. COLLABORATION - Collaborative document and content
Book module. A `book page' can be short, or long. Each book page can then be put under the `main book page' which is called the PARENT (independent, top-level book). You can also `outline' any page, video, audio, image into the book. What you will see is the `Book Navigation' visible below the content as `up, next, previous' and the titles of each book page and the main page in a block. Remember that you can control this feature by `Access Control List'.
38. Count page views
39. Tracker - tracking a user's page visit, posts (content) and comments. `Personal blogging' track if BLOG enabled. If enabled, there should be a `recent posts' link in the Navigation menu.
40. Default `front page' can be set to any specific page
For example - user registration page, user login page, user profile, Search, Categories, Sitemap, Image Gallery, Slideshow (if you have one) *
Remember that `Error page' 403 and 404 `page not found' can be redirected also to anywhere
41. `Revert revisions'
Creating and reverting revisions - default for admin, can be assigned to users in ACL. You can also set if revisions are accessible or not to readers.
- Not just `comments', but also `Add additional information, opinion, data, info' and `objection' `disagree'.

43. USER AUTHENTICATION - Validation email - Verification of registered user
USER GREETING - upon registration and activation
Even if you didn't bother to create user `profile fields', you can put some text in the `User Registration guideline', and the e-mail which will be sent to the user' email address.
Some CMS and Bulletin Board sent very strange messages which are encrypted. It might be caused by non-UTF texts (Unicode fonts) or non-English message which cannot be read by your web browsers automatically. Some webmasters are ignorant about this problem. The danger is that the email will be thought of as `spam' or `dangerous e-mail' when the user sees weird e-mail sender names and titles and delete it right away.
Some CMS and BB also take quite long time to send the `validation email' or `activation link' which will only make the potential user give up on your website. Worse still, some CMS or Bulletin Board FAIL altogether to send the `validation email' or `activation link' . This lagging might be webhosting problem, or it could be caused by high traffic, or it might be an inherent problem of the CMS/BB. It could also because of problems with the user's e-mail server.
User Management features are critical especially for Membership Portal and E-Commerce, Fan sites, exclusive websites, and Community portals. We must strive to get rid of so many hurdles and obstacles to the users.
Feature to turn Single Sign on / off
45. FREE TAGGING - again, a great innovation in CMS
As far as we are concerned, Free Tagging if enabled for a particular content type, enables a user posting article to `tag' his or her article, news or picture with whatever keywords permissible and suitable. What more, MULTIPLE TAGS can also be enabled. Again, these tags will be read by SE spiders and they, in addition to descriptive categories, titles, and URL aliases, will help your site gets ranked fast and high by Google. (What about Yahoo? I am not sure, Yahoo search engine still reads the Meta tags).
46. PING
- `Ping module' is: Alert to other sites when your site is updated. *The ping module is useful for notifying interested sites that your site has changed. It automatically sends notifications (called "pings") to the pingomatic service [] to tell it that your site has changed. In turn pingomatic will ping other services such as, Technorati,, BlogRolling,, Moreover, etc.
47. Confidential or `secret' data; Exclusive viewing of content and user profiles only to certain groups of users; Exclusive membership
The CMS should be able to switch the access to user registration, content and profiles on and off quickly. The `User registration and Login' block can also be hidden quickly. The user profile field can be set to `Private - only privileged users (admin) can access'.
User Profile revisited - `Private profile field'
48. Templates - standards
49. Customisable menus
By default, there should be a Navigation menu which makes sense to the user and admin.The most basic and important menu link which should be displayed:
Create content. Then, the links to: My Account, Administer, and Logout. If applicable: My recent posts, all recent posts. For an anonymous user (not logged in, or just browsing): All recent posts.
A new menu item should be added, as well as a new menu which is displayed in a separate block from the Navigation block.
For admin, user, writer - Workflow for writers (that is not concerned with web administration and is not assigned as admin):
Creating content - default settings: Teaser - unlimited, or 200 (default) - 600 words. Published (default) or Moderated. Sticky. Unpublished. Promoted to front page (default for page and story). Create new revision. Inputs (Textfields) - Title, Body, Attach files (if enabled). Preview or Submit.
`Submit page / story / content':
Publishing options - Published -In moderation queue-Promoted to front page -Sticky at top of lists -Create new revision
Side display - in `blocks' - you can add a custom block, and put it top header, bottom footer, left, right, or inside under list of content. Mission box can also display HTML so that you can display logos and introduction.
Remember that you can create a piece of text, HTML, and PHP, and Java applets in blocks. You can also copy and paste Google AdSense which is .js script into custom blocks, mission box, or footer.
User can select theme -
User can change username
Change color - if your boss doesn't like the green color, just change it to other colors or let him/her switch colors using the color dial.
Save as HTML - Title of article, Name, URL (if using alias) - saving a page using web browser
CMS should enable you to handle `blocks' as you wish. The block control is not confusing.
Yyou can do a lot of things with blocks - display, hide, show only in specific page or content type, or show only in specific article. Block can handle text, HTML, img src, audio, video, PHP. Block creation can be set only for admin, or privileged users. Block can be hidden or displayed only for privileged users. You can also set `show block by default but users can choose to hide them',`hide by default but...' - individual preferences to see or not.
Block system enables you to make use of spaces - header, footer, left and right column, and content under your articles. You can put links and images, audio and video consoles in blocks. If you like a Java script, CGI script, or PHP snippets, you can use them in blocks. You can create a scrolling text or `moving pictures' using `marquee' HTML to make your site lively.

Monday, June 23, 2008

Steps for Installing ColdFusion

IIS Installation
Control Panel > Add-Remove Programs > Windows Components

Install Cold Fusion 6.1

Install new version of Cold Fusion MX
Developer Edition
Server Configuration
Default Folder
All IIS WebSites
Default Inetpub directory
Enter Admin Password

Start Installation

Configuration of Cold Fusion Server
enter RDS Password
Install example application

Install MSDE stand-alone DB (MS SQL Server)
open notepad setup=sapwd = "Kar$123"
install sqlserver setup
install msmanager
----->register database(local)for default tables
--->create a folder


create a SQL Server user “user_sl” with pwd as user_sl
Restore DB in D:\SQLDATA\MSSQL\data
DB name - StoneLocatorLOCAL


[Macromedia][SQLServer JDBC Driver]Error establishing socket. Connection refused: connect
Solution :-
Run svrnetcn.exe from cmd prompt and enable Named Pipes and TCP/IP and click OK.
Restart the MSDE service

creating a sql server authentication--->
open server objects-->
in the server object click SQL SERVER AUTHENTICATION
provide the password
and confirm password
then click user(rt click)----->new user

provide loginname and password

In the CFIDE adminstrator write datasource name—xyz
database name -specified in database
server -localhost
username- (database)
password- (database)

Tags Used in CFML

Let's look at some of the tags that make up CFML. This section provides a quick overview of some of the most common tags and their use. This should give you a general idea of what ColdFusion MX 6.1 is capable of. Following later are descriptions and code snippets detailing how to use some of these tags in a ColdFusion page.
ColdFusion MX 6.1 has more than 100 CFML tags, which Macromedia's documentation breaks down into the following categories:
Application framework
Database manipulation
Data output
Exception handling
File management
Internet protocol
Page processing
Variable manipulation
However, what's more important are the specific tags that you will discover you use every day in ColdFusion. Some of the more useful tags are:
cfchart: Generates charts on the fly in a variety of formats, including .jpeg, .png, and .swf (Flash).
cfdirectory: Performs directory management tasks and allows you to create, delete, rename, or list the contents of a directory.
cfdump: Displays the contents of a variable to the screen for debugging purposes. Variables can contain simple values such as strings and numbers, or complex data such as Recordsets and structures.
cferror: Tells ColdFusion how to handle errors that occur in your application.
cffile: Performs file-management tasks and allows you to read, write, delete, move, rename, or append data to files on the server.
cfform: Similar to HTML forms, except that it allows developers to take advantage of automatically generated JavaScript validation provided by the ColdFusion server.
cfftp: Allows ColdFusion to FTP files to and from remote FTP sites.
cffunction: Allows you to write your own custom functions using CFML tags.
cfhttp: Allows you to post variables to remote sites, or grab the contents of a file on a different server.
cfif: Performs if ... then ... else logic in ColdFusion, running code only if certain conditions are met.
cfinclude: Embeds other HTML or CFML code into the current document. This allows developers to break up larger files and reuse certain code/functions throughout the site.
cfinput: Used in conjunction with the tag to take advantage of built-in JavaScript validation.
cflocation: Redirects the currently running page to a different page, or redirects users to a different site altogether.
cfloop: Allows you to loop over Recordsets and structures a defined number of times, or while a certain condition is true.
cfmail: Sends an e-mail to a single user or group of users.
cfmodule: Allows you to call your own custom tags with ColdFusion.
cfoutput: Used to output the value of a variable, or loop over a Recordset.
cfparam: Checks to see if a certain variable exists; if not, it creates the variable and assigns a default value. It can also be used to validate the data type of a variable.
cfquery: Used to pass SQL statements to a database.
cfqueryparam: Used within to insert dynamic values into a SQL statement.
cfset: Define the value of a variable.
cfstoredproc: Execute a stored procedure (if supported by your database of choice).
cfswitch: Passes control to a matching tag and evaluates passed expressions. This could be performed using a series of tags, but this method saves space and simplifies things.
cftry: Monitors a block of ColdFusion code and tries to catch any errors that may occur. It is used in conjunction with the tag.
ColdFusion also has a couple of special files that are triggered before or after every user request and can be used to hold site-wide variables or settings; we will look at these now.

Resolving issues in sql server & dream weaver

Steps For using CF8 libraries in DremWeaver8 editor

  1. Download dreamwwaver extension library from

  2. double click on the MXP fille

  3. if you open the dreamweaver editor, close it & open it again

SQL SERVER - Fix : Error : 40 - could not open a connection to SQL server.

An error has occurred while establishing a connection to the server when connecting to SQL server 2005, this failure may be caused by the fact that under default settings SQL server does not allow remote connection. ( provider: Named Pipes Provider, error: 40 - could not open a connection to SQL server. )


1) Make sure SQL SERVER is up and the instance you try to connect is running.

2) Your system Firewall should not block SQL Server port.

3) Go to Computer Management >> Service and Application >> SQL Server 2005 Configuration >> Network Configuration.Enable TCP/IP protocol. Make sure that SQL SERVER port is by Default 1433.

4) Now follow this KB Article of MSDN depending on your server :;EN-US;914277

For restoring database in sql server 2005

  1. right click on Databases in sql sever management studio express-restore database

  2. give database name in "To database"

  3. check radio button "from device" >> click on "_ _ _" >> click on "add" >> select the location of bak file & then click OK & again ok

  4. click on options in left menu >> change the path in "restore as" to the location where mdf & ldf files exists (make sure name doesnot in the specified folder )

  5. finally click on "OK"

Steps For using CF8 libraries in DremWeaver8 editor

  1. Download dreamwwaver extension library from

  2. double click on the MXP fille

  3. if you open the dreamweaver editor, close it & open it again

SQL SERVER - Fix : Error : 40 - could not open a connection to SQL server.

An error has occurred while establishing a connection to the server when connecting to SQL server 2005, this failure may be caused by the fact that under default settings SQL server does not allow remote connection. ( provider: Named Pipes Provider, error: 40 - could not open a connection to SQL server. )


1) Make sure SQL SERVER is up and the instance you try to connect is running.

2) Your system Firewall should not block SQL Server port.

3) Go to Computer Management >> Service and Application >> SQL Server 2005 Configuration >> Network Configuration.Enable TCP/IP protocol. Make sure that SQL SERVER port is by Default 1433.

4) Now follow this KB Article of MSDN depending on your server :;EN-US;914277

For restoring database in sql server 2005

  1. right click on Databases in sql sever management studio express-restore database

  2. give database name in "To database"

  3. check radio button "from device" >> click on "_ _ _" >> click on "add" >> select the location of bak file & then click OK & again ok

  4. click on options in left menu >> change the path in "restore as" to the location where mdf & ldf files exists (make sure name doesnot in the specified folder )

  5. finally click on "OK"

Sunday, June 22, 2008

50 JavaScript Interview Questions

D,A,B,C,C,A, B,B,A,B,B,D,A,A,C,D
1. Why so JavaScript and Java have similar name?

A. JavaScript is a stripped-down version of Java

B. JavaScript's syntax is loosely based on Java's

C. They both originated on the island of Java

D. None of the above

2. When a user views a page containing a JavaScript program, which machine actually executes the script?

A. The User's machine running a Web browser

B. The Web server

C. A central machine deep within Netscape's corporate offices

D. None of the above

3. ______ JavaScript is also called client-side JavaScript.

A. Microsoft

B. Navigator

C. LiveWire

D. Native

4. __________ JavaScript is also called server-side JavaScript.

A. Microsoft

B. Navigator

C. LiveWire

D. Native

5. What are variables used for in JavaScript Programs?

A. Storing numbers, dates, or other values

B. Varying randomly

C. Causing high-school algebra flashbacks

D. None of the above

6. _____ JavaScript statements embedded in an HTML page can respond to user events such as mouse-clicks, form input, and page navigation.

A. Client-side

B. Server-side

C. Local

D. Native

7. What should appear at the very end of your JavaScript?

The <script LANGUAGE="JavaScript">tag

A. The </script>

B. The <script>

C. The END statement

D. None of the above

8. Which of the following can't be done with client-side JavaScript?

A. Validating a form

B. Sending a form's contents by email

C. Storing the form's contents to a database file on the server

D. None of the above

9. Which of the following are capabilities of functions in JavaScript?

A. Return a value

B. Accept parameters and Return a value

C. Accept parameters

D. None of the above

10. Which of the following is not a valid JavaScript variable name?

A. 2names

B. _first_and_last_names

C. FirstAndLast

D. None of the above

11. ______ tag is an extension to HTML that can enclose any number of JavaScript statements.





12. How does JavaScript store dates in a date object?

A. The number of milliseconds since January 1st, 1970

B. The number of days since January 1st, 1900

C. The number of seconds since Netscape's public stock offering.

D. None of the above

13. Which of the following attribute can hold the JavaScript version?




D. None of the above

14. What is the correct JavaScript syntax to write "Hello World"?

A. System.out.println("Hello World")

B. println ("Hello World")

C. document.write("Hello World")

D. response.write("Hello World")

15. Which of the following way can be used to indicate the LANGUAGE attribute?

A. <LANGUAGE="JavaScriptVersion">

B. <SCRIPT LANGUAGE="JavaScriptVersion">

C. <SCRIPT LANGUAGE="JavaScriptVersion"> JavaScript statements…</SCRIPT>

D. <SCRIPT LANGUAGE="JavaScriptVersion"!> JavaScript statements…</SCRIPT>

16. Inside which HTML element do we put the JavaScript?

A. <js>

B. <scripting>

C. <script>

D. <javascript>

17. What is the correct syntax for referring to an external script called " abc.js"?

A. <script href=" abc.js">

B. <script name=" abc.js">

C. <script src=" abc.js">

D. None of the above

18. Which types of image maps can be used with JavaScript?

A. Server-side image maps

B. Client-side image maps

C. Server-side image maps and Client-side image maps

D. None of the above

19. Which of the following navigator object properties is the same in both Netscape and IE?

A. navigator.appCodeName

B. navigator.appName

C. navigator.appVersion

D. None of the above

20. Which is the correct way to write a JavaScript array?

A. var txt = new Array(1:"tim",2:"kim",3:"jim")

B. var txt = new Array:1=("tim")2=("kim")3=("jim")

C. var txt = new Array("tim","kim","jim")

D. var txt = new Array="tim","kim","jim"

21. What does the <noscript> tag do?

A. Enclose text to be displayed by non-JavaScript browsers.

B. Prevents scripts on the page from executing.

C. Describes certain low-budget movies.

D. None of the above

22. If para1 is the DOM object for a paragraph, what is the correct syntax to change the text within the paragraph?

A. "New Text"?

B. para1.value="New Text";

C. para1.firstChild.nodeValue= "New Text";

D. para1.nodeValue="New Text";

23. JavaScript entities start with _______ and end with _________.

A. Semicolon, colon

B. Semicolon, Ampersand

C. Ampersand, colon

D. Ampersand, semicolon

24. Which of the following best describes JavaScript?

A. a low-level programming language.

B. a scripting language precompiled in the browser.

C. a compiled scripting language.

D. an object-oriented scripting language.

25. Choose the server-side JavaScript object?

A. FileUpLoad

B. Function

C. File

D. Date

26. Choose the client-side JavaScript object?

A. Database

B. Cursor

C. Client

D. FileUpLoad

27. Which of the following is not considered a JavaScript operator?

A. new

B. this

C. delete

D. typeof

28. ______method evaluates a string of JavaScript code in the context of the specified object.

A. Eval

B. ParseInt

C. ParseFloat

D. Efloat

29. Which of the following event fires when the form element loses the focus: <button>, <input>, <label>, <select>, <textarea>?

A. onfocus

B. onblur

C. onclick

D. ondblclick

30. The syntax of Eval is ________________

A. [objectName.]eval(numeric)

B. [objectName.]eval(string)

C. [EvalName.]eval(string)

D. [EvalName.]eval(numeric)

31. JavaScript is interpreted by _________

A. Client

B. Server

C. Object

D. None of the above

32. Using _______ statement is how you test for a specific condition.

A. Select

B. If

C. Switch

D. For

33. Which of the following is the structure of an if statement?

A. if (conditional expression is true) thenexecute this codeend if

B. if (conditional expression is true)execute this codeend if

C. if (conditional expression is true) {then execute this code>->}

D. if (conditional expression is true) then {execute this code}

34. How to create a Date object in JavaScript?

A. dateObjectName = new Date([parameters])

B. Date([parameters])

C. dateObjectName := new Date([parameters])

D. dateObjectName Date([parameters])

35. The _______ method of an Array object adds and/or removes elements from an array.

A. Reverse

B. Shift

C. Slice

D. Splice

36. To set up the window to capture all Click events, we use which of the following statement?

A. window.captureEvents(Event.CLICK);

B. window.handleEvents (Event.CLICK);

C. window.routeEvents(Event.CLICK );

D. window.raiseEvents(Event.CLICK );

37. Which tag(s) can handle mouse events in Netscape?

A. <IMG>

B. <A>

C. <BR>

D. None of the above

38. ____________ is the tainted property of a window object.

A. Pathname

B. Protocol

C. Defaultstatus

D. Host

39. To enable data tainting, the end user sets the _________ environment variable.





40. In JavaScript, _________ is an object of the target language data type that encloses an object of the source language.

A. a wrapper

B. a link

C. a cursor

D. a form

41. When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type ___________

A. ScriptObject

B. JSObject

C. JavaObject

D. Jobject

42. _______ class provides an interface for invoking JavaScript methods and examining JavaScript properties.

A. ScriptObject

B. JSObject

C. JavaObject

D. Jobject

43. _________ is a wrapped Java array, accessed from within JavaScript code.

A. JavaArray

B. JavaClass

C. JavaObject

D. JavaPackage

44. A ________ object is a reference to one of the classes in a Java package, such as netscape.javascript .

A. JavaArray

B. JavaClass

C. JavaObject

D. JavaPackage

45. The JavaScript exception is available to the Java code as an instance of __________

A. netscape.javascript.JSObject

B. netscape.javascript.JSException

C. netscape.plugin.JSException

D. None of the above

46. To automatically open the console when a JavaScript error occurs which of the following is added to prefs.js?

A. user_pref(" javascript.console.open_on_error", false);

B. user_pref("javascript.console.open_error ", true);

C. user_pref("javascript.console.open_error ", false);

D. user_pref("javascript.console.open_on_error", true);

47. To open a dialog box each time an error occurs, which of the following is added to prefs.js?

A. user_pref("javascript.classic.error_alerts", true);

B. user_pref("javascript.classic.error_alerts ", false);

C. user_pref("javascript.console.open_on_error ", true);

D. user_pref("javascript.console.open_on_error ", false);

48. The syntax of a blur method in a button object is ______________

A. Blur()

B. Blur(contrast)

C. Blur(value)

D. Blur(depth)

49. The syntax of capture events method for document object is ______________

A. captureEvents()

B. captureEvents(args eventType)

C. captureEvents(eventType)

D. captureEvents(eventVal)

50. The syntax of close method for document object is ______________

A. Close(doc)

B. Close(object)

C. Close(val)

D. Close()

where we use javascript and for which purpose we use
javascript how?
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
A JavaScript consists of lines of executable computer code
A JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
Everyone can use JavaScript without purchasing a license
JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a
scripting language with a very simple syntax! Almost anyone
can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A
JaDoes javascript support multidimensional arrays ?rmation on the visitor's

How do you send a message to the browser in JavaScript?
Either use (document.write) or use web technology like php
and pass the value through url and get on that page.
What looping structures are there in JavaScript?
FOR, While and Do...While

What does "1"+2+4 evaluate to?
nything which follows string is converted to String.
Hence, "1" is string, and the digits 2 and 4 which comes
after this, also become part of string only.

So the answer is 124

What are the security related issues in JavaScript scripts?
Basically the source code of the Javascript will be visible
when we select the source,hence the javascript part of the
code is fully transparent.
Secondly javascripts can be disabled on the browser easily
Basically all that naveen said is true but there cannot be
any instance of js hiding it can always be viewalble if u
know how to do it.

Also other security issues are that u can track the ip of
the system on which the site has been view also the time of
loading on the current system.

Since javascript has no current standard which monitors the
use of js it can be used in any way you want to.
Therefore security related issues in javascript is just a
idea but never a hard code procedure.

What is the use of a form in html page? Is there any way to submit the page without using the form.

In html we can use JAVASCRIPT for validation purpose. Since
we require a specific form name for validation and to
specicy the action after certain operation is performed.

why you used Java Script? Can it use for both client side and server side validation purpose?
Mainly used for client side scripting purpose.JavaScript is
a platform-independent,event-driven, interpreted client-
side scripting and programming language.

javascript cannot be used as server side scripting.

What is the difference between GET and POST?
A. GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
What is this keyword

The this keyword is a synonym for the current object and can
be used with properties

: How do you convert numbers between different bases in JavaScript?
using parseInt(value,base)
also parseFloat(number,base)

CFCs in Fusebox

Ok, so it’s been a while since the last fusebox tutorial and I figured enough time has passed since you began working with fusebox and you should be feeling fairly confident by now with it. I let some time lapse for several reasons, first and foremost I’ve been busy, second cfc’s in fusebox are rather complex thing to get into. It takes some understanding of how fusebox works before you can dive into cfcs.

Anyway, I’ve gotten a few responses as to what I should do to display the use of cfcs in fusebox, the majority were rather complex and would require a mountain worth of explaining. I decided to go with a simple application just because of the complexity of calling cfcs and for the widest possible understanding from everyone. You can easily build your own complex applications once you have the basics.

Ok so to begin download the sample app I have. I have not added anything to it that is covered here, but it has the basic setup of the fusebox and circuits. Unzip it to a site in your wwwroot folder. Once that is finished we can begin.

Ok, so first off let’s talk a bit about fusebox and how it calls cfcs. Fusebox reads and calls cfcs as a java class. No worries if you have no idea what that are, you don’t really need to understand java classes to work with cfcs.

Ok first off open the fusebox.xml file. Within the first couple of lines you will see an opening and closing tag named “classes”. In-between those two lines add the following code:

<class alias="testClass" type="component" classpath="yoursite.cfc.test" />

Ok I highlighted “yoursite” for a very good reason and here it is. For those of you using a developing server if inside your wwwroot folder you have a folder for a site named something like you are going to get an error when you create the dot path. I suggest making a completely new site with no dots anywhere in it’s name. For example “testingsite” NOT “”. If you insist on using your dot riddled folder you can declare a class path in your cf admin panel to the cfc folder. I am not going to explain that, you can find information in the tech notes and on macromedia if you decide to go that path. For those of you uploading to your own hosted site. You do not need to name your site. Chances are your host has already added your site to a class path if not you can ask them to. So you would just need a dot path to the cfc from root. IE (cfc.test). Please do not email with questions about this. I do not have access to your server you are using so I wouldn’t be able to tell you anything different than I have here.

Ok that warning out of the way what did we just do. We created a class and named it “testClass” we told it that it is a component. (The other option I believe is webservice, but I have never had a need for this.) And told it where to find our cfc.

Save and open the circuit.xml.cfm file under the folder “main”.

Again copy the code below to the fuseaction called “testcfc” making sure you place it above the included page.

<instantiate object="application.test" class="test" arguments="id" />
<invoke object="application.test" methodcall="testFun(" returnvariable="myResult" />

So what did we do here. First off you can set all the classes in the world in your fusebox.xml file and they would just sit there doing nothing without that first line above. All classes you set will need to be instantiated to be used. The object attribute sets the class in a variable that can be used application wide. Hence the “application” prefix. The class attribute says what class to give this “application” variable to. And here is the tricky part. You must pass any and all arguments that are in your cfc in the arguments attribute. Delimit them with a comma. In our cfc we are about to make we are going to have a cfarguement of “ID” so we declare that here.

The next line is just like a cfinvoke tag. We tell it that we want to invoke the object “application.test” that we just set above it and the method in which to use in our cfc. The method is the same as the cffunction name. In this case we have a cffunction method called “testFun”. We also included the ID argument within the brackets. In this case it is our url variable which we are using as our ID. Then we want to name the variable we would like to use once our cfc has processed. Which we ae just going to use the same variable that is passed back to us from the cfc called “myResult”.

Ok hard part over. Now lets make our cfc.

Here’s the code to do that.

<cffunction name="testFun" access="public" returntype="string">
<cfargument name="ID" type="string" required="yes">
<cfset myResult="Today is: #DateFormat(Now(),"MM/DD/YYYY")#">
<cfreturn myResult>

Notice that the cfargument is required. It doesn’t have to be, but since we are passing it we will require it. Then we do a little code telling it what to do. And Return the results. I am not going into detail here, because I am assuming that if you are doing this tutorial you have some knowledge of cfcs.

Go ahead and test our your app by opening your index.cfm file into your browser. Click on the available link and you will see the cfc in action. If you get an error message check the path to your cfc in your fusebox.xml file. Otherwise it should work. Well it is that simple.

The FuseBox Organization believes it has devised new methods of ColdFusion coding that will allow CF to cure acne, heal canker sores, and most importantly prevent hair loss... The FuseBox Organization invites the CF development community to examine and try these standards. Suggestions are always welcome. These papers are specific to Allaire's ColdFusion, although we've found that because of the advent of WDDX it would be possible to very easily integrate a ColdFusion "Fusebox" application with another application written using a different web application server (such as ASP or Perl). Similar standards would need to be created in those languages. If anyone is interested in doing so, please contact me directly, I'm pretty interested in doing this also, but don't have the expertise many other web application languages.

The Fusebox Model
Fusebox applications are modeled around an electrical Fusebox in a House. For example, the electrical circuit for your kitchen is separated from your bathrooms and also separated from your living room. In the end, your house has electricity, to the common family they never notices that the electricity is really separated. When little joey decides it would be funny to put a fork in the electrical socket in the kitchen and he blows out the fuse. So the power goes out in the kitchen but it doesn't go out in the living room. This is similar to a software program, when a user does something that the developer wasn't expecting them to do the program throws an error. With Fusebox we separate each application from the other application's in the home thus allowing circuits to be blown without taking out ALL the power in the home application.
There are two types of applications in a large scale Fusebox application.
Circuit Application - If you've ever written a Fusebox application before you've probably written a Circuit application. This generally consists of a single directory of files (although it doesn't have to be limited to this). A circuit application generally does a few related tasks. An example is the eBags Search engine: This search engine has multiple Fuseactions but it's main purpose is to help the user find the product they're looking for. Another example is the eBags Testimonials: This application allows users to view,add,edit,delete testimonials (depending on the user's security level)
Home Application - This is the overall application, it is made up many circuit applications that are tied together with an interface. The common user does not realize they are using a circuit applications they are under the impression that they are using the Home application. An example of a Home application is The entire site is made up of many many circuit applications that do various specific tasks such as searching, information, product details, purchasing etc. Although to the common user whether they are searching for luggage, or checking they are still in the home. This is similar to a real life home. Whether a person plugs a television into an outlet in the kitchen or in the living room, they still get power, because they are in their home. (assuming they paid the power bill :). It is important to realize that circuit applications may contain bugs in them.... but if they do, it is possible to remove them from the Home application without bringing the rest of the Home application down. It is also possible to go the other direction. When a new Circuit is added to the Home application it can be added without affecting the other circuit applications.
Because web sites are no longer static it is important to be able to add new features or remove old features from the site without affecting the entire site. This method of building your large scale applications will prove to be very helpful when it comes time to upgrade the application.
How to tie Circuit Applications together with the Home Application
The Home application is made up of many Circuit applications so when writing a large scale application it's important to be able to tie everything together. The Home application is nothing more than a concept it is the result of multiple circuit applications. You can think of the Home application as a directory structure on your CF server. By putting all of your circuit applications in the same root directory that entire directory structure could make up the Home application. The root directory of your Home application will contain the app_globals.cfm file. This file will be included in all app_locals.cfm files which are in every circuit application.
The root directory of your Home application may contain a circuit application itself. If you take a look at: you will notice that a few of the links go to: This is a circuit application that is in the root directory. These tasks that may be not fit in any of your other circuit applications.
Once you've set up your directory structure that will be able to handle multiple circuit applications. You will eventually need to link your many circuit applications together. This can be done so by using the different types of links that is described in Technique 7 Use the universal format as much as possible (i.e. point links and forms to: index.cfm). There will be cases that you cannot use the universal format such as when building menus, I recommend using the absolute format (i.e. /directoryname/index.cfm) in your menus. The reason for this is that it will allow you to use the same menu on multiple circuit applications while still having the links in tact.

Saturday, June 21, 2008

ColdFusion Interview Questions

How would you loop through a SQL result set stored in the CF variable named my “results” and output the result set columns named “cola” and “colb” in an html table?

<cfoutput query=”results”>

Given the url http://localhost/test.cfm?printmesg=yes How would you write an if statement which would echo the message “hello world!” if the url parameter printmesg equals “yes”.

<cfif isDefined(”url.printmesg”) and url.printmesg IS “yes”>
hellol world!

When is it appropriate to use <cfparam> versus <cfset>?

<cfparam> allows you to set a default parameter if that variable does not have a value bound to it.
<cfset> merely sets the value of a given variable.

Given the datasource named “mydb” and a SQL stored procedure named “mystoredproc” which takes the following two parameters one VARCHAR param and one INTEGER parameter respectively, how would you declare this using the cold fusion tags <cfstoredproc>, <cfprocparam>, and <cfprocresult>?

<cfset param1 = “this is my test string”>
<cfset param2 = 1>

<cfstoredproc datasource=”mydb” procedure=”mystoredproc”>
<cfprocparam type=”IN” cfsqltype=”CF_SQL_VARCHAR” dbvarname=”@parama”
<cfprocparam type=”IN” cfsqltype=”CF_SQL_INTEGER” dbvarname=”@paramb”
<cfprocresult name=”myprocresult”>

How do you call a module named “testmod.cfm” with the parameters param1=”yes” and param2=5?

<cfmodule template=”testmod.cfm”

When is it appropriate to use <cfinclude> versus <cfmodule>?

Given two tables:

| id |
| title |
| rating |
| length |
| country |

| id |
| movie_id |
| name |

How would you write a SQL statement to find the names of all the actors associated with a movie titled “fight club”?

FROM movie INNER JOIN actor ON = actor.movie_id
WHERE movie.title = ‘Fight Club’

| id |
| title |
| rating |
| length |
| country |

| id |
| movie_id |
| name |

How would you write a LEFT JOIN statement to return a result set of movie.title’s and’s?

FROM movie LEFT JOIN director ON = director.movie_id

If there are no indices defined on any of the columns in the above two tables, which columns would you index to speed up the LEFT JOIN query?


How would you write a simple stored procedure in TSQL which takes a movie_id and returns all the directors associated with it?


CREATE procedure [dbo].getDirector (
@movie_id INT

SELECT name FROM directors WHERE movie_id = @movie_id


What are the advantages and disadvantages of using stored procedures versus calling SQL inline in Cold Fusion?

Stored procedures abstract database logic from server side code. They also offer performance benefits in pushing application logic to the database side.

The disadvantage is that if they are poorly written then they can hinder database performance and make development a little more obfuscated.

How would you format some text using css to be verdana and bold?

.myfontclass {
font-family: Verdana;
font-weight: bold;

What is the difference between absolute and relative div positioning?

Absolute is from the absolute 0,0 position in the top left corner of the browser window. Relative is relative from the positioning of where the div is declared within the html body.

How would you declare an inline css to format the table with a background color of “yellow” and give the table cell a right margin of 10 pixels?

table {
background-color: yellow;
td {
margin: 0 10px 0 0;

<td>Hello world</td>

ColdFusion Interview Questions - Part II
post info
By prayes
Categories: ColdFusion
Tags: ColdFusion

1. Which path is used in the template attribute in the tag?

A. physical path
B. calling template relative path
C. web document root relative path
D. any directory under Cfusion\CustomTags

The correct answer is B.

2. Which of the following would be the last one to capture an exception?

B. <CFERROR TYPE=”Request”>
C. <CFERROR TYPE=”Exception”>
D. site-wide error handler specified in the ColdFusion Administrator

The correct answer is D.

3. Of these tags with errors, which could NOT be caught with a block?

A. <CFSET X = 5 / 0>
B. <CFEST X = 5 / 0>
C. <CFSET X = “Y” + 1>
D. <CFINCLUDE TEMPLATE=”file.cfm”> where file.cfm is NOT found

The correct answer is B.

4. If you have the following variable definition in the Application.cfm file, what is the scope of the variable after it is created?

<CFSET x = “foo”>

A. Variables (local)
B. Application
C. Session
D. Request

The correct answer is A.

5. What is the purpose of the GetAuthUser() function?

A. To log in a specified user
B. To return the name of a logged in user who is requesting the page on which the function is used
C. To retrieve user details from a specified data source
D. To assign roles to the user who is requesting the page on which the function is used

The correct answer is B.

6. Which of the following variable types requires the use of the scope when referencing the variable? (Choose two)

A. request
B. form
C. local
D. application

The correct answer is A and D.

7. Which function is necessary when using CACHEDWITHIN attribute with the <CFQUERY> tag?

A. CreateDateTime()
B. ParseDateTime()
C. CreateTimeSpan()

The correct answer is C.

8. What is missing from the following <CFQUERY> tag’s SELECT statement if you want to return the count?

SELECT Count(*)
FROM TestTable

A. SELECT Count(CountVar)
B. SELECT Count(*) AS CountVar
C. SELECT Count(*) INTO CountVar

The correct answer is B.

9. Which of the following ANSI standard WHERE clauses will return all rows where City begins with the letter ‘S’?

B. WHERE City = ‘S*’

The correct answer is D.

10. Which one of the following tags is used for server-side validation? (Choose one.)

A. input type =”text”
B. input type=”hidden”
C. input value=”hidden”
D. input value=”text”

The correct answer is B.

11. When will the cookie created by the following tag expire?

<CFCOOKIE name=”bgcolor” value= “bgcolor”>

A. never
B. after one day
C. when the last browser window is closed
D. after the timeout period for session variables has elapsed

The correct answer is C.

1: What exactly is ColdFusion?
ColdFusion is actually two things, it is an application server and it is also a language. Most ColdFusion developers do not distinguish the two – they install the ColdFusion application server and use the ColdFusion language (called CFML for ColdFusion Markup Language) to write applications that run on that server. But ColdFusion the language can also be used on top of other application servers, J2EE application servers, providing an alternate and simplified scripting syntax for those high-end servers. Either way, the CFML language is used to create powerful applications quickly and easily, applications that run on the ColdFusion application server, or on an application server of your choice.

2: How old is ColdFusion?
ColdFusion is the original Web application server (even predating that term); it was created in 1995 making it the most mature product in the space.

3: How many organizations use ColdFusion?
ColdFusion is used by over 10,000 organizations worldwide and runs on over 125,000 servers.

4: How many developers use ColdFusion?
Conservative estimates put the number of ColdFusion developers at approximately 350,000. In reality this number is likely much higher as ColdFusion is sold per server and there is no limit to the number of developers who could use the same server.

5: How successful has ColdFusion been relative to other application servers?
Very. ColdFusion is the leading commercial (as in paid for) application server, and is second only to ASP in published pages. ColdFusion is used by over 75% of the Fortune 100.

6: What types of applications are built using ColdFusion?
While ColdFusion is used for all kinds of applications, including dynamic web sites, e-commerce sites, and portals, the significant majority of ColdFusion applications are Intranet and data reporting applications. This has always been one of ColdFusion's key strengths, and continues to be so.

7: Why do I not see more public ColdFusion driven sites?
Actually, there are lots of public ColdFusion sites out there. But, as Intranets and reporting is where ColdFusion tends to be most used the majority of ColdFusion powered applications are behind firewalls and on corporate networks. These can skew the perception of usage and page counts. For an idea of who is using ColdFusion see the lists on as well as

8: Why do companies buy ColdFusion when ASP and PHP are free?
Free is a bit of an overstatement. Yes, some core functionality may be available just by downloading software, but ColdFusion includes significant integrated services that are not included with other products. Major features like business graphing and full-text search, as well as small utility features like handling file uploads and reading and writing e-mail messages are not part of ASP and PHP and are included with ColdFusion. One recent estimate found that to add CF Professional functionality to ASP involved a raw cost of goods that topped $30,000. As such, ColdFusion Professional (for well under $1,000) is a real value. And that does not even take into account the cost savings of a simpler learning curve and shorter development cycle.

9: Isn't ColdFusion proprietary, and isn't using proprietary software dangerous?
No, ColdFusion is not proprietary. In fact, there are several other products (from other vendors) that have implemented CFML (or parts of it). In addition, ColdFusion leverages all open and public standards for everything from database integration (JDBC, ODBC) to configuration files (XML) to underlying architecture (J2EE). In fact, some might argue that ColdFusion and CFML are less proprietary than ASP and PHP (which are not supported by third party servers) and even Java itself (there is no licensing program or fee required to be ColdFusion compatible).

10: What is CFML?
CFML is the ColdFusion Markup Language, a tag based programming language designed specifically for writing Web and Internet based applications. CFML looks more like HTML than it does traditional programming languages, and this makes the language easy to learn and use (no more difficult than HTML). CFML is supported by ColdFusion as well as by some third party servers.

11: I have heard it argued that CFML is not a real programming language. Is this the case?
You can write real programs in CFML, that makes it a real programming language. Having said that, CFML has taken some heat for not looking like traditional programming languages (it is primarily tag based, not script based). There are several important points to keep in mind here: 1) CFML was designed to mimic HTML because it is HTML (and its inherent simplicity) that made the Web successful; rather than retrofitting existing languages to be Web centric (think Perl) CFML was built from the ground up for this space. 2) ColdFusion does indeed support scripting for programmatic tasks (flow control, conditional processing, etc.) via and more recently server-side ActionScript. 3) CFML is a very powerful programming language and is made up of about 100 tags and over 200 functions that perform all common programmatic operations and many not so common ones too (LDAP interaction, XML abstractions, COM and CORBA support, graphing and full text searching, and more). 4) It is somewhat ironic that for 5 years CFML was criticized for being tag based, and then comes ASP.NET featuring tag abstractions, and JSP which is essentially tag wrappers around Java code, and even XML which is nothing more than tag based data sharing. Looks like CFML had it right all along.

12: What are .CFM and .CFC files?
CFML code is saved in files with either a .CFM or a .CFC extension. .CFM files are standard ColdFusion files and may be plain files, included files, or Custom Tags. .CFC files are ColdFusion Components (reusable ColdFusion objects).

13: Isn't ColdFusion a low-end and entry-level solution?
Only if you want it to be. ColdFusion is a tool, what you do with the tool is up to you. Sure, lots of entry-level solutions have been built with ColdFusion – after all, for beginners ColdFusion is the easiest product and technology to learn. But unlike many easy-to-learn tools, ColdFusion allows users to expand their use to much more advanced applications. In addition to the many basic applications, many high-end and mission critical applications have been built with ColdFusion too. ColdFusion is no more "low-end" than a hammer is "a tool to build only small houses" – it's not the tool, it's how you use it.

14: Doesn't ColdFusion encourage poor programming practices?
No, not at all. ColdFusion provides all the necessary building blocks to create highly scalable, structured, manageable, and maintainable code. ColdFusion does not enforce any particular development methodology or structure – this is deliberate and by design as ColdFusion's emphasis is on getting the job done. Many developers do in fact start off by writing code that is less than ideal, and then learn and grow with the product. The fact of the matter is that not every application need be n-tier, implemented using model-view controllers, or built using design patterns. However, all of these are supported (especially via ColdFusion Components) and should be used when needed. In other words, you'll not outgrow ColdFusion – use it as suits you best and then keep getting better.

15: I have no programming experience. Is ColdFusion for me?
Absolutely. You'll need to learn some HTML and SQL, but Dreamweaver MX can even help with those too. Unlike other programming languages, you'll find yourself productive in ColdFusion in hours (not days or weeks or months).

16: I am an experienced developer and use C and/or Java, why should I use ColdFusion?
C and Java are great low-level programming languages, and are ideally suited for heavy-lifting and back-end processing. But you'd never want to generate HTML output or interact with form submissions using those languages. It would be way too much work and with no real value or upside. Rather, you should use a combination of ColdFusion with those languages and tier your development. Let ColdFusion handle the presentation layer and all web integration, and use your C or Java code for the back-end. It's the ideal solution.

17: I am a Flash user. Why should I use ColdFusion?
As a Flash user you already understand the importance of creating rich and engaging user experiences. Flash is often used for animation, intros, advertisements, and special effects, but Flash can do a whole lot more too. Flash can also be used as a front end for Internet based applications, and ColdFusion is ideally suited to be the back-end powering your Flash applications. ColdFusion and Flash are designed to talk to each other allowing you to build client-server type applications easily and effectively – Flash as the client and ColdFusion as the server.

18: My company has standardized on the J2EE platform. Doesn't this preclude the use of ColdFusion?
On the contrary. Your company has made a strategic decision to builds its IT infrastructure on an incredibly powerful facilitating technology, one that is steadily growing in popularity. J2EE (the Java platform) provides the architecture and the building blocks needed to build reliable, robust, and scalable applications. But all that power comes with a price (and not just the cost of software) – J2EE development is complex and beyond the scope of most members of most organizations. And even for experienced Java developers, not all tasks need be (or even should be) written in low-level Java. ColdFusion MX can sit on top of J2EE implementations, leveraging the underlying architecture and investment, while making its power accessible to all. Or put another way, ColdFusion MX delivers the power of underlying J2EE to those to whom it would have been inaccessible, and along the way makes accomplished Java developers far more productive. Not only does a move to J2EE not preclude the use of ColdFusion, it actually makes ColdFusion a logical choice for you – you've already made a massive investment (both financially and resource-wise), with just a little more money that investment can actually become usable by all.

19: As ColdFusion MX is built on underlying Java technology, is Microsoft and Windows support going to be discontinued?
The significant majority of ColdFusion installations run on Windows and use Microsoft back-ends (SQL Server, for example). There are no plans whatsoever to drop support for our most used platform, and with new support for .NET services ColdFusion has stronger Windows support than ever before. At the same time, ColdFusion also supports non-Microsoft platforms like Linux, Solaris, and HP-UX and non-Microsoft databases like Oracle, DB2 and mySQL – making it one of the most flexible products on the market.

20: Active communities are important to the success of any technology. Does ColdFusion have a strong and involved user community? Comments
ColdFusion has always had strong community ties, and the direction and growth of product has always been very community driven. There are numerous discussion lists, forums, publications, user groups, events (both Macromedia events and independent events) and an entire third-party publishing industry too.

21: Is Macromedia committed to ColdFusion?
Definitely. In fact, the latest version of ColdFusion (the first built entirely by Macromedia) was built by the largest product development team ever with the greatest budget and resource allocation of any ColdFusion to date. That alone is testament to Macromedia's commitment to ColdFusion and the ColdFusion community.


1: What do I need to start writing ColdFusion? Comments
You need two things: 1) a ColdFusion server to run your applications, you may either use an ISP who offers ColdFusion hosting or install your own server, and you may even install a local copy of ColdFusion for development at no cost whatsoever. 2) You also need an editing environment. Your best bet is to use Dreamweaver MX, but any text editor may be used.

2: Realistically, what skills do I need to be productive using ColdFusion?
You should be familiar with web and internet basics, and you should know the basics of using HTML to build web pages. You also need a good working knowledge of SQL. Armed with these you'll find yourself productive with ColdFusion in no time.

3: Which version of ColdFusion should I install to get started?
If you want to experiment with ColdFusion, your best bet is to use the Developer Edition (it even has an integrated Web server to help you get up and running quickly and easily). However, you cannot deploy applications using the Developer Edition - you'll need a full version of ColdFusion, and you have two choices: ColdFusion MX Standard is the entry-level version of ColdFusion, or ColdFusion MX Enterprise (which can be installed standalone or as a Java application on top of a J2EE server).

4: Where can I obtain a copy of ColdFusion?
ColdFusion can be bought from Macromedia directly at and from resellers (information at that same URL). You can also download a trial version by going to The trial version is the full product and will run for 30 days from the time of installation. After 30 days it reverts to a Developer Edition which may be used for ongoing development.

5: What is the ColdFusion Developer Edition?
ColdFusion Developer Edition is a non-expiring version of ColdFusion that is freely available to ColdFusion developers. It is the full ColdFusion Enterprise product but limited in that it will only process local requests as well as requests from one other IP address. As such, it is useful for development only (you can test pages on the server hosting ColdFusion and from one other machine). Applications created with the free Developer Edition may be deployed on full versions of ColdFusion. The Developer Edition is actually the full Enterprise product, at install time you'll be able to select an option that activates it as a Developer Edition (instead of having to provide a license number). The Developer Edition is also included with the Macromedia MX Studio.

6: What are the primary differences between ColdFusion Standard and ColdFusion Enterprise?
ColdFusion Enterprise runs on more platforms and supports more databases than does ColdFusion Standard, and also includes a full copy of JRun, supports the creation of multiple ColdFusion instances, features high performance mail delivery, and more. Sites that require high availability and greater performance should consider using the Enterprise edition. The complete feature comparison chart is at

7: Is ColdFusion available for Mac OSX?
A Developer Edition of ColdFusion MX for J2EE is available for Mac OSX. It requires that a J2EE server (like JRun or Tomcat) be installed, and ColdFusion will run on top of it. At this time there is no production version of ColdFusion for OSX.

8: Where can I find a hosting company that offers ColdFusion hosting?
The most complete ColdFusion ISP list is at

9: Where can I find books on ColdFusion?
Start at, the "ColdFusion Web Application Construction Kit" is the book used by most ColdFusion developers. If you need a quick introduction to SQL take a look at "Sams Teach Yourself SQL in 10 Minutes".

10: I need a class to help me get started. Where can I find out about ColdFusion training? Comments
If you are just starting with ColdFusion you may want to take Macromedia's "Fast Track to ColdFusion" class - a 3 day introduction to ColdFusion. Information about this class (and other classes on ColdFusion, Flash, Dreamweaver, and more) is at

11: What methodology should I use for my ColdFusion development? Comments
That's a tough one. There is no right or wrong methodology, nor is there a preferred methodology. The only real wrong is writing applications without a methodology, be it a formal one or one of your own. The most popular ColdFusion framework and methodology is the independent initiative Fusebox (, and many ColdFusion developers are now paying attention to Mach-II (


Thursday, June 12, 2008

HTML Screen Scraping using C# .Net WebClient

What is Screen Scraping ?

Screen Scraping means reading the contents of a web page. Suppose you go to, what you see is the interface which includes buttons, links, images etc. What we don't see is the target url of the links, the name of the images, the method used by the button which can be POST or GET. In other words we don't see the HTML behind the pages. Screen Scraping pulls the HTML of the web page. This HTML includes every HTML tag that is used to make up the page.
Why use screen scraping ?

The question that comes to our mind is why do we ever want the HTML of any web page. Screen Scraping does not stop only on pulling out the HTML but displaying it also. In other words you can pull out the HTML from any web page and display that web page on your page. It can be used as frames. But the good thing about screen scraping is that it is supported by all browsers and frames unfortunately are not.

Also sometimes you go to a website which has many links which says image1, image2, image3 and so on. In order to see those images you have to click on the image and it will enlarge in the parent or the new window. By using screen scraping you can pull all the images from a particular web page and display them on your own page.

Displaying a web page on your own page using Screen Scraping :

Lets see a small code snippet which you can use to display any page on your own page. First make a small interface as I have made below. As you can see the interface is quite simple. It has a button which says "Display WebPages below" and the web page trust me or not will be displayed in place of label. All the code will be written for the Button Click event. Below you can see the "Button Click Code".

C# Button Click Code :
private void Button1_Click(object sender, System.EventArgs e)
WebClient webClient = new WebClient();
const string strUrl = "";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
lblWebpage.Text = objUTF8.GetString(reqHTML);

Explanation of the Code Snippet in C#:

As you can see the code is few lines long. This is because has a very strong set of class libraries that makes the task easier for the developer. If you were trying to achieve the same result from classic Asp you might have to write a lot more code, I guess that's good for all the coders out there in the programming world.

In the first line I made an object of the WebClient class. The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

In the next line we just defined a private string variable strUrl which holds the url of the web page we wish to use in our example.

Then we declared a byte array reqHTML which will hold the bytes transferred from the web page.

Next line downloads the data in the form of bytes and put them in the reqHTML byte array.

The UTF8Encoding class represents the UTF-8 encoding of Unicode characters.

And in the next line we use the UTF8Encoding class method GetString to get the bytes as a string representation and finally we binds the result to the label.

This code now gets the homepage when the label is bound with the HTML of the yahoo page. The whole yahoo page is displayed.
The Generated HTML :

For those curious people who want to see that HTML was generated when the request was made. You can easily view the HTML by just viewing the source code of the yahoo page. In our internet explorer go to View -> Source. The notepad will open with the complete HTML generated of the page. Lets see a small screen shot of the HTML generated when we visit As you can see the HTML generated is quite complex. Wouldn't it be really cool if you can extract out all the links from the generated source. Lets try to do that :)
Extracting Urls :

The first thing you need to extract all the Urls from the web page is the regular expression. I am not saying you cannot do this without regular expression you can but it will be much harder.
Regular Expression for Extracting Urls :

First you need to introduce System.Text.RegularExpressions. Next you need to make a regular expression that can extract all urls from the generated HTML. There are many regular expressions already made for you which you can view at . Your regular expression would like this:

Regex r = new Regex("href\\s*=\\s*(?:(?:\\\"(?[^\\\"]*)\\\")|(?[^\\s]* ))");

This just says that extract everything from the web page source which starts with "href\\"
User Interface in Visual Studio .Net:

I am keeping user interface pretty simple. It consist of a textbox, datagrid and button. The datagrid will be used to display all the extracted urls.

Here is a screen shot of the User Interface.

The Code:

Okay the code is implemented in the button click event. But before that lets see the important declarations. You also need to include the following namespaces:



System.IO // If you plan to write in a file
// creates a button protected System.Web.UI.WebControls.Button Button1; // creates a byte array private byte[] aRequestHTML; // creates a string private string myString = null; // creates a datagrid protected System.Web.UI.WebControls.DataGrid DataGrid1; // creates a textbox protected System.Web.UI.WebControls.TextBox TextBox1; // creates the label protected System.Web.UI.WebControls.Label Label1; // creates the arraylist private ArrayList a = new ArrayList();

Okay now lets see some button click code that does the actual work.
private void Button1_Click(object sender, System.EventArgs e)
// make an object of the WebClient class
WebClient objWebClient = new WebClient();
// gets the HTML from the url written in the textbox
aRequestHTML = objWebClient.DownloadData(TextBox1.Text);
// creates UTf8 encoding object
UTF8Encoding utf8 = new UTF8Encoding();
// gets the UTF8 encoding of all the html we got in aRequestHTML
myString = utf8.GetString(aRequestHTML);
// this is a regular expression to check for the urls
Regex r = new Regex("href\\s*=\\s*(?:(?:\\\"(?[^\\\"]*)\\\")|(?[^\\s]* ))");
// get all the matches depending upon the regular expression
MatchCollection mcl = r.Matches(myString);

foreach(Match ml in mcl)
foreach(Group g in ml.Groups)
string b = g.Value + "
// Add the extracted urls to the array list

// assign arraylist to the datasource
DataGrid1.DataSource = a;
// binds the databind

// The following lines of code writes the extracted Urls to the file named test.txt
StreamWriter sw = new StreamWriter(Server.MapPath("test.txt"));
The MatchCollection mc1 has all the extracted urls and you can iterate through the collection to get all of them. Once you enter the url in the textbox and press the button the datagrid will be populated with the extracted urls. Here is a screen shot of the datagrid. The screen shot only shows few urls extracted there are at least 50 of them.
Final Note:

As you see that its simple to extract urls from any web page. You can also make the Column in the datagrid a hyperlink column so you can browse the extracted url.