Archive for April, 2010

Anybody can write code. With a few months of programming experience, you can write ‘working applications’. Making it work is easy, but doing it the right way requires more work, knowledge and experience. Believe it, majority of the programmers write ‘working code’, not ‘good code’. Writing ‘good code’ is an art and we all should learn and practice it. Some of the characteristics of good code are:

  1. Reliable
  2. Maintainable
  3. Efficient

Now i will tell some way to write your code with these characteristics.

Naming Conventions and Standards:

  1. Pascal casing for Class and Method names. Pascal casing means first character of all words are Upper Case and other characters are lower case. Example: “SaveProduct”.
  2. Camel casing for variables and method parameters. Camel casing means first character of all words, except the first word are Upper Case and other characters are lower case. Example: “totalCount”.
  3. Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity ).
  4. Use meaningful, descriptive words to name variables. Do not use abbreviations like “num” or single character variable names like “i”, “n”, “s” etc. Example: “number”.
  5. Do not use underscores (_) for local variable names.
  6. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.
  7. Prefix boolean variables, properties and methods with “is” or similar prefixes. Example: “isFinished”.

Indenting and Spacing:

  1. Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4.
  2. Curly braces ( {} ) should be in the same level as the code outside the braces.
  3. There should be one and only one single blank line between each method inside  the class.
  4. Use one blank line to separate logical groups of code.
  5. Use #region to group related pieces of code together.

Good Programming Practices:

  1. Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.
  2. Method name should tell what it does. Do not use mis-leading names. If the method name is obvious, there is no need of documentation explaining what the method does.
  3. A method should do only ‘one job’. Do not combine more than one job in a single method, even if those jobs are very small.
  4. Do not hardcode numbers. Use constants instead.
  5. Do not hardcode strings. Use resource files i.e.  a separate constant file.
  6. Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case.
  7. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never  assume that if one is not matching then the only possibility is the other value.
  8. Use String.Empty instead of “”.
  9. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.
  10. Error messages should help the user to solve the problem. Never give error messages like “Error in Application”, “There is an error” etc. Instead give specific messages like “Failed to update database. Please make sure the login id and password are correct.”
  11. Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.
  12. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.
  13. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure.
  14. If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block.
  15. Use StringBuilder class instead of String when you have to manipulate string objects in a loop.
  16. Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users.
  17. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.
  18. Use try-catch in your data layer to catch all database exceptions.

Read Full Post »

Recovering a Database

In my post named “Database Recovery Techniques”, I talked about performing different kinds of backups but the recovery process was only in theory. Now I will see show you how to restore a database in different recovery scenarios.

Retrieving Backup Information

Before you can start restoring databases, you need to know which backups you need to restore. SQL Server stores backup history about every single backup performed on databases in the msdb database. The msdb database can be queried to find the backups to restore.

Retrieving Simple Backup Information

1. To get information about which backups have occurred on the AdventureWorks database, execute the following SELECT statement:

USE msdb
SELECT backup_start_date,type, physical_device_name,backup_set_id
FROM backupset bs inner join backupmediafamily bm
ON bs.media_set_id = bm.media_set_id
WHERE database_name =’AdventureWorks’
ORDER BY backup_start_date desc

The results pane shown below indicates that the most recent backup was of backup type I, a differential backup. As you know, to restore a differential backup, you first need to restore the most recent full database backup. This backup can be found on line 2, with type D indicating a full database backup.

2. Every backup gets a unique id called a backup set id that can be seen in the results window, as shown below:

Using the above information, you can find out which data and log files were affected by the backup and what their original locations were.

Restoring a Database Using SQL Server Management Studio

In many cases, the easiest way to restore a database is to use SQL Server Management Studio. SQL Server Management Studio uses the backup history stored in the msdb database to show us the best way to restore a database.

Performing a Restore Using SQL Server Management Studio

1. To restore the database, open Object Explorer by selecting Object Explorer in the View menu or by pressing the F8 key.

2. In the tree view shown, expand your SQL Server instance, open the Databases folder and right-click the AdventureWorks database. In the context menu, select Tasks | Restore | Database.

3. The Restore Database dialog box opens and you will see that the most recent backup sets are already selected for restoration, as shown in the below figure. To complete the restore, simply click the OK button.

Note: Make sure no connections are open to AdventureWorks because no connections to the database are allowed while a restore is in progress.

4. A message box should appear to inform you that the restore was successful.

Read Full Post »

Preventing data loss is one of the most critical issues involved in managing database systems. Data can be lost as a result of many different problems:

  1. Hardware failures
  2. Viruses
  3. Incorrect use of UPDATE and DELETE statements
  4. Software bugs
  5. Disasters, such as fire or flood

To prevent data loss, you can implement a recovery strategy for your databases.

Full Database Backups

A very common backup strategy is to back up the whole database in a predefined time series (once each night, for instance). With such a backup strategy, it is possible to recover a database to the state it had when the last backup occurred. This strategy is implemented by using full database backups. A full database backup contains all data and database Meta information needed to restore the whole database, including full-text catalogs. When you restore a full database backup, it restores all database files yielding data in a consistent state from the time the backup completed.

Using Differential Backups

The main advantage of a full database backup is that it contains all the data needed to rebuild the entire database. But this advantage can also be a disadvantage. Consider a database where full database backups are performed each night. If you need to recover the database, you always have to use the backup from the previous night, resulting in the loss of a whole day’s work. One way to reduce the potential period of time that can be lost would be to perform full database backups more often. But this itself can be a problem. Because all data and parts of the transaction log are written to the backup device, it can be very time-intensive to make a backup. Also, you need a lot of storage space to hold these backups, and a full backup can decrease the performance of your database as a result of the large amount of I/O it requires. Wouldn’t it be better to perform one full database backup at night and only take backups of data changes made during the day? This sort of functionality is provided by the differential backup.

The differential backup stores only the data changes that have occurred since the last full database backup. When the same data has changed many times since the last full database backup, a differential backup stores the most recent version of the changed data. Because it contains all changes since the last full backup, to restore a differential backup, you first need to restore the last full database backup and then apply only the last differential backup.

Performing Differential Backups

Performing a differential backup is very similar to performing full database backups. The only difference is that you state in the WITH option of the backup that you want to perform a differential backup. The syntax of the BACKUP DATABASE statement to perform a differential backup of AdventureWorks to a physical device, overwriting other existing backups on the backup device, is as follows:

USE master;
TO DISK=’t:\adv_diff.bak’

Using Transaction Log Backups

With the combination of full database and differential backups, it is possible to take snapshots of the data and recover them. But in some situations, it is also desirable to have backups of all events that have occurred in a database, like a record of every single statement executed. With such functionality, it would be possible to recover the database to any state required. Transaction log backups provide this functionality. As its name suggests, the transaction log backup is a backup of transaction log entries and contains all transactions that have happened to the database. The main advantages of transaction log backups are as follows:

  1. Transaction log backups allow you to recover the database to a specific point in time.
  2. Because transaction log backups are backups of log entries, it is even possible to perform a backup from a transaction log if the data files are destroyed. With this backup, it is possible to recover the database up to the last transaction that took place before the failure occurred. Thus, in the event of a failure, not a single committed transaction need be lost.

Combining Transaction Log and Differential Backups

Another possible backup strategy is to combine full database, differential, and transaction log backups. This is done when restoring all transaction log backups would take too much time. Because restoring from a transaction log backup means that all transactions have to be executed again, it can take a great deal of time to recover all the data, especially in large databases. Differential backups only apply data changes, which can be done faster than re-executing all transactions.

To recover a database when you have a combined backup strategy, you need to restore the last full database backup, the last differential backup, and then all subsequent transaction log backups.

The Full Recovery Model

As mentioned before, you need to tell SQL Server in advance which backup strategy you plan to implement. If only full database and differential backups are used, the database has to be set to the simple recovery model. If you also want to use transaction log backups, the recovery model must be set to FULL (or BULK_LOGGED). The full recovery model tells SQL Server that you want to perform transaction log backups. To make this possible, SQL Server keeps all transactions in a transaction log until a transaction log backup occurs. When the transaction log backup happens, SQL Server truncates the transaction log after the backup is written to the backup device. In simple mode, the transaction log is truncated after every checkpoint, which means that committed transactions (which are already written to the data files) are deleted from the transaction log. Thus, in simple mode, transaction log backups cannot be created.

To set the recovery model to FULL, use the ALTER DATABASE statement again. The following code sets the recovery mode of AdventureWorks database to FULL:

USE master;

To set recovery model to SIMPLE, use the following command
USE master;

Read Full Post »

Sort List/IList by Linq

As an Asp.net developer i have to work with List/IList very often. Another common requirement is to sort the list. Previously we had to do the sorting in database level or if we want to do it in application level then we had to implement the IComparer class.

But the amazing thing is we don’t have to do either of these two to do the sorting in List/IList. We can do it by writing only one line code using Linq.

public class Employee
  public string FirstName {set; get;}
  public string LastName {set; get;}
  public DateTime DOB {set; get;}

public void Sort(ref List<Employee> list, string sortBy, string sortDirection)
  //Example data:
  //sortBy = “FirstName”
  //sortDirection = “ASC” or “DESC”

  if (sortBy == “FirstName”)
  var list = list.OrderBy(x => x.FirstName).toList();

Read Full Post »

As a Microsoft fan, Windows XP was one of the most amazing invention of this computer world to me. I used Windows XP for around 7 years and i was really happy with its performance. Then Microsoft came with Windows Vista. I started to use it then and there but was totally shocked to see such a problematic operating system. So i again went back to Windows XP.  Then when Microsoft came with Windows 7 at first i was in a confusion whether to move to Windows 7 or not. But later i do some research and found some amazing improvement in Windows 7.

I have found that the way windows service works, has been changed in windows 7. The common scenario is to run common windows services on startup. Normally this takes long booting time and shutdown time. Also the services which startup automatically may not be needed all the time. For example “Tablet PC Input Service”, this service starts automatically when computer starts but this is not needed if you don’t use tablet PC. So this type of services do nothing but take up computer processing power and memory and causes slow start up and shut down.

To get rid of this problem Microsoft Kernel team has got a new way of starting and stopping services. This is trigger based. So now in Windows 7 all the services do not start automatically rather starts by kernel when some kinds of trigger fires. For example the “Table PC Input Service” do not start on startup. But if some kind of tablet PC is attached then and there the kernel will identify that for this the “Tablet PC Input Service” needs to be started, and start the service. And whenever the tablet PC will be unplugged the service will be stopped by the service.

Another big problem we face always when an operating system up gradation takes place, we always have to think with the software and hardware compatibility issue. Lots of software were not ready to run in Windows Vista at first which were running in Windows XP. There is a solution for these kind of problems in Windows 7. That is Windows 7 -Windows XP mode. We can install Windows XP within Windows 7 as a virtual PC and can run all the software that we used to run in Windows Xp. USB port is also enabled for this virtual pc option. And its very easy to install. Just one drawback, your pc Ram should be good to run virtual pc smoothly.

Windows 7 has many more features like this. If i start writing about all of those then it will be a huge post. So i am stopping here. The good news is that you won’t have to spend long agonizing over the whole ‘XP or Vista?’ decision any more, because Windows 7 generally outdoes them both. Microsoft really does appear to have learned its hard-taught lessons and, while it hasn’t fixed everything, the latest incarnation of Windows does show significant improvements over its predecessor. Windows 7 is really better and it finally gives long-standing Windows XP fans a reason to upgrade.

Read Full Post »

iPad : What can I say!

Apple released their new product “iPad” on 3rd April 2010. According to me iPad is another revolutionary product of Apple. But to some people iPad has no use and they believe iPad will not be succeed at all. So if you will allow me, I would like to share some hopefully original thoughts on the iPad buzz. When I first saw the iPad, I was honestly skeptical. I kept waiting for Steve Jobs to talk about the new time travel app. But after further consideration, I’ve decided the iPad will be huge.

The iPhone was a huge product and generated excitement because it did things no phone or handheld had done before. Many people are disappointed that the iPad did not bring such novelty. As one of my friend commented, “This is great, but what am I going to use it for that I can’t already do?” This is the amazing point. Rather than introduce new uses, Apple has created the iPad as a new way of doing things we already do.

The iPad is not simply a large iPod Touch; performance reports and the new iWork apps indicate as much. But the iPad certainly lacks much of the flexibility and features in a laptop running OS X or Windows. It truly is a new type of device. If you’re technologically savvy, you may miss what I’m talking about. But if you’ve ever provided technical support to people who aren’t technologically savvy, you’ll realize how much people still struggle with the intricacies of desktop operating systems and applications. Navigating file systems, decrypting error messages, finding device drivers, configuring security software, managing program details, monitoring memory usage – PCs (and Macs) can be overwhelming for someone who just wants to send e-mails or look at photos.

Now enter the iPad. If anybody asks for my suggestion before buying a new computer i always ask them what are they gonna use it for. Except few occasion most of the time i get the answer, “Browsing the web, reading and sending email, enjoying photos, watching videos, listening to music, playing games, typing up a document every now and then etc.” Amazingly these are the exact words came from the “Apple Press Release” announcing the iPad. Many average consumers never task their computer’s powerful hardware with anything beyond these basic operations. The iPad can fill the same role with an intuitive and deceptively simple interface.



Here are some specification of iPad:

Height: 9.56 inches (242.8 mm)

Width: 7.47 inches (189.7 mm)

Depth: 0.5 inch (13.4 mm)

Weight: 1.5 pounds (0.68 kg) Wi-Fi model; 1.6 pounds (0.73 kg) Wi-Fi + 3G model

I believe this is only the beginning. The iPad is the first in this new category that mixes a simplified computer with an enhanced portable media player. I am convinced that Apple knows what they are doing once again, and that people will be intrigued by a device that lets them accomplish their basic technology goals without all the usual hassles. For many users, that really is magical.

Read Full Post »

Protect your Privacy

Now a days we all use computer and internet. But a very few of us sweep or clean up our computer hard drive or using track which should be done in a regular basis. There are lots of good reasons to clean up your computer’s hard drive and usage tracks. One of the most important reason is:

If a hacker ever gained access to your machine, some of your juiciest information is stored in your Web browsers cache. There is enough in almost every browser on earth to engineer a social breach. In other words a hacker could gain access to your personal data and then use it to pose as you.

Actually it is very difficult to keep all of your private information protected, given that it’s scattered all over your machine in places you’ve never even heard of. Like:

  1. Temporary Internet files, Web site cookies, browser history, and index.dat.
  2. Typed URL history.
  3. Saved passwords and form auto-complete information stored in your browser.
  4. Recent Documents.
  5. Usage history of: Start/Run, Search.
  6. Temporary directories on the hard drive.
  7. Items contained within the Windows Registry.
  8. Deleted items contents.
  9. Media player history.
  10. And many more…

Here’s what you can do about it. First, use one (or more) of the following tools to automatically erase all of the things on the list above. And by the way, all two of these offer Secure File Deletion, which makes the deletions unrecoverable:

  1. CCleaner
  2. Privacy Eraser

So one of these will do the hard work for you. According to me you should do these kind of cleaning very often (At least once in a month if more than that is not possible).

Read Full Post »

Older Posts »