Welcome to the amazing dot net programming

Author: Vijaya Kumar



Get updates by e-mail

HP Computer Museum





free website submission search engine seo optimization


Powered by Blogger

October 14, 2006

Microsoft Makes Vista Licensing Tougher On Users

New licensing restrictions on retail versions of Vista say users can only transfer licenses between PCs once.

By Gregg Keizer TechWeb

Microsoft has released licenses for the Windows Vista operating system that dramatically differ from those for Windows XP in that they limit the number of times that retail editions can be transferred to another device.

The new licenses, which were highlighted by the Vista team on its official blog Tuesday, add new restrictions to how and where Windows can be used.

"The first user of the software may reassign the license to another device one time. If you reassign the license, that other device becomes the "licensed device," reads the license for Windows Vista Home Basic, Home Premium, Ultimate, and Business. In other words, once a retail copy of Vista is installed on a PC, it can be moved to another system only once.

The new policy is narrower than Windows XP's. In the same section, the license for Windows XP Home states: "You may move the Software to a different Workstation Computer. After the transfer, you must completely remove the Software from the former Workstation Computer." There is no limit to the number of times users can make this move. Windows XP Professional's license is identical.

Although the Vista team's blog did not point out these changes, it did highlight others. "Two notable changes between Windows Vista license terms and those for Windows XP are: 1) failure of a validation check results in the loss of access to specific features; and 2) an increase in our warranty period from 90 days to 1 year, which brings Windows in line with most other Microsoft products," wrote Vista program manager Nick White.

Specifically, the Vista license calls out the ramifications of a failed validation check of Vista.

"The software will from time to time validate the software, update or require download of the validation feature of the software," it reads. "If after a validation check, the software is found not to be properly licensed, the functionality of the software may be affected."

Vista's new anti-piracy technologies, collectively dubbed "Software Protection Platform," have met with skepticism by analysts and criticism by users. Under the new program, a copy of Vista that's judged to be in violation of its license, or is counterfeit, is disabled after a set period, leaving the user access only to the default Web browser, and then only for an hour at a time.

Google Launches Search Service For Computer Code

By: Eric Auchard

Google Inc. is introducing a new search service that only a geek could love.

The Web search leader said late on Wednesday it is introducing Google Code Search, a site that simplifies how software developers search for programming code to improve existing software or create new programs.

Google product manager Tom Stocky said the Mountain View, California-based company is set to help programmers sift through billions of lines of computer source code using its familiar search box to uncover snippets of reusable software.

"For a long time it has been sort of an unsolved problem," said Stocky, a product manager in the developer products group. "It is hard to find references to this sort of data."

Google is applying the same machine-driven techniques it uses to help consumers search the Web for text, images, video and books to help professional programmers as well as computer enthusiasts overcome stumbling blocks to writing code.

Searchers can seek out specific programming terms or computer languages and dive deep into compressed code to locate specific features. Users also can narrow a search to find software code based on specific licensing requirements, which is a big deal in warding off future patent litigation.

Similar to how a consumer might type a few words into a standard Google search box for answers, programmers can seek out relevant lines of code at http://google.com/codesearch -- except the results are for machine-readable phrases such as "go{2}gle" "hello,\ world" or "^int printk."

No Secret Code

It's commonplace, when looking to improve a particular line of software, for most code writers to search the Web for quick tips. But finding actual programming code rather than just discussions about a particular coding problem is tough.

To meet this need, sites such as Koder, O'Reilly Labs or ProgrammingIsHard.com have sprung up that offer repositories of code. Most are small, require membership and are often devoted to only a specific class of software or problem.

Some programmers say Google Code Search answers some of the nightmares of building software, by creating a central place to trawl for publicly available code.

"(Google Code Search) may come in handy when looking for different ways of approaching a particular programming problem," said Niall Kennedy, a San Francisco technical blog commentator.

Others were less impressed: "Functional and simple, but therein lies the problem," said the writer of a site called "Digital Alchemy," who sees few advantages over existing sites.

Google searches through code repositories that are popular among programmers -- CollabNet's Subversion and another alternative called CVS, Stocky said.

The service began as a way for Google programmers to search through internal company code. It added a search of publicly available code and recently Google decided it might as well open up the service to others.

Google Code Search is in test mode on Google's Labs site.

Initially, Google Code Search is free of advertising. Should the site prove popular, Stocky said Google may consider running pay-per-click advertising along search results, the way it makes money from its more mainstream search services, he said.

SQL Server FAQ

What is Normalization?
Normalization is the process of designing a data model to efficiently store data in a database. The end result is that redundant data is eliminated, and only data related to the attribute is stored within the table.

What does normalization have to do with SQL Server?
To be honest, the answer here is nothing. SQL Server, like any other RDBMS, couldn't care less whether your data model follows any of the normal forms. You could create one table and store all of your data in one table or you can create a lot of little, unrelated tables to store your data. SQL Server will support whatever you decide to do. The only limiting factor you might face is the maximum number of columns SQL Server supports for a table.

SQL Server does not force or enforce any rules that require you to create a database in any of the normal forms. You are able to mix and match any of the rules you need, but it is a good idea to try to normalize your database as much as possible when you are designing it. People tend to spend a lot of time up front creating a normalized data model, but as soon as new columns or tables need to be added, they forget about the initial effort that was devoted to creating a nice clean model.

Advantages of normalization

1. Smaller database: By eliminating duplicate data, you will be able to reduce the overall size of the database.
2. Better performance:

  • Narrow tables: Having more fine-tuned tables allows your tables to have less columns and allows you to fit more records per data page.
  • Fewer indexes per table mean faster maintenance tasks such as index rebuilds.
  • Only join tables that you need.

Disadvantages of normalization

1. More tables to join: By spreading out your data into more tables, you increase the need to join tables.
2. Tables contain codes instead of real data: Repeated data is stored as codes rather than meaningful data. Therefore, there is always a need to go to the lookup table for the value.
3. Data model is difficult to query against: The data model is optimized for applications, not for ad hoc querying.

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow
NULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8).

In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.

What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction.

Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable
Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn).What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What's the maximum size of a row?
8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'.

What is lock escalation?
Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

What are constraints? Explain different types of constraints.
Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.


Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same time, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

Write a SQL Query to find first Week Day of month?

How to find 6th highest salary from Employee table
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee ORDER BY salary DESC) a ORDER BY salary

What is sorting and what is the difference between sorting and clustered indexes?
The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table.

i have triggers, views , functions , stored Procedures for a table, when i am dropping that table what are the objects deleted?
view, trigger gets deleted

Triggers and views are associated with a table where as functions and procedures are not

In a database we can able to create more than one primary key is it possible indirectly?

after creating one primary key, the other 2 fields are unique key with not null constraint

how many number of databases can be there in a single server

What is a traditional Network Library for SQL Servers?
Named Pipes

What is a default TCP/IP socket assigned for SQL Server?

What is a stored procedure?
Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.

Can we use Truncate command on a table which is referenced by FOREIGN KEY?
No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.

What command do we use to rename a db?
sp_renamedb 'oldname' , 'newname'

When do you use SQL Profiler?
SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..

What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.

What are the authentication modes in SQL Server?
Windows mode and mixed mode (SQL & Windows).

Where do you think the users names and passwords will be stored in sql server?
They get stored in master db in the sysxlogins table.

What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.

What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored
procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer.

What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable
SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the
web server etc.

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

What is blocking and how would you troubleshoot it?
Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Explain CREATE DATABASE syntax
Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command:


But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal confuguration mode.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs.

What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added,
changed, or removed (that is, if the distribution of key values has
changed), or the table has been truncated using the TRUNCATE TABLE
statement and then repopulated
3) Database is upgraded from a previous version

What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:
* Snapshot replication
* Transactional replication (with immediate updating subscribers, with queued updating subscribers)
* Merge replication

How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed.

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors.

Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.

Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax:

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by__expression]
[HAVING search_condition]
[ORDER BY order__expression [ASC DESC] ]

What is a join and explain different types of joins.
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.


Can you have a nested transaction?
Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure.

What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(),

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also.

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this mplementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a self join? Explain it with an example.
Self join is just like any other join, except that two instances of the same table will be joined in the query.

Here is an example:
Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

empid int,
mgrid int,
empname char(10)
INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager] FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager] FROM emp t1 LEFT OUTER JOIN
emp t2
t1.mgrid = t2.empid

Be a Better Computer Caretaker

You spent good money on your PC. You might as well take good care of it, too.
By Oliver Rist for MSN Tech & Gadgets

Whether your machine is the $500 Sunday driver from Dell or multi-thousand dollar screamer, you have a vested interest in keeping it in top condition. Here's how the big guys do it.

Get your operating system on CD and create those recovery disks
Most Windows PCs are sold without giving you the Windows operating system on a disk-unless you request it, either from the manufacturer or Microsoft. Make the effort and get that disk, either by contacting Microsoft support after the sale or (considerably more convenient) making sure the seller gives it to you with the purchase.

Many PC-makers include a small "recovery disk" application that makes it even easier to reinstall a system. The difference between a Windows operating CD and a recovery CD is that the Windows CD simply reinstalls the operating system. That's it. A recovery CD is configured to reinstall not just Windows, but all the current hardware drivers in your system as well as specific custom applications. If your computer has a recovery disk app, use it. Typically the kick-off application to create the recovery CDs either comes up every now and then when you reboot the system or it's located off the Start >> Programs menu where it will be located under the heading of the manufacturer's name (Dell, Gateway, etc.).

Do a backup
I know, it's a yawner, but that doesn't mean it isn't necessary. Just go through one bad crash and you'll find out just how necessary backups are. Besides, creating them only takes a few mouse clicks and even fewer minutes. My favorite backup option for home computers is an external USB hard drive. They can go for about $200 for a 200GB version like the Maxtor OneTouch II. And because they're USB 2.0-compatible they simply plug into your XP machine and work. (The backup software is often embedded on the device so you may not even need to even install it; just access it straight off the hard disk.)

All you've got to do is follow the quick-start guide and choose the folders you want backed up. After that, the disk will take care of creating backups either on a schedule or whenever you press the backup button. It really doesn't get much more convenient than that.

"I do so much work on a notebook that goes everywhere with me," says Paul Lindo, a management exec and good friend. "With all the wear and tear on my notebook I crash them pretty often. Just being able to press a button the night before a trip and know I've got a full backup in case anything goes wrong is worth the price of the disk by itself. The fact that it's saved my bacon twice already is gravy."

Run your disk defragmenter

Like everything else, hard disks get sloppier the more they're used. Data becomes spread out over wider areas on the disk and accessing it gets slower and slower. You can buy third-party disk optimizers that work faster, but Windows includes its own that gets the job done. Just head over to Start >> All Programs >> Accessories >> System Tools and click Disk Defragmenter. When the program pops up, highlight the "C:" drive and hit Defragment. Then walk away because this will take a while. But the down time will be worth it in improved disk performance and reliability. I do this about once every three months.

Next: Uninterruptible power supply, don't plug in without one

Remember these three words: uninterruptible power supply
Don't plug your PC in without one. An uninterruptible power supply (or UPS) boils down to a surge suppressor with a battery. By storing a few minutes of power in a battery, a UPS allows you to shut down your PCs and peripherals in an orderly manner in the case of a power outage-instead of losing power suddenly, which tends to have a bad effect on delicate circuit boards. "Reboots, especially, sudden unexpected ones take a big toll on PC circuitry," says James Chang, a full-time desktop and systems administrator in New York City. As power consumption rises nationwide, so do blackouts and brownouts. Plugging your PC directly into the wall means many unnecessary reboots plus power spikes, and surges could damage the computer's long-term circuit life and even cause a fatal short. A UPS has a surge suppressor built-in to shield a PC from this kind of electronic havoc.

"I've seen PCs that were bought at the same time-from the same batch even-after two years with some plugged into UPSes and some just plugged into the wall," continues Chang. "The wall jobs were practically dead."

For home users, a UPS can cost between $40 and $150 depending on what features you want. Besides a battery, other whiz-bangs include surge protection for broadband modems (cable or DSL) and USB devices. UPS sometimes come with software that will do an orderly shutdown automatically if it senses the primary power has gone down. Me? I like the APC Back-UPS ES 725, which handles a lot of equipment (450-watt load; basically, two power strips worth of hardware into a single UPS) and also has broadband coverage. It sells for about $90 at CompUSA. Yes, it costs a bit more, but drop the Benjamin Franklin and smile. You're probably saving your PC at least a few months worth of extra life.

Don't cold reboot
A "cold" reboot refers to powering a PC all the way down so that it requires pushing the power key to get running again. This is bad for much the same reason as an unexpected reboot-it's tough on the circuitry. Cold reboots may be unavoidable, but that doesn't mean you should go looking for them. Set your PC to go into standby and subsequently hibernate mode after 30 minutes or more of inactivity by accessing the power options icon under the Windows XP Control Panel. To do this, go to Start >> Control Panel >> Power Options. There's a wizard screen here that lets you set individual power down thresholds with just a couple of mouse clicks. Some notebooks may have proprietary power management utilities that supersede the ones built into Windows, but they'll have similar wizard-style screens.

However, cold reboots are not bad for displays. Your monitor's overall life is actually increased by turning the thing off every night. So set let your PC sleep and your printer go into nap mode, but hit that power button on your monitor every night.

Watch the environment
No, that's not the Brazilian rainforest, it's the air around your PC. Computer cases have air vents, so dusty areas tend to fill your computer with that dust over time. That means it's a good idea to keep your work area as clean as possible.

Then open your PC once every couple of months and clean out the accumulated detritus. Buy a can of compressed air at any computer or electronics store-it only cost a couple of dollars-and gently blow the dust away with a few strategic gusts. Most home cases today have a couple of thumbscrews on the back that require no tools. Unscrew them and you can simply slide the case open, do your compressed air thing and slide it closed again. Keep the can at least six inches away from any circuitry. While you're at it, clean your keyboard and monitor with a few puffs. Stick with compressed air, as liquid is just as bad for your keyboard and display as for your motherboard.

For displays, you might try some of those eyeglass lens wipes you get at the optician; the kind that are pre-moisturized with glass cleaner. Don't do this too often, however, just once or twice a year. The rest of the time a few good compressed air puffs will do you nicely.

Take care of your peripherals
Most everyone uses optical mice these days, but if you're still using an old-fashioned mouse, a ball-actuated one, don't ignore that little sphere or its tiny sensors. Pop the bottom of the mouse open and swab both the ball and the sensors with rubbing alcohol applied with a Q-Tip.

Your disk drives also see a lot of use. Not much you can do for your hard disk aside from running a defragger, but your CD and DVD disk drives can be helped by investing in cleaning disc. They're usually less than $10 at most electronics stores, and they can improve your drives' overall life by up to 25 percent.

October 13, 2006

HP Computer Museum

Welcome to the HP Computer Museum 25 Years of Innovation (1966 to 1991)

What And Why

The HP Computer Museum is a collection of old Hewlett-Packard computer hardware, software, documentation and other marketing materials from HP's early years in the computer industry (beginning in 1966). The Museum is privately funded and owned by Wordsong Communications Pty. Ltd. The museum is not a commercial enterprise; it's a resource and discussion forum for enthusiasts. The museum is housed in a 2500 square-foot building (shed, really) in Melbourne, Australia. The museum is not open to the public, but is viewable by appointment. Please contact us if you would like to visit the museum.

The museum's long-term goal is to have working models of all computers and peripherals produced by Hewlett-Packard during the company's first 25 years in the industry (1966 to 1991). The early stages of museum development have focussed on products that had the most "human interaction". These include desktop computers, terminals and peripherals that people used in their daily working lives. The museum also contains some interesting examples of HP computer technology from the post-1991 period. The museum does not include any HP instruments.

The period of greatest innovation in any industry occurs during the birth and early growth periods. This is true of the computer industry and of HP's involvement in the industry. HP is one of only two major "survivors" in the computer hardware industry, the other being IBM. It is interesting to track HP's progress in the industry and to speculate as to why HP survived into middle age when almost all others failed. From a historical perspective, HP is most notable for its pioneering company culture "The HP Way".

The Museum Web Site:
The museum's web site will be continuously updated as more material is added. The initial development of the web site has focussed on posting as much material as possible. More educational content and commentary will follow. All photographs and original text are copyright Wordsong Communications Pty. Ltd. We have reserved copyright on our photographs primarily to prevent possible misrepresentations in the "internet world". The web has a very active market for second hand computers, and we would hate to see our pictures used to misrepresent an auction, for example. In most cases, we are happy to approve the use of our photographs. Please contact us first. If you spot an inaccuracy in our content or have any suggestions on how we might improve our site, please contact us.

Test Driven Development with Visual Studio 2005

Test Driven Development (TDD) is not a new concept. In fact, the idea of test-first, code-second has been around for many years. In the latest release of Microsoft's premier developer tool, Visual Studio 2005 Team System many new features have been added, including features for testing software. What does this mean to you, the serious developer? It means you now have integrated unit testing that can be leveraged for Test Driven Development.

What is Test Driven Development?

I like to think of TDD as a means to design software by first documenting the requirements in a language a programmer understands, and then writing the code to fulfill the requirements. In his book Test-Driven Development: By Example (Addison-Wesley), Kent Beck defined TDD with two simple rules:

1) Never write a single line of code unless you have a failing automated test.
2) Eliminate duplication.

Kent's rules and my idea of TDD go hand-in-hand. In most typical software development cycles, a product owner or project manager will provide a set of requirements; typically the requirements are in a Word document titled "Functional Specification." Word documents are great for conveying a story, but what we really need to do is translate the story told by the project manager into a programming language - think of this as a new requirements document written in C# (or Visual Basic). The requirements are written in code as tests; each test representing a single requirement. In addition, when we get to writing the functional code (a little later) we want to ensure we eliminate any duplicate code by centralizing code that is needed in more than one place.

Types of Tests

Every time I start talking to people about software tests their mind seems to go immediately to thinking about a test to ensure the application works as expected. This is certainly important, and it can be broken into two parts.

  • Programmer Tests

Automated tests written by the programmer prior to writing the functional code. The functional code is written to do no more and no less than pass the test. These are also know as unit tests.
  • Customer Tests

Tests written by a test engineer to validate the functionality of the application from the customer perspective. These are also known as acceptance tests.

For the remainder of this article I will be talking solely about Programmer Tests, which, even though they include the word "test," are the responsibility of the programmer.

No Less, No More

In the definition of Programmer Tests, I mentioned that the functional code should do no more and no less that what the programmer test indicates. This is a lot more difficult than it sounds. It is a natural tendency, especially for programmers, to attempt to foresee the future. How many times while writing code have to included a "feature" because you know that eventually it would be requested. Perhaps you wrote a method to get customer order summaries, even though that was not part of the current specification. Certainly this would be needed soon.

This is the trap we have to avoid. Albert Einstein once said, "Any fool can make things bigger, more complex, and more violent. It takes a touch of genius — and a lot of courage — to move in the opposite direction." In other words, truly brilliant code includes on the code necessary to execute the requirements, and no more. The functional code should pass all of its programmer tests, communicate its purpose clearly, and contain the smallest number of classes and methods possible. When the code does all of these things it is done. Step away from the keyboard. Resist the urge to add more.

That's Great, But How Does It All Work?

As a programmer committed to using TDD well, the first thing you need to do is document the functional requirements as programmer tests. Do this before any functional code is written. Start by creating a Test List. Describe all of the tests that define the requirements, and ensure this list is the most complete definition of the requirements criteria. Ensure the Test List is as simple as it can be while conversely ensuring all of the requirements are documented.

For example, let's say as part of our application we need to create an object to represent a Product. The Test List may look something like this:

1) Create a Product and verify IsDirty is false.
2) Create a Product, change the Product Name, and verify IsDirty is true.
3) Create a Product, change the Product Name, verify the ProductName is changed.
4) Create a Product, change the Product Name, save the Product, verify the Product was saved.

This is a simplified version of a Test List, and depending on the requirements there may not be much more to document.


Red/Green/Refactor is the TDD mantra, and it describes the three states you go through when writing code using TDD methods.

-- Write a failing test.
-- Write the code to satisfy the test.
-- Improve the code without changing its functionality.

Alternately you could say, "Make it fail. Make it work. Make it better."

October 12, 2006

Javascript FAQ

Here i added the Javascript faq which i got some other resources, as a developer i know the importance of javascript in web development. Hope this faq would be helpful.

Q. What is JavaScript?
A. JavaScript is a scripting language designed for adding interactivity to HTML pages. JavaScript is an interpreted language. This means that scripts execute without preliminary compilation, i.e. without conversion of the script text into a system-dependent machine code. The user's browser interprets the script, that is, analyzes and immediately executes it.

Thus, most Internet users today have browsers that support JavaScript. That's why JavaScript is one of the most popular tools for adding interactive features to Web pages.

Q: How do I insert comments in JavaScript code?
A: JavaScript supports three different types of comments:

1. Multiple-line C-style comments. Everything between /* and */ is a comment,
for example:
/* This is a comment */
/* C-style comments can span
as many lines as you like,
as shown in this example */

2. One-line comments of C++ style. These comments begin with // and continue up to the next line break:
// This is a one-line comment

3. One-line comments with the HTML comment-opening sequence (<!--). Note that the JavaScript interpreter ignores the closing characters of HTML comments (-->). Consider this example:
<!-- This is treated as a one-line JS comment
<!-- It works just like a comment beginning with //
<!-- --> This is also a one-line JS comment
<!-- --> because JS ignores the closing characters
<!-- --> of HTML-style comments

Q: How do I hide JS code from old browsers that do not support JavaScript?
A: To prevent old browsers from displaying your JS code, do the following:

1) Immediately after the opening <script> tag, put a one-line HTML-style comment without the closing characters, so that the first two lines of your script would look like this:
<script language="JavaScript">

2) At the end of your script, put the following two lines:

Thus, your HTML file will contain the following fragment:
<script language="JavaScript">
<!--Here you put your JS code.
Old browsers will treat it
as an HTML comment.//-->

Q: If the user's browser cannot execute JavaScript code, can I display a warning for the user?
A: Yes, you can display a special warning for users of JavaScript-incapable browsers. Put your warning text between the tags <NOSCRIPT> and </NOSCRIPT>.
Here's an example:

<H3>This page uses JavaScript</H3>
<ul><li>Please use Netscape Navigator 3+ or Internet Explorer 3+
<li>Make sure that JavaScript is enabled in your browser.

JavaScript-enabled browsers will ignore everything between <NOSCRIPT> and </NOSCRIPT>. Browsers that cannot execute JavaScript will display your message on the page.

Q: Can I include JavaScript code from external JS files, rather than embedding all my scripts within HTML pages?
Answer: Yes. To do so, create a new file with the extension .js, for example, myscript.js. Put your JavaScript code in this file; do not include opening and closing SCRIPT tags in the .js file!

To embed myscript.js into your Web page, use these tags in your HTML file:

<SCRIPT LANGUAGE="JavaScript" SRC="myscript.js"></SCRIPT>

Q: Can I make a button on my page work as the browser's Back button?
A: To create your own Back button, use this code

<form><input type=button value="Back" onCLick="history.back()"> </form>

Q: Can I make a button on my page work as the browser's Forward button?
A: To create your own Forward button, use this code

<form><input type=button value="Forward" onCLick="history.forward()" ></form>

If your browser's Forward button is currently inactive, then the Forward button on your page won't work either. This is the case when the current page is the last page in your browsing history.

Q: Can I pass parameters from one my page to another?
Answer: Yes, you can pass a parameter to another page in several different ways:

by storing the parameter in a cookie
by storing the parameter in a variable of another window or frame
by storing the parameter in the rewritable property top.name (the browser window name)
by appending the parameter to the destination page's URL as a query string

Q: How do I convert strings to numbers in JavaScript?
Answer: To convert a string to a number, use the JavaScript function parseFloat (for conversion to a floating-point number) or parseInt (for conversion to an integer).

parseFloat syntax: parseFloat('string')

Q: Is there a way to test whether a particular variable holds a number or a string?
Answer: Yes. To test whether the variable holds a number or a string, use the typeof operator. If your variable holds a number, typeof(variable) will return "number". If it holds a string, typeof(variable) will return "string". The following are examples of typeof usage:

typeof(123) // result: "number"
typeof("123") // result: "string"

if (typeof k == "string") { alert('k is a string.') }
if (typeof k == "number") { alert('k is a number.') }

Q: How do I generate random numbers in JavaScript?
Answer: To generate random floating-point numbers in the range from 0 to 1, use the Math.random() method:

num = Math.random() // num is random, from 0 to 1

If you need random floating-point numbers in the range from A to B, use this code:
num = A + (B-A)*Math.random() // num is random, from A to B

Q: How do I extract a substring from a string?
Answer: To extract a substring from a string, use the substring method:


string - is the string from which you want to extract a substring.
start - is the number specifying the position of the character at which the substring begins. (The character at start itself will be included in the substring.)
end - is the number specifying the position of the character at which the substring ends. (The character at end will not be included in the substring.)

Note that the first character in the string corresponds to position 0, and the last character to position string.length-1.


'Hello'.substring(0,2) // 'He'
'Hello'.substring(0,4) // 'Hell'

Q: Can I play a sound file without using JavaScript?
A: Yes, you can play a sound by specifying the sound file's URL as a hyperlink destination, for example, <A HREF="mySound.mid">

Q: How do I set a background sound on a Web page?
A: In all audio-enabled browsers, you can use the EMBED tag to play a background sound. For example, if you want to play the file bkground.mid right after the browser loads the page, you can use the following EMBED tag:


To stop the background sound,call the cross-browser method document.bkgroundID.stop() .

If your target browser is Microsoft Internet Explorer (for example, in an intranet), then you can use the Explorer-specific BGSOUND tag:

<BGSOUND ID="bkgroundID" LOOP=0 VOLUME="-600" SRC="bkground.mid">

Here, again, bkground.mid stands for the name of the sound file that you actually want to play.

Q: How do I generate a user prompt from JavaScript?
A: To generate a user prompt, use the prompt() method:

prompt('Prompt text','Suggested input')

use the following code:

<form name=myform>
<input type=button value="Try it now" onClick="f=prompt('Enter your name','Name');alert('Hello '+f+'!')" > </form>

Q: What value does prompt() return if the user clicked the Cancel button?
A: The return value of canceled prompt() depends on the browser. In some browsers the return value is null, in others it's '' (empty string). Therefore, you might want to use the following code when calling the prompt() method:

userInput = prompt('Prompt text','Suggested input');
if (userInput != '' && userInput != null) {
// do something with the input

Q: How do I disable a radio button in a form (making it not selectable)?
A: To make a radio button not selectable, in the button's INPUT tag you can use an onClick event handler like this:

<INPUT type="radio" name="myButton" value="theValue" onClick="this.checked=false; alert('Sorry, this option is not available!')">

Q: How do I change an image when the user's mouse points at it?
A: Here is a simple example:
Point at this folder, and it will open. Move the mouse away, and the folder will close.

In this example, the image is 2.gif; the image is 1.gif. Both files are stored in the ../hi-icons directory. In order to create the "mouseover" effect, the <IMG> tag is embedded in a hyperlink that has onMouseOver and onMouseOut event handlers:

<a href="#any_URL" onMouseOver="handleOver(); return true;" onMouseOut="handleOut(); return true;" >
<img name=imgName width=17 height=15 border=0 alt="This image changes when you point at it!" src="../hi-icons/2.gif"></a>

In the <HEAD> section of the page, we have JavaScript code that preloads the image files and defines the event handler functions:
<script language="JavaScript">
if (document.images) {
img_on =new Image(); img_on.src ="../hi-icons/1.gif";
img_off=new Image(); img_off.src="../hi-icons/2.gif";

function handleOver() {
if (document.images) document.imgName.src=img_on.src;

function handleOut() {
if (document.images) document.imgName.src=img_off.src;


Q: How do I check whether the user clicked the left or right mouse button?
A: The click event occurs for the left mouse button only. Therefore, onClick event handlers do not need to preform the left-versus-right button test.

On the other hand, the mousedown and mouseup events may occur for any mouse button. To determine whether the user clicked the left or right button, you can use the following event properties:

event.which in Netscape Navigator
event.button in Internet Explorer

If the value of these properties is 1, the event occurred for the left button. In the following example, the onMouseDown event handler displays the messages Left button or Right button, depending on the mouse button you actually have clicked. The messages will appear on your browser's status bar. Click or right-click anywhere on this page to see it work:

<script language="JavaScript">
function mouseDown(e) {
if (parseInt(navigator.appVersion)<3) {
var clickType=1;
if (navigator.appName=="Netscape") clickType=e.which;
else clickType=event.button;
if (clickType==1) self.status='Left button!';
if (clickType!=1) self.status='Right button!';
return true;
if (parseInt(navigator.appVersion)<3) {
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")

Q: Can I disable the Windows context menu that normally shows up when the user clicks the right mouse button?
A: In most modern browsers, you can disable the context menu by using the oncontextmenu event handler in the body tag of your page:

<body oncontextmenu="return false;">

Q: Can I disable the right-click context menu for a particular image, while still enabling the menu for all other parts of my page?
Answer: Yes. In most modern browsers you can disable the right-click menu for a particular image. To do so, you can use the event handler oncontextmenu="return false;" within the IMG tag that defines your image:

<IMG border=0 src="..." oncontextmenu="return false;">

Q: How do I determine the week day for a given date?
A: To determine the week day for a given date, you set this date in a Date() object, and then get the week day using the Date.getDay() method:

d=new Date();


if (ww==0) wDay="Sunday";
if (ww==1) wDay="Monday";
if (ww==2) wDay="Tuesday";
if (ww==3) wDay="Wednesday";
if (ww==4) wDay="Thursday";
if (ww==5) wDay="Friday";
if (ww==6) wDay="Saturday";

Q: How can I show a different image each day?
we can display a different image for each day of the week:

<script language="JavaScript">
var today = new Date();
var number = today.getDay() + 1;
document.write('<img src="images/' + number + '.jpg"'+'>');

This creates a date object and then gets the number of the day of the week, and then uses that to display the relevant image.

If you have more than 7 images then you'll need to alter this, either using the day of the month or the day of the year, or maybe even the day of the millennium!

Q: How do I display a random banner image?
A:There is an existing JavaScript method that returns a random number:

//Returns a random number between 0 and 1
function getRandom() {
return Math.random()

In Netscape Navigator 2 this only works on Unix platforms, so you might want to try the following instead:

rnd.today=new Date();

function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);

function rand(number) {
return Math.ceil(rnd()*number);

// end central randomizer. -->

To create a random number between 1 and 10 use rand(10). To display an random image named banner1.gif to banner10.gif use:

Q: How do I disable the "Back" button of a browser?

Easy answer - you can't.

Longer answer - you cannot totally remove the ability for the user to go back to the previous location, although you can make it harder.

1) You can use the location replace method when changing the location. This replaces the current history location with the new location. However older browsers do not support this method, which is why it is required to test for the images object:

<script language="JavaScript">
if (document.images)
location.href = 'apage.html';

Note: in Opera replace() will work, but only with absolute URL's.

2) You can load the new location into another window, and then close the old window:

In the first page:

<script langauge="JavaScript">
function newWindow(fileName,windowName) {

<a href="javascript:newWindow('1.html','window1')">Open Window</a>

In the next window:

<script language="JavaScript">
function newWindow(fileName,windowName)
{ msgWindow=window.open(fileName,windowName); }

function replaceURL(fileName) { newWindow(fileName,'window2'); self.close();

<a href="javascript:replaceURL('2.html')">change location</a>

3) You can open a window without a toolbar:

<script language="JavaScript">

However, this does not totally stop the user from being able to go back to the previous page.

4) You can add code to the previous page to force the browser to go forwards again:

Q: What's the difference between Java and JavaScript and why should I prevent my browser from executing JavaScript?
JavaScript is an OO type interpreted language that runs on the clients browser, enabling interaction between the user and the document, without the need to always go back to the server for processing. for example to validate form input. There is no reason why you would want to stop JavaScript from executing on your browser, unless yet another security hole is found in the browser that allows data to be captured by a third party. All the *known* security holes have been plugged.

Java is a byte compiled language that is a fully fledged OO language. It again runs on the clients browser. It can do things that JavaScript cannot do, like reading a file on the same server that the document was served from (I believe this is correct). It can do graphcs. I'm not too sure if there are valid reasons why you would not want to allow Java to execute on your browser, other than that Java applets can be quite big and can take a while to download. The initial loading of Java in the browser can take quite a few seconds to start up.

Q: Is there a way to close a window without that confirm message?
The only way to avoid the message appearing is when you close a window that only has one location in its history. Most visitors to a site will have many locations in their current history.

If you are creating a window that you then want to close later on without the message occurring, then make sure that you use the JavaScript replace() method when changing the location within that window, that way you will not create new entries within that windows history object.

To use the replace method without causing errors on browsers that don't support it you'll need to do the following:

<script language="JavaScript">
function go(url) {
if (document.images)
location.href = url;

And then for all your links in that window:

<a href="javascript:go('http://somewhere.com/nextpage.html')">Next Page</a>

Make sure you use the absolute URL, because in some versions of Opera, an absolute reference will cause problems when used with the replace() method.

Note that for browsers that don't support the replace method (the same as those that don't support the image object) the window will build up entries in the history object.

Q: How can I disable the "View Source" menu item?
Sorry, not possible.

Q: How can I calculate the number of days elapsed between two dates?

<script language="JavaScript">
function y2k(number) {
return (number < 1000) ? number + 1900 :
number; }

function daysElapsed(date1,date2) {
var difference = Date.UTC(y2k(date1.getYear()), date1.getMonth(),date1.getDate(),0,0,0) - Date.UTC(y2k(date2.getYear()), date2.getMonth(),date2.getDate(),0,0,0);

return difference/1000/60/60/24;}

document.write(daysElapsed(new Date(2000,0,1), new Date(1999,11,31)));

Q: How do you subtract X hours from a date?

The following subtracts five hours from the current date and time:

<SCRIPT LANGUAGE = 'JavaScript'>
function y2k(number) {
return (number < 1000) ? number + 1900 : number;

var date = new Date();
var date = new Date(Date.UTC(y2k(date.getYear()), date.getMonth(),date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) - 5*60*60*1000);

Q: How can I calculate the difference between two dates?
<script language="JavaScript">
function timeDifference(laterdate,earlierdate) {
var difference = laterdate.getTime() - earlierdate.getTime();
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);

document.write('difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ' + secondsDifference + ' second/s ');}

var laterdate = new Date(2000,0,1); // 1st January 2000
var earlierdate = new Date(1998,2,13); // 13th March 1998

Q: How can I calculate the number of days in the current month?
The following little gem was provided by Paul Bennett. At first look it looks too simple, but on closer investigation it is a pretty clever piece of code:

function days_in_month (year, month) {
return 32 - new Date(year, month, 32).getDate();

Q: How can I convert a text string: "Wed Aug 26 14:40:45 MET DST 1998." into a Date object?
The date foramt has to be altered to:

Wed, 26 Aug 1998 14:40:45So:

<script language="JavaScript">
var textdate = 'Wed Aug 26 14:40:45 MET DST 1998.';
var myArray = textdate.split(' ');
var input = myArray[0] + ', ' + myArray[2] + ' ' + myArray[1] + ' ' + myArray[3] + ' ' + myArray[6].substring(0,4);
var output = Date.parse(input);
var mydate = new Date(output)

Q: How can I convert a mm/dd/yy date to dd/mm/yy and vice versa?

<script language="JavaScript">
var mmddyy = "12/31/99";
var mm = mmddyy.substring(0,2);
var dd = mmddyy.substring(3,5);
var yy = mmddyy.substring(6,8);
var ddmmyy = dd + '/' + mm + '/' + yy;

// and back again...

var dd = ddmmyy.substring(0,2);
var mm = ddmmyy.substring(3,5);
var yy = ddmmyy.substring(6,8);
mmddyy = mm + '/' + dd + '/' + yy;

Q: How do I add a number of days to a date?
<script language="JavaScript">
function addDays(myDate,days) {
return new Date(myDate.getTime() + days*24*60*60*1000);
alert(addDays(new Date(),10));

Q: How can I cancel the users F5 request to refresh the page in Internet Explorer?

Do it by redirecting the keyboard action on another keycode that you can control (backspace in this example):

function cancelRefresh() {
// keycode for F5 function
if (window.event && window.event.keyCode == 116) {
window.event.keyCode = 8;
// keycode for backspace
if (window.event && window.event.keyCode == 8) {
// try to cancel the backspace
window.event.cancelBubble = true;
window.event.returnValue = false;
return false; }}

This function is called on the onKeyDown event and it seems to work!

Q: When creating a form, how can I check to see if data entered in a text field contains all numerics?

<script language="JavaScript">
function validate(string) {
if (!string) return false;
var Chars = "0123456789";
for (var i = 0; i < string.length; i++) {
if (Chars.indexOf(string.charAt(i)) == -1)
return false;
return true;

<input type="text" onChange="if (!validate(this.value)) alert('Not Valid')">

Q: How do I get a word count of the text in a textarea?

<script language="JavaScript">
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words return a.length;

<form name="myForm">
<textarea name="myText" rows="3" cols="40">

This is some sample text. There is punctuation (sprinkled)about, plus some line-separators. The answer should be 19.
<input type="button" value="Word Count" onClick="alert(wordcount(this.form.myText.value))">

Q: How can I stop a user from hitting the Submit button twice?

<form onSubmit="if (this.submitted) return false; this.submitted = true; return true">
<input type="submit">

Q: there a way to restrict number of characters within a textarea?

<form> <textarea onKeyUp="if (this.value.length > 100) { alert('100 chars max'); this.value = this.value.substring(0,99); }"></textarea> </form>

Q: When a page reloads (due to the user pressing back) how do I clear a form of all the user entered data?

Simply invoke the form's reset method, immediately after defining the form, for example:

<form name="myForm">
<input type="text">

<script language="JavaScript">

Q: How can I extract just the extension file name from a forms file upload field?

<script language="JavaScript">
function getExtension(value) {
return value.substring(value.lastIndexOf('.') + 1,value.length);
<input name="myFile" type="file">
<input type="button" value="Extract" onClick="alert(getExtension(this.form.myFile.value))">

Q: How can I check where a visitor has come from?

<script language="JavaScript">
if (document.referrer != '')
document.write('You came from: ' + document.referrer);

Q: How can you make a .wav play when you click on an image?

You should use the <EMBED> tag.

The following will play the midi or wav file as soon as its loaded on a Java enabled browser:

The following allows you control when it plays:

<script language="JavaScript">
function playSound() {
function pauseSound() {
function stopSound() {
<a href="javascript:playSound()">
<img src="play.gif" width="100" hight="100">
<a href="javascript:pauseSound()">
<img src="pause.gif" width="100" hight="100">
<a href="javascript:stopSound()">
<img src="stop.gif" width="100" hight="100">
<embed src="sound.wav" hidden=true autostart=false loop=false name="firstSound" mastersound></body>

You can replace sound.wav with sound.mid.

Q: When I open a new window, how can I change the contents of the original window from the new window?

Within the original window:

<script language="JavaScript">
function newWindow(file,window) {
if (msgWindow.opener == null) msgWindow.opener = self;

<input type="button" value="Open New Window" onClick="newWindow('a.html','window2')">

Within the new window:

<script language="JavaScript">
function load(file,target) {
if (target != '')
target.window.location.href = file;
window.location.href = file;

<a href="javascript:load('b.html',top.opener)">load document into opener</a>
<a href="javascript:load('b.html','')">load document</a>

Q: How do I open a window at a given position on the screen?
In Netscape Navigator 4 the screenX and screenY attributes were introduced. In Internet Explorer 4 the top and left attributes were introduced. By combining the two both Netscape Navigator 4 and Internet Explorer 4 will allow you to position the window:

<script language="JavaScript">
function openWindow() {
msgWindow = window.open('','newWin','width=100, height=100, screenX=400, screenY=400, top=400, left=400'); msgWindow.location.href = 'apage.html';}

<input type="button" onClick="openWindow()" value="Click Me">

Q: Is it possible to close the parent window (main web browser window) from a child window?

Put the following in the child:

<script langauge="JavaScript">

Although you'll need to make sure that the opener has been defined for browsers that don't have it by default, by placing the following in the parent:

<script language="JavaScript">
msgWindow.location.href ='apage.html';
if (msgWindow.opener == null) msgWindow.opener = self;

Note, that this will likely prompt the user for confirmation before closing the window.

Q: How can I close a popup window after, say, 5 seconds?


Q: How do you return the results from a query into a new window?

<FORM ACTION="apage.html" TARGET="newwindow">

Q: Is it possible to disallow a pop-up window to be maximized?

When opening a window use the attribute resizable:


The code does not work in Internet Explorer - you can maximise the window, and the resizable=no is ignored once you restore the size.

Q: Can i get Javascript counter?

JavaScript CAN NOT do a Web page counter alone. You will have to use a CGI script, or Java as well. The reason for this is that JavaScript can not write to external files, something necessary to run a counter (updating hit count).

Q: How do i clear the user's cache?
There are several things that can't be done with JavaScript for security reasons, including such things as changing user preferences or clearing the cache.

However, I do have a slick workaround that prevents a page from being stored in the user's cache. (You don't have to clear the cache if the page isn't in the cache!) Anyways, on with it. The code to stick in the HEAD section of your page is this:

<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="Thu, 01 Dec 1994 120000 GMT">

Note: The second 'Expires' tag is not necessary for all browsers, but some browsers do use with the 'no-cache' tag, so it is best to just leave it in for good measure.

October 10, 2006

ASP.NET : Exporting Data to Excel

A common request of users is to be able to download data for use in Microsoft Excel. This is actually fairly easy to accomplish without a lot of extra work. I do most of my database work with DataTable objects, as I don't need the overhead of a DataSet. I also have a Database wrapper class that is able to easily retrieve data from a SQL Server database. Once I use my function to get my DataTable, I can start exporting the data. For this example, however, I'll use the traditional SqlDataAdapter method to retrieve the data initially.

There are a few tricks to making this work. First, you have to create an ASPX page with no HTML content in it. The only thing that should be in the ASPX page is the Page directive at the top. The second trick is to clear the existing content and send down a new content type. For Excel, you use a content type of application/vnd.ms-excel. This tells your Web browser to expect something that can be handled within Excel. The third trick is to send down the data tab-delimited per column and a newline at the end of each row. After that, Excel does the rest of the work for you.

Here's the code:

protected void Page_Load(object sender, EventArgs e)
SqlConnection cn = new SqlConnection("yourconnectionstring");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", cn);
DataTable dt = new DataTable();

Response.ContentType = "application/vnd.ms-excel";
string sep = "";
foreach (DataColumn dc in dt.Columns)
Response.Write(sep + dc.ColumnName);
sep = "\t";

int i;
foreach (DataRow dr in dt.Rows)
sep = "";
for (i = 0; i < dt.Columns.Count; i++)
Response.Write(sep + dr[i].ToString());
sep = "\t";


After I open my connection and retrieve my data, I clear the output buffer and send down a new content type, since the default type of text/HTML isn't appropriate in this case. I then loop through the columns and write out the column names, separated by tabs. At the end of the field list, I send down a newline character.

I then loop through the rows of the table and, within each row, loop through the fields. Each field value is printed out in its default format under the appropriate column header. If you have data types, such as Booleans, that should be printed in a different format, you can look at the dt.Columns collection to help determine which data type each field is and use an appropriate conversion function.

The result of running this page is a prompt to open or save the Excel spreadsheet. You can use this code with any query and any database connection. Once you've got the content cleared and the content type set, Excel does the hard work of formatting for you.

Introducing Serialization in .NET


Serialization is the concept whereby an object is written into a linear stream. The .NET Framework provides an excellant support to serializing and deserializing objects. This article discusses Serialization, XML, SOAP and Binary and provides code examples to illustrate the concepts explained.

Article Contents:

What is Serialization and De-serialization?
Advantages and Disadvantages of Serialization
The Serializable Attribute
Types of Serialization
Advantages and Disadvantages of Binary Serialization
SOAP Serialization
XML Serialization
Advantages of XML Serialization
Working with Formatters
Custom Serialization
Points to remember


Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. De-serialization is the reverse; it is the process of reconstructing the same object later. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another. In this article I will discuss .NET's support for Serialization and how we can build a class that supports custom serialization.

What is Serialization and De-serialization?

Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes. The object can be persisted to a file, database or even in the memory. The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media.
Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to implement serialization in .NET, we basically require a stream and a formatter. While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.
The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization. Refer to the figure below.

Figure 1

The above figure illustrates that the serialized object is independent of the storage media, i.e., it can be a database, a file or even the main memory of the system.

Advantages and Disadvantages of Serialization

The following are the basic advantages of serialization:
· Facilitate the transportation of an object through a network
· Create a clone of an object
The primary disadvantage of serialization can be attributed to the resource overhead (both the CPU and the IO devices) that is involved in serializing and de-serializing the data and the latency issues that are involved for transmitting the data over the network. Further, serialization is quite slow. Moreover, XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes. Therefore, it compels the developer to allow the class to be accessed to the outside world.

The Serializable Attribute

In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute. However, the private and public members of a class are always serialized by default. The SerializationAttribute is only used for the binary serialization. The code snippet below shows the usage of SerializableAttribute.

public class Employee
public int empCode;
public string empName;
Note the Serializable attribute that is specified at the beginning of the class in the code listing above. The SerializableAttribute is useful for situations where the object has to be transported to other application domains. It needs to be applied even irrespective of whether the class implements the ISerializable interface. If this attribute is not set in that case, then when we try to serialize an object the CLR throws a SerializationException.

Types of Serialization

Serialization can be of the following types:
· Binary Serialization
· SOAP Serialization
· XML Serialization
· Custom Serialization
All these types of serialization are explained in details in the sections that follow.

Binary Serialization

Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media. A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved. Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object. The following code listing shows how we can implement binary serialization.

Listing 2:
public void BinarySerialize(string filename, Employee emp)
FileStream fileStreamObject;
fileStreamObject = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, emp);

The following code listing shows how we can implement binary de-serialization.

Listing 3:
public static object BinaryDeserialize(string filename)
FileStream fileStreamObject;

fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));

Advantages and Disadvantages of Binary Serialization

One of the major advantages of using Binary Serialization in the managed environment is that the object can be de-serialized from the same data you serialized it to. Besides, the other advantage of Binary Serialization is enhanced performance as it is faster and even more powerful in the sense that it provides support for complex objects, read only properties and even circular references. However, the downside to this is that it is not easily portable to another platform.

SOAP Serialization

The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. The following code listing shows how we can implement serialization using the SOAP protocol.

Listing 4:
public void SOAPSerialize(string filename,Employee employeeObject)
FileStream fileStreamObject = new FileStream(filename, FileMode.Create);
SoapFormatter soapFormatter = new SoapFormatter();
soapFormatter.Serialize(fileStreamObject, employeeObject);

The following code listing shows how we can implement de-serialization using the SOAP protocol.

Listing 5:
public static object SOAPDeserialize(string filename)
FileStream fileStreamObject = new FileStream(filename, FileMode.Open);
SoapFormatter soapFormatter = new SoapFormatter();
object obj = (object)soapFormatter.Deserialize(fileStreamObject);
return obj;

XML Serialization

According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple. The basic class that we need to use is the XmlSerializer for both serialization and de-serialization. The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class. XML Serialization is however, much slower compared to Binary serialization. We can set a property as an XML attribute as shown in the code listing below.

Listing 6:
public string EmpName
return empName;
empName = value;

The following code listing shows how we can implement XML serialization.

Listing 7:
public void XMLSerialize(Employee emp, String filename)
XmlSerializer serializer = null;
FileStream stream = null;
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
serializer.Serialize(stream, emp);
if (stream != null)

The following code listing shows how we can implement XML de-serialization.

Listing 8:
public static Employee XMLDeserialize(String filename)
XmlSerializer serializer = null;
FileStream stream = null;
Employee emp = new Employee();
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Open);
emp = (Employee)serializer.Deserialize(stream);
if (stream != null)
return emp;

Advantages of XML Serialization

The advantages of XML Serialization are as follows:
· XML based
· Support for cross platforms
· Easily readable and editable

Working with Formatters

A formatter is used to determine the serialization format for objects. In other words, it is used to control the serialization of an object to and from a stream. They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network. They expose an interface called the IFormatter interface. IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization. There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter. Both these classes extend the IFormatter interface.

The Binary Formatter

The Binary formatter provides support for serialization using binary encoding. The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology. This class is not appropriate when the data is supposed to be transmitted through a firewall.

The SOAP Formatter

The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol. It is used to create a Soap envelop and it uses an object graph to generate the result. It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages. SOAP formatters in .NET are widely used by the Web Services.

Custom Serialization

In some cases, the default serialization techniques provided by .NET may not be sufficient in real life. This is when we require implementing custom serialization. It is possible to implement custom serialization in .NET by implementing the ISerializable interface. This interface allows an object to take control of its own serialization and de-serialization process. It gives us a great deal of flexibility in the way we can save and restore objects. The ISerializable interface consists of a single method, GetObjectData, which accepts two parameters.

The SerializationInfo class serves as the container for all the data we want to serialize. The AddValue method is called to add the objects we want to serialize to this container. The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process of de-serialization. The following code listing shows how we can implement Custom Serialization.

Listing 9:
public class Employee: ISerializable
private int empCode;
private string empName;
protected Employee(SerializationInfo serializationInfo, StreamingContext
this.empCode = serializationInfo.GetInt32("empCode");
this.empName = serializationInfo.GetString("empName");
public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
StreamingContext streamingContext)
serializationInfo.AddValue("empCode", this.empCode);
serializationInfo.AddValue("empName", this.empName);

The following listing shows how we can implement Custom Serialization on a Custom Collection class that extends the CollectionBase class of the System.Collections namespace.

Listing 10
public class EmployeeCollection: System.Collections.CollectionBase,
private int empCode;

public EmployeeCollection()
empCode = 1;

protected EmployeeCollection(SerializationInfo info, StreamingContext context)
: base(info, context)
empCode = info.GetInt32("empCode");

public virtual void GetObjectData(SerializationInfo info, StreamingContext
base.GetObjectData(info, context);
info.AddValue("empCode", empCode);

Points to remember

This section deals with some of the points that we have already covered in this article and some others that we have not, but are still very important and relate to the serialization and de-serialization concepts of .NET.

When you apply the Serializable custom attribute to a type, all instance fields of the class (public, private, protected, etc.) are serialized automatically.

XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface. The XmlSerializer class can only serialize the public properties of the class, whereas the BinaryFormatter class can serialize private fields using the ISerializable interface.
The Serializable attribute is a must for making a class serializable irrespective of whether we have implemented the ISerializable interface in this class. When we serialize a class, the objects of the references to other classes that are contained in this class are also serialized if they are marked as serializable. All members are serialized, including public, private or protected members. Furthermore, even circular references are supported by binary serialization. Note that read only properties are not serialized except the collection class objects. However, the read only properties can be serialized using binary serialization.

If we do not require serializing a particular property of a class when using an XmlSerializer, we have to mark the property with the custom attribute XmlIgnoreAttribute. When using a SoapFormatter we have to use the SoapIgnoreAttribute instead. The XmlSerializer generates an in-memory assembly optimized for each type since the initial invocation to a Web Service always takes so much time. To combat this, we can use the sgen.exe tool to pre-generate the serialization assembly.


Serialization is the process of storing an object, including all of its members, to a persistent or a non-persistent storage media by converting the object into a linear stream of data. De-serialization is the process of restoring an object's values from the said stream. The advantage of serialization is to save the state of an object in order to have the ability to recreate the same object at a later point of time if and when it is required. The .NET Framework provides a strong support for serialization of objects. The .NET Framework provides a unified standard for serializing and de-serializing objects for building distributed heterogeneous systems. This article has explored Serialization and De-serialization and the various types of Serialization concepts with code examples wherever necessary. It has discussed what Custom Serialization is and how to implement it. However, I would recommend not using serialization unless it is absolutely necessary due to the drawbacks that I have already explained in this article.

I hope that the readers will find this article quite useful and post their comments and suggestions on this article.

Happy reading!

Web dotnetlibrary.blogspot.com