Google voice search for PC

Google voice search for PC
After introducing a mobile app now Google has introduced the Search by voice feature for desktops as well. It’s easy to search out loud. All you need is Google Chrome and a built-in or attached microphone. To get started:
  1. Download and install Latest version of Google Chrome.
  2. Open Chrome and go to google.com.
  3. Just click the mic in the search bar and start talking.
Note:-
Right now Voice Search is available for Google Chrome and US English only.

Handy For

Hard-to-spell searches
Makes searching words you're not sure how to spell quicker and easier.


Searches that are just more fun to search out loud
Now you can ask your computer anything.

Longer searches
Search long queries, even longer queries, just by talking.

Searching without any typing
Use it in the kitchen, in the garage or anytime your hands might be full.

More Detail
Read more...

Countdown timer in javascript

In this programming tutorial you will learn how to develop the countdown timer in javascript. I have got the countdown timer code from internet but I have found lot of bugs in it during its testing process, after fixing those bugs I have decided to share it with you people. Following are the features of this countdown timer
  1. Cross browser compatibility.
  2. Doesn’t get unnecessary calls.
  3. Easy to implement.
  4. Work smoothly and perfectly.
Countdown timer in javascript
Just you have to do is to set a specific target date in the future, get the current date and then calculate the remaining time between them.

So let’s have a look over the example given below

Countdown timer in javascript

Countdown.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script> 
<script language="javascript" type="text/javascript">
function countdown(yr, m, d) {
            var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
            theyear = yr; themonth = m; theday = d
            var today = new Date()
            var todayy = today.getYear()
            if (todayy < 1000)
                todayy += 1900
            var todaym = today.getMonth()
            var todayd = today.getDate()
            var todayh = today.getHours()
            var todaymin = today.getMinutes()
            var todaysec = today.getSeconds()
            var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec
            futurestring = montharray[m - 1] + " " + d + ", " + yr
            dd = Date.parse(futurestring) - Date.parse(todaystring)
            dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1)
            dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1)
            dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1)
            dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1)
   if (dday == 0 && dhour == 0 && dmin == 0 && dsec == 1) {
   alert("12");
                document.getElementById('days1').innerHTML = "-";
                document.getElementById('days2').innerHTML = "-";
                document.getElementById('hrs1').innerHTML = "-";
                document.getElementById('hrs2').innerHTML = "-";
    document.getElementById('min1').innerHTML = "-";
                document.getElementById('min2').innerHTML = "-";
    document.getElementById('sec1').innerHTML = "-";
                document.getElementById('sec2').innerHTML = "-";
                return
            }
            else {
                if (dday > 0 || dhour > 0 || dmin > 0 || dsec > 0) 
    {//Some time remaining
                    if (dday <= 0) 
     {//If we have time of less than a day
                        document.getElementById('days1').innerHTML = "-";
                        document.getElementById('days2').innerHTML = "-";

                    }
                    if (dday > 0 && dday < 10) 
     {
                        //IF day is let's suppose 9
                        document.getElementById('days1').innerHTML = 0;
                        document.getElementById('days2').innerHTML = dday;
                    }
                    else 
     {
                        //IF day is let's suppose >=10
                        var numDays = new Number(dday);
                        numDays = numDays.toString();
                        if (numDays.length == 1) 
      {
                            document.getElementById('days1').innerHTML = 0;
                            document.getElementById('days2').innerHTML = numDays.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('days1').innerHTML = numDays.substring(0, 1);
                            document.getElementById('days2').innerHTML = numDays.substring(1, 2);
                        }
                    }
                    //Day region Ends Here

                    //Hour Region Starts Here
     if (dhour <= 0) 
     {
                        document.getElementById('hrs1').innerHTML = "-";
                        document.getElementById('hrs2').innerHTML = "-";

                    }
                    if (dhour > 0 && dhour < 10) 
     {
                        document.getElementById('hrs1').innerHTML = 0;
                        document.getElementById('hrs2').innerHTML = dhour;
                    }

                    else 
     {
                        var numHrs = new Number(dhour);
                        numHrs = numHrs.toString();
                        if (numHrs.length == 1) 
      {
                            document.getElementById('hrs1').innerHTML = 0;
                            document.getElementById('hrs2').innerHTML = numHrs.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('hrs1').innerHTML = numHrs.substring(0, 1);
                            document.getElementById('hrs2').innerHTML = numHrs.substring(1, 2);
                        }
                    }
     //Hour Region Ends Here
     
     //Minute Region Starts Here
     if (dmin <= 0) 
     {
                        document.getElementById('min1').innerHTML = "-";
                        document.getElementById('min2').innerHTML = "-";

                    }
                    if (dmin > 0 && dmin < 10) 
     {
                        document.getElementById('min1').innerHTML = 0;
                        document.getElementById('min2').innerHTML = dmin;
                    }

                    else 
     {
                        var numMins = new Number(dmin);
                        numMins = numMins.toString();
                        if (numMins.length == 1) 
      {
                            document.getElementById('min1').innerHTML = 0;
                            document.getElementById('min2').innerHTML = numMins.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('min1').innerHTML = numMins.substring(0, 1);
                            document.getElementById('min2').innerHTML = numMins.substring(1, 2);
                        }
                    }
     //Minute Region Ends Here
     
     //Second Region Starts Here
     if (dsec <= 0) 
     {
                        document.getElementById('sec1').innerHTML = "-";
                        document.getElementById('sec2').innerHTML = "-";

                    }
                    if (dsec > 0 && dsec < 10) 
     {
                        document.getElementById('sec1').innerHTML = 0;
                        document.getElementById('sec2').innerHTML = dsec;
                    }

                    else 
     {
                        var numSecs = new Number(dsec);
                        numSecs = numSecs.toString();
                        if (numSecs.length == 1) 
      {
                            document.getElementById('sec1').innerHTML = 0;
                            document.getElementById('sec2').innerHTML = numSecs.substring(0, 1);
                        }
                        else 
      {
                            document.getElementById('sec1').innerHTML = numSecs.substring(0, 1);
                            document.getElementById('sec2').innerHTML = numSecs.substring(1, 2);
                        }
                    }
     //Second Region Ends Here
     setTimeout("countdown(theyear,themonth,theday)", 1000)
                }
    //Don't comment this below mentioned else statement
    //This statement is very much helpful when you will perform testing of this code by providing old date
    //This else statement will only executed when you provide old date as compared to current date
                else {
                    document.getElementById('days1').innerHTML = "-";
                    document.getElementById('days2').innerHTML = "-";
                    document.getElementById('hrs1').innerHTML = "-";
                    document.getElementById('hrs2').innerHTML = "-";
     document.getElementById('min1').innerHTML = "-";
                    document.getElementById('min2').innerHTML = "-";
                    document.getElementById('sec1').innerHTML = "-";
                    document.getElementById('sec2').innerHTML = "-";

                }

            }
        }
    $(document).ready(function () {
            countdown(2011, 12, 25);
        });

</script>

And here's the html code of this example that you will copy and paste in your web page
<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 27px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Days</div>

  <div style="border: medium none; padding: 12px; margin: 0px 0px 480px 157px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Hrs</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 280px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Mins</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 480px 400px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 20px;font-family:verdana;">Secs</div>

<div style="border: medium none; padding: 12px; margin: 0px 0px 400px 27px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;"
        id="days1"> </div>
<div id="days2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 80px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;
        "> </div>
<div id="hrs1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 157px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;
       "> </div>
<div style="border: medium none; padding: 12px; margin: 0px 0px 400px 212px; position: absolute;
        z-index: 1000; bottom: 0px; left: 0px; font-size: 50px;"
        id="hrs2"> </div>
<div id="min1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 280px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="min2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 330px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="sec1" style="border: medium none; padding: 12px; margin: 0px 0px 400px 400px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>
<div id="sec2" style="border: medium none; padding: 12px; margin: 0px 0px 400px 450px;
        position: absolute; z-index: 1000; bottom: 0px; left: 0px; font-size: 50px; 
         "></div>

This countdown timer function will give you countdown between current date, that it will pick from your system date, and the date mentioned in calling of countdown timer function which is countdown(2011, 12, 25);

You just have to replace this date with the date you desire for countdown time. I have used jquery’s $(document).ready(function ()) event because I want to execute this function when every DOM is loaded. But if you don’t want to use jquery and its ready event then exclude the jquery file and its code from the example and copy/paste following code just before </html> tag

<script language="javascript" type="text/javascript">
countdown(2011, 12, 25);
</script>

This technique is equivalent to jquery’s document.ready event.

I have used two divs for showing days, two divs for showing hours, two divs for showing minutes and again two divs for showing seconds. For example if remaining days are 14 then 1 will be store in days1 div and 4 will be stored in days2 div. You can use one div for showing remaining days, hours, minutes and seconds.

Moreover, I have applied all the checks in javascript code so that function will not get any extra call if countdown is finished, I have seen lot of code in internet that work perfectly but when countdown is finished but its code is still in web page then the countdown function gets extra and totally unnecessary calls but in my example I have taken care of this issue and avoid extra calls to the countdown timer function.

So that’s it.
I love your feedback.

Read more...

Export to excel in php with jquery

In this programming tutorial we will learn how to perform export to excel in php. I have already written a post on same topic in asp.net as well. In php there are various methods for this purpose. In this tutorial I will discuss the very basic method that will export the plain data in table to excel. Let’s have a look over the example given below.
Export to excel in php with jquery
default.php
<html>
<head>
<title>Export to excel in php</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<style type="text/css">
.myClass
{
font-family:verdana;
font-size:11px;
}
</style>
</head>
<body>
<form action="exporttoexcel.php" method="post" 
onsubmit='$("#datatodisplay").val( $("<div>").append( $("#ReportTable").eq(0).clone() ).html() )'>
  <table id="ReportTable" width="600" cellpadding="2" cellspacing="2" class="myClass">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Country</th>
    </tr>
    <tr>
      <td><center>
          Adeel
        </center></td>
      <td><center>
          Fakhar
        </center></td>
      <td><center>
          Pakistan
        </center></td>
    </tr>
    <tr>
      <td><center>
          Zeeshan
        </center></td>
      <td><center>
          Butter
        </center></td>
      <td><center>
          England
        </center></td>
    </tr>
    <tr>
      <td><center>
          Neil
        </center></td>
      <td><center>
          Johnson
        </center></td>
      <td><center>
          United Kingdom
        </center></td>
    </tr>
    <tr>
      <td><center>
          Diala
        </center></td>
      <td><center>
          Katherine
        </center></td>
      <td><center>
          America
        </center></td>
    </tr>
  </table>
  <table width="600px" cellpadding="2" cellspacing="2" border="0">
    <tr>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td align="center"><input type="hidden" id="datatodisplay" name="datatodisplay">
        <input type="submit" value="Export to Excel">
      </td>
    </tr>
  </table>
</form>
</body>
</html>
exporttoexcel.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
In the onSubmit event of form, I am appending the div with ReportTable table. Using clone() method of jquery, I am making the clone of the ReportTable table that I wanted to export to excel, and in the end I am assigning the html of that cloned table to hidden field available in my form so that when form is posted then the data will be transferred to the exporttoexcel.php web page and in that web page I have all my logic for exporting data to excel in php.

Copy/paste this example, run the page and enjoy.

Note: - For this example to run properly, there must be no declaration of inline css in your table or div that you want to export. Whenever you use the style attribute to give inline css, the export to excel functionality will not be performed according to your expectations.

Later on, in this blog I will tell you other methods for this purpose; those methods will perform exporting with all the formatting that you have applied to the data of your table.

If you want to share your methods/techniques for export to excel in php then don’t hesitate to share with the rest of world through our blog.

So that’s it.
I love your feedback.

Update Note at 05-Oct-2011

Hay guys i really apologize that i miss an important line in the end of exporttoexcel.php page, the line is
echo $_REQUEST['datatodisplay'];
The above mentioned line of code will export the table data to excel. The absence of this line causing the generation of blank excel file that was also complained below by users in comments section . Now tutorial has been updated, I'm sorry for inconvenience.
Read more...

List all tables in a mysql database

In this programming tutorial we will learn how to list all tables in a mysql database. Sometimes you may want to get the table names of a mysql database; in that case the below mentioned show command will be very handy to you. It is as simple as reading a,b,c. Let’s have a look over it.

Show or List all tables in a mysql database
First of all you have to select the database whose tables you want to see.
Using this command, you will select the database.

use your_db_name

Replace your_db_name with the database name. And then use below mentioned command to get list of all tables in that database.

show tables

Yeah show tables command will do what you want.

So that’s it.
I love your feedback

Read more...

Change default Port of the ASP.NET Development Server

In this programming tutorial we will learn how to change default Port of the ASP.NET Development Server. Today one of my friend got alert message when he tried to view page in browser. He got this alert message. Unable to launch the asp.net development server because port '8080' is in use. We have solved this issue by changing the default port of the ASP.NET Development Server but there are two more ways to solve this issue as well. I will discuss those two ways as well in this tutorial. So lets start.

1) Change default Port of the ASP.NET Development Server

When you use the ASP.NET Development Server to run a file-system Web site, by default, the Web server is invoked on a randomly selected port for localhost. For instance, if you are testing a page called index.aspx and you run the page using the built-in ASP.NET Development Server also called Cassini Web Server, the URL of the page might be the following:
http://localhost:8080/index.aspx

Port is assigned according to project location as well.

You have the option to select which port is used when using the built-in development server. The steps to specify the port to be used are slightly different for a website project or for a web application project.

To specify a port for the ASP.NET Development Server - WebSite / WebServices project

  1. In Solution Explorer, right click the name of the application.
  2. In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list. It will enable editing of the Port number property.
  3. In the Properties pane, click the text box beside Port number and type in a port number that you want.
  4. Click outside of the Properties pane. This saves the property settings.

Whenever you run a file-system Web site within Visual Web Developer or visual studio then the ASP.NET Development Server will listen on the specified port.

To specify a port for the ASP.NET Development Server - Web Application project

  1. Right click the Project in the Solution Explorer -> select Properties
  2. Click Web tab.
  3. Check Specific port rather than Auto-assign Port.

This was the one solution and it was also the topic of my tutorial. But the other two ways to fix the Unable to launch the asp.net development server because port '8080' is in use issue are quite simple.

2) Restart your system

Yeah in computer science restarting the system normally fix many issues :) . It is better to delete the temporary files by typing %temp% command in run before restarting the system.

3) Change the location of the folder

Change the location of the Folder contains all the files of your website, to some thing else. Load in project in visual studio or visual web developer whatever you have installed in your system and run the project again. and u have done it.

It will work because the ASP.NET Development Server chooses a new port number to run the project.

So that's it :)
I love your feedback.
Read more...

How to check whether an element exists using jQuery

In this programming tutorial you will learn how to check whether an element exists using jQuery. Fortunately it is very easy in jquery. Let’s have a look over example given below.
How to check whether an element exists using jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script language="javascript" type="text/javascript">
<!--
if ($("#mydiv").length > 0){
  // div exists
  // do something here that you want to do
}

// -->
</script>
With a jQuery selector we can also use the length property, which will return the size of the object. If we don't use length property while using a selector, jQuery will always return an object. So the if statement will always be true and never be false.

If an element exists then the length of that element will be 1 else it will be 0.

So that’s it.
I love your feedback. Stay tuned :)
Read more...

Learn how to detect browser in javascript

In this programming tutorial you will learn how to detect the browser in javascript. Browser detection is a very important part of the web development. Sometimes it can be very handy to detect the visitor's browser and then serve the suitable information. Let’s have a look over the javascript code given below. This code will give you the exact browser name and its version, so that's why it is different from source codes available in other websites :)
Browser detection in javascript
<script language="javascript" type="text/javascript">
<!--
var DetectBrowser = {
 init: function () {
  this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
  this.version = this.searchVersion(navigator.userAgent)
   || this.searchVersion(navigator.appVersion)
   || "an unknown version";
  
 },
 searchString: function (data) {
  for (var i=0;i<data.length;i++) {
   var dataString = data[i].string;
   var dataProp = data[i].prop;
   this.versionSearchString = data[i].versionSearch || data[i].identity;
   if (dataString) {
    if (dataString.indexOf(data[i].subString) != -1)
     return data[i].identity;
   }
   else if (dataProp)
    return data[i].identity;
  }
 },
 searchVersion: function (dataString) {
  var index = dataString.indexOf(this.versionSearchString);
  if (index == -1) return;
  return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
 },
 dataBrowser: [
  {
   string: navigator.userAgent,
   subString: "Chrome",
   identity: "Chrome"
  },
  {  string: navigator.userAgent,
   subString: "OmniWeb",
   versionSearch: "OmniWeb/",
   identity: "OmniWeb"
  },
  {
   string: navigator.vendor,
   subString: "Apple",
   identity: "Safari",
   versionSearch: "Version"
  },
  {
   prop: window.opera,
   identity: "Opera"
  },
  {
   string: navigator.vendor,
   subString: "iCab",
   identity: "iCab"
  },
  {
   string: navigator.vendor,
   subString: "KDE",
   identity: "Konqueror"
  },
  {
   string: navigator.userAgent,
   subString: "Firefox",
   identity: "Firefox"
  },
  {
   string: navigator.vendor,
   subString: "Camino",
   identity: "Camino"
  },
  {  // for newer Netscapes (6+)
   string: navigator.userAgent,
   subString: "Netscape",
   identity: "Netscape"
  },
  {
   string: navigator.userAgent,
   subString: "MSIE",
   identity: "Internet Explorer",
   versionSearch: "MSIE"
  },
  {
   string: navigator.userAgent,
   subString: "Gecko",
   identity: "Mozilla",
   versionSearch: "rv"
  },
  {   // for older Netscapes (4-)
   string: navigator.userAgent,
   subString: "Mozilla",
   identity: "Netscape",
   versionSearch: "Mozilla"
  }
 ]
 
};
DetectBrowser.init();
alert("Browser name is "+DetectBrowser.browser);
alert("Browser version is "+DetectBrowser.version);
// -->
</script>
Note:-
The version detect doesn't work in Safari and OmniWeb because these browsers donot include appropriate version information in their identity string.

So that’s it. This is the way to detect browser in javascript.
I Love your feedback.

Read more...

Query to get the all column names of a given table in ms sql server


In this programming tutorial you will learn the query to get the all column names of a given table in ms sql server. Its quite easy. Lets have a look over the query

--Query to get the all field names of a given table in ms sql server
select column_name from information_schema.COLUMNS 
where table_name='yourtbl_name' 
order by column_name asc

So that's it.
I love your feedback.
Read more...

Query to get the all table names with their total number of columns stored in ms sql server


In this programming tutorial you will learn the query to get the all table names with their total number of columns stored in ms sql server. Its quite easy. Lets have a look over the query given below.

select table_name,count(*) as total_columns from information_schema.COLUMNS
GROUP BY table_name order by table_name asc

So that's it.
I love your feedback.
Read more...

Query to get the total no of columns in a given table in ms sql server database


In this programming tutorial you will learn the query to get the total no of columns in a given table in ms sql server database. Its quite easy in ms sql server. Lets have a look over the query given below

Select Count(*) As ColumnCount
From   Information_Schema.Columns
Where Table_Name = 'mytbl_name' 

So that's it. Run this query, replace the mytbl_name with your table name and enjoy.
I love your feedback.
Read more...

Query to get the total no of tables in a ms sql server database


In this programming tutorial you will learn the query to get the total no of tables in ms sql server database. Its quite easy. Lets have a look over the query mentioned below.

-- This query will give you the total no of user created tables
Select Count(*) As TableCount
From   Information_Schema.Tables
Where  Table_Type = 'BASE TABLE'
Table_Type='BASE TABLE' means the tables created by the users.

So that's it.
I love your feedback.
Read more...

MS SQL Server Optimization Techniques for ASP.Net Programmers

In this programming tutorial you will learn the MS SQL Server optimization techniques for asp.net programmers. MS SQL Server is a widely used database with websites developed in asp.net technology. If your website is connected with a large database that contains hundreds of tables and lot of visitors come daily to your website then you must have to explore your database and optimize it in order to get more efficiency from it.

The list below includes best techniques when developing or maintaining the website interacting with the MS SQL Server database. Try to adopt these optimization techniques when building efficient, scalable website. So let’s have a look over them.

Avoid Select * statement in your SQL queries

Don’t select all columns from table by using * in your sql query. Always mention columns name in your sql query because sometimes we get unwanted columns in the result, definitely those unwanted columns consume memory, so why should we get those unwanted columns. Avoiding select * will give you double benefit.

First benefit.

Let’s assume we have a table named as web_tbl_student and in this table we have 25 columns and 1600 records but in our query we only want to get the student’s firstname, lastname, rollno columns (fields) when gender is male. So the best practice that reduce memory consumption and network traffic will be

select firstname, lastname, rollno from web_tbl_student where gender="male"

And literally the bad practice will be

select * from web_tbl_student where gender="male"

Second benefit.

Make your query flexible and easy to understand for other programmers in-case you are not more attached with the company you are working for :)

So the Bottom line is, please don’t put extra burden on database.

Try to Use stored procedures and views instead of large and nested queries

If you really want to boost up the performance of your ms sql server database then always use stored procedures and views instead of large and nested queries. Send shorter queries to database that include only the name of stored procedure or view instead of large and heavy strings.

Use constraints instead of triggers

Constraint is more efficient and effective than trigger; you can improve the performance by using constraints instead of triggers.

When creating tables, don't use nvarchar and nchar if it is not necessary

Don’t use nvarchar and nchar while creating the tables if they are not necessary.
If you don’t want to store the Unicode characters in any column of your table or in whole table then please use varchar and char data types instead of nvarchar and nchar data types. Varchar and char need two times less space. I have already written a tutorial over Difference between varchar and nvarchar Over it.

Use comments in Stored Procedures

Always use comments while creating stored procedures. It will not decrease the performance and efficiency; literally it will improve your performance and productivity when you come back to your T-SQL code after a long time.

Use SQL Server .NET data provider

You can get access to MS SQL Server database with different ways. There are multiple providers such as OLEDB, ODBC and SQLServer.NET. The fastest and best is SQLServer.NET provider located in System.Data.SqlClient namespace. Remember, you can use SQLClient for SQL Server 7 or later versions. It cannot be used on SQL Server versions older than SQL Server 7. In older versions you can use OLEDB or ODBC (I recommend OLEDB).

Avoid use of unnecessary DISTINCT clause 

I have seen some web developers use distinct clause in almost every query, it is totally bad practice. You should only use it where you really want to use because it put extra burden on database.

Use UNION ALL instead of UNION

UNION ALL does not check the duplicate rows in database like UNION. Due to this UNION ALL is very fast. If there is no duplicate row in the table then use UNION ALL instead of UNION to get faster query execution.

Use SmallDateTime instead of DateTime

You should use SmallDateTime data type instead of DateTime. DateTime requires two times more space (8 bytes) than SmallDateTime (4 bytes). But one think you must know is that DateTime is precise. If you don’t want to save time intervals less than minute then you should use SmallDateTime.

Try to Use smallest possible integer data type

Again I have seen many web developers who by default choose int as a data type of column. Data type for column must be chosen according to value that will be stored in it. If column will store value within the range of 0 to 100 then in this case you should use tinyint data type rather than int.

Bigint, int, smallint and tinyint are integer data types available in ms sql server database.

tinyint data type can store numbers in the range from -128 to +127 / 0 to 255 (unsigned) only. Require 1 byte of storage per value.

Smallint data type can store numbers in the range from -32,768 to +32,767 / 0 to 65,535 (unsigned) only. Require 2 bytes of storage per value.

Int data type can store numbers in the range from -2,147,483,648 to 2,147,483,647 / 0 to 4,294,967,295 (unsigned) only. Require 4 bytes of storage per value.

Bigint data type can store numbers in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 / 0 to 18,446,744,073,709,551,615 (unsigned) only. Require 8 bytes of storage per value.

Use WHERE clause instead of HAVING CLAUSE

In order to boost up the performance of query, you should use WHERE clause instead of HAVING clause.

Must avoid SELECT COUNT(*)

This is the most important factor to discuss. Most of the asp.net web developers use
select count(*) from tbl_name
to get the total number of rows in the table. If your table contains 10,000 records then you muse think how much time that above query will take to give you the result as

Output:-
10000

Select COUNT(*) reads and scans entire table to return the total number of the rows. Using select count(*) is a bad practice, instead of select count(*) you must use the following query to get the total number of rows in the table

SELECT rows FROM sysindexes WHERE id = OBJECT_ID('tbl_name') and indid < 2 

Sysindexes is the built-in table in MS SQL Server that contains each and every information related all tables saved in the database. There is ROWS column in the sysindexes table that contains the total row count for each table in your database.

Make habit to Use Stored Procedures

It is better and faster to get access to the data via stored procedures. So to get the maximum performance and efficiency always use store procedures rather than ADO.NET methods.

Set NO COUNT ON in stored procedures

If we use NO COUNT ON command in stored procedures then the end users will not know how many rows effected by SQL query. It will boost up the performance and decrease the network traffic.

Use connection pooling on effective way

To get maximum from the connection pooling always use the same query string. You should only open connection when you really need to open and don’t forget to close connection when you don’t want to interact with database any more. Must remember to drop the temporary objects and close the transactions before closing the connection. Try to avoid the use of application roles as well.

Use Server IP address in connection string

If you use the server ip address instead of name resolution then your connection will be open very fast. On cluster use virtual SQL server ip address.

So that’s it. If you have any other ms sql server optimization techniques then share your thoughts with the rest of the world through our blog.

So these are the MS SQL Server Optimization Techniques for ASP.Net Programmers.

I love your feedback.

Read more...

Delete records in database using 3-tier architecture in asp.net with c#

In this programming tutorial you will learn how to delete the records in database using 3-tier architecture in asp.net with c#. For beginners ,I strongly recommend to read this tutorial 3-Tier Architecture in asp.net using c# first to get basics of 3-tier architecture in asp.net. So let’s begin, have a look over .aspx page
delete records in database using 3-tier architecture in asp.net with c#
Delete records in database using 3-tier architecture in asp.net with c#

delete-records.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="delete-records.aspx.cs" Inherits="delete_records" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> Delete records in database using 3-tier architecture in asp.net with c#</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false"
        GridLines="None" Width="100%" OnRowDeleting="GridView1_RowDeleting"
>
        <Columns>
            <asp:TemplateField HeaderText="Roll No" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:Label ID="lblRollNo" runat="server" EnableTheming="false" Text='<%# Bind("rollNo")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="First Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("firstName")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("lastName")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" EnableTheming="false" Text='<%# Bind("gender")%>'></asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete" HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:Label ID="lblDelete" Visible="false" Text='<%# Bind("rollNo")%>' runat="server"></asp:Label>
                    <asp:ImageButton runat="server" ID="img" ImageUrl="images/delete.gif" CommandName="Delete"
                        OnClientClick="return window.confirm('Are you sure you want to delete this record?')" />
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</form>
</body>
</html>
As you have seen, we have an asp:gridview control in our web page. We have four template fields in it, these are rollNo, firstName, lastName and Delete image to delete the records. The main thing you must have to notice is the OnRowDeleting event of gridview. Through this event we will delete the records from database. So let’s have a look over its c# code behind file.

delete-records.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using BusinessLayer;//Don’t forget to include this namespace

public partial class delete_records : System.Web.UI.Page
{
    BusStudent _objStudent = new BusStudent();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
                
                BindGrid();
            
        }

    }

    public void BindGrid()
    {
        _objStudent.GetStudentRecords();
        GridView1.DataSource = _objStudent.StudentDS.Tables["studentrecords"];
        GridView1.DataBind();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;
        GridViewRow row = GridView1.Rows[index];
        //The asp:label just before delete image
        Label lbl = (Label)row.FindControl("lblDelete");
        int rollNo = Convert.ToInt32(lbl.Text);
        //Deleting Records From Database    
        _objStudent.DeleteStudentRows(rollNo);
       //Again Populating Gridview after records deletion
        BindGrid();
    }
}

BusStudent.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DataAccessLayer;//Donot forget to import this namespace

namespace BusinessLayer
{
public class BusStudent
{
DbAccess _dbAccess = new DbAccess();
private DataSet _StudentDS = new DataSet();
public DataSet StudentDS
{
get
{
return _StudentDS;
}
set
{
_StudentDS = value;
}
}

        public void GetStudentRecords()
        {

            try
            {
                string strQuery = "select rollNo,firstName,lastName,gender from web_tbl_student";
                if (_StudentDS.Tables.Contains("studentrecords"))
                {
                    _StudentDS.Tables["studentrecords"].Clear();
                }
                _dbAccess.selectQuery(_StudentDS, strQuery, "studentrecords");
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

  //Function to delete records from database, in this example I used MS SQL SERVER as a backend database   

        public void DeleteStudentRows(int rollNo)
        {
            try
            {
       // I will always recommend you to not delete the records physically
                string strQuery = "delete from web_tbl_student where rollNo='"+ rollNo +"'";
                _dbAccess.executeQuery(strQuery);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }



}

}


Every thing is self explanatory and I will not go into any details as I already have written two tutorials 3-Tier Architecture in asp.net using c# and Insertion of records in database using 3-tier architecture in asp.net with c#.

If anything is not cleared then please read these above mentioned tutorials first. So this is the way to delete records in database using 3-tier architecture in asp.net with c#.

I love your feedback.

Read more...