Nov 12, 2009

How to select the First midde and last word in a phrase + SQL SERVER 2008

No Doubt "SQL SERVER" is a great utility that makes various operation more simple.
"Nothing is Impossible with SQL SERVER"

Now lets see how to select a last word from a phrase.

1. Selecting the first word in a pharse is simple as we trace for the first space in the phrase and get the charindex of the first space and we can make it done using the Left function.
SELECT LEFT('Be Always Happy',CHARINDEX(' ','Be Always Happy')-1)


2. Now how to select the last word of the pharse ?
How we gonna trace for the last space in the phrase? let see
One method is like

SELECT PARSENAME(REPLACE('Be Always Happy', ' ', '.'), 1)


3.we can also select the second word form the right like

SELECT PARSENAME(REPLACE('Be Always Happy', ' ', '.'), 2)


Replacing the 2 by 3 would select the third word from the phrase namely 'Be'
and go on as many word we have.

But this wont work at all the time say for example when there is dot at the end of the phrase like

SELECT PARSENAME(REPLACE('Be Always Happy.', ' ', '.'), 1)

Now the output is NULL for the above query.

So i found the method which can handle all possible situations. Lets see how?

Finding Last word of a phrase:

SELECT RIGHT('Be Always Happy.', CHARINDEX(' ', REVERSE('Be Always Happy.')) - 1)

With the above query its done. There may be many way to achieve this but this is one simple idea.

Nov 11, 2009

How the change the First letter of each word in a string to caps + SQL SERVER 2008

The Following is the way to achieve this:

DECLARE @Name VarChar(25), @SpaceIndex TinyInt

SET @Name = 'be happy' // is the input string

-- Determines whether the string has more than one word:

SET @SpaceIndex = CHARINDEX(' ', @Name)

IF @SpaceIndex <> 0

-- Space: Capitalize first & substring


+ LOWER(SUBSTRING(@Name, 2, @SpaceIndex - 1))

+ UPPER(SUBSTRING(@Name, @SpaceIndex + 1, 1))

+ LOWER(SUBSTRING(@Name, @SpaceIndex + 2, LEN(@Name)))


-- No space: Cap only first char.


+ LOWER(SUBSTRING(@Name, 2, LEN(@Name)))

Be Happy

Oct 14, 2009

How to read a MS Access file from SQL SERVER using OPENDATASOURCE

Reading an MS Access database from SQL SERVER is possible and quite simple.

'Data Source=\\server1\C\TEMP\orderDB.mdb')...[orders]

Here the above SQL Query uses OPENDATASOURCE method to read the MS Access file .
1. 'Orders' is the name of the table in MS Access mdb file.
2. The 3 dots (...) should be there before specifiying the table name.
3. “Ad hoc distributed queries” has to be enabled to used the OPENDATASOURCE method.

Oct 13, 2009

how to execute a SP or table query every 5secs + SQL SERVER

The below query would make a delay of 5secs in calling he SP.

While 1 = 1


EXEC dbo.UpdateCustomer // executes the SP named UpdateCustomer

waitfor delay '00:00:05'

Here the delay notification is in hrs:Mins:secs

Sep 30, 2009

how to make javascript operation wait for some time without doing any process

Below is the function that halts the javascript process for specified number of milliseconds

function wait(msecs)
var start = new Date().getTime();

var cur = start

while(cur - start < msecs)


cur = new Date().getTime();



In Client side this can be called as wait(5000) will make the process wait for 5 seconds.
Note: you cannot execute anyother process at this time.

Sep 22, 2009

Javascript validation for numeric or decimal value

How to make a textbox wont even allow user to type a invalid text :

// To check whether the value entered is a numeric or decimal value.

// This method will wont even allow the user to type the invalid value.

function isNumber(field) {

var re = /^[0-9.]*$/;

if (!re.test(field.value)) {

field.value = field.value.replace(/[^0-9.]/g, "");


The above method will wont even allow you to type any text or * or $ symbol in textbox.
// To make a call to the method on onkeyup event.

<asp:TextBox ID="txtRadNZoomValue" Runat="server" Width="65px" ForeColor="Black" onkeyup="isNumber(this)">

This is also tested in master pages scenerio .

How to raise a button click event on Enter keypress

Button click on Enter :

On client side:

// To perform button click operation on enter.

function doClick(buttonName, e) {

//the purpose of this function is to allow the enter key to

//point to the correct button to click.

var key;

if (window.event)

key = window.event.keyCode; //IE


key = e.which; //firefox

if (key == 13) {

//Get the button the user wants to have clicked

var btn = document.getElementById(buttonName);

if (btn != null) { //If we find the button click it;

event.keyCode = 0



On server side :
on server side we have to specify that the click should happen only when the cursor is on certain text box.
txtRadNZoomValue.Attributes.Add("onKeyPress", "doClick('" + btnZoomValue.ClientID + "',event)");

How to convert Miles to KM in javascript

Below is the simple method to convert Miles to KM.

function ConvertMileToKM(dist)
var distC = dist * 1; // to make the value as integer
var distKM = dist * 1.609344; // to convert into km
var distMile = distC.toFixed(2); // to round it to 2 decimal places.

To convert a string value to integer we can simply multiply with 1
stringvalue * 1 will give you a integer value

Sep 21, 2009

How to check for postback in clientside javascript

Javascript Ispostback Method :

Normally we use IsPostback method in the server side to check for postback. But there may be some situations where we really need this on clientside.
So lets see how to do this

// Client side postback Identification

function IsPostBack() {

return < %= IsPostBack.ToString().ToLower() % >;

The above method will return the boolean value indicating whether it is a postback or not. we can use like below
   // To do
  // To do
So Checking for postback in clientside javacript is possible.

How to call a javascript method on Keypress or Keydown

How to call method on keypress :

we can use
document.onkeypress = KeyCheck; or

document.onKeydown = KeyCheck;

// to perform operation on esc key press
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == '27') // 27 is the key code for ESC key

// To do


Note : onKeypress wont work for safari browser so we can use onkeydown

Sep 17, 2009

Passing arguments to javascript’s setTimeout() method

Javascript's setTimeout - A detailed look :
Normal set time out method which will call the method test() after 2 seconds.

setTimeout(test(), 2000 );
function test()
alert("Its done ! Be Happy");
Now the above will work fine but what happens when we want to call a method
with a delay which has arguments ? so we may go for

setTimeout(test('Enjoy'), 2000 );
function test(value)

Even the above method will work fine but then if we want to call a method which
may have dynamic argument then see what happens

function dynamicArgument(value)
setTimeout(test(value), 2000 );

function test(value)
The above is wrong and wont work so we have to follow some other way to make it work.
Lets see
function dynamicArgument(value)

var delay = function() { test(value); };
setTimeout(delay,2000 );
function test(value)
- here the method with argument is assigned to a var delay and used in the settimeout method.

The above will work or else we can do it still simpler like

function dynamicArgument(value){
setTimeout(test,2000,[value] );

function test(value)


How to detect browser name + Clientside + javascript

Below is the Clientside script to identify the browser name:

function detect_browser()
var agt = navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
if (agt.indexOf('\/') != -1)
if (agt.substr(0,agt.indexOf('\/')) != 'mozilla')
return navigator.userAgent.substr(0,agt.indexOf('\/'));
return 'Netscape';
else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
return navigator.userAgent;

This is the general method for all browsers , if you want to identify only when
the browser is safari then use like this

function detect_browser()
var agt = navigator.userAgent.toLowerCase();
if (agt.indexOf("safari") != -1) return 'Safari';


Apart from this the navigator object has the following properties

The navigator object was conceived back in the days when Netscape Navigator reined supreme. These days it serves as much as an irony of NS's diminished market share as way of probing browser information.

The navigator object of JavaScript contains the following core properties:
Properties Description
appCodeName - The code name of the browser.
appName - The name of the browser (ie: Microsoft Internet Explorer).
appVersion - Version information for the browser (ie: 4.75 [en] (Win98; U)).
cookieEnabled - Boolean that indicates whether the browser has cookie enabled.

language - Returns the default language of the browser version (NS and Firefox only).
mimeTypes[] - An array of all MIME types supported by the client. (
NS and Firefox only).
platform[] - The platform of the client's computer (ie: Win32).
plugins - An array of all plug-ins currently installed on the client. (
NS and Firefox only.)
systemLanguage Returns the default language of (ie: en-us). IE only.
userAgent - String passed by browser as user-agent header.

(ie: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1))
userLanguage - Returns the preferred language setting of the user (ie: en-ca).
IE only.


Sep 4, 2009

How to convert decimal value to Degree Mins Secs and viceversa in C#


private string convertToDegrees(decimal decValue)
//Method to convert to Decimal values to Degrees.
int Degree = 0, Mins = 0, Secs = 0;
decimal dec_Mins = 0.0M, dec_Secs = 0.0M;
string output = null;

Degree = (int)decValue;
dec_Mins = Math.Abs(decValue - Degree) * 60;
Mins = (int)dec_Mins;
dec_Secs = Math.Abs(dec_Mins - Mins) * 60;
dec_Secs = Math.Round(dec_Secs);
Secs = (int)dec_Secs;
output = Degree + "°" + Mins + "." + Secs;
return output;

The above method takes decimal as input and output degree.
The below method does the vice versa


public string ConvertDegToDec(string value)
double vDeg, vMin, vSec, vConv1;
string result = string.Empty;
// attempt to convert if valid data
string[] lines = Regex.Split(value, "ΓΈ");
string[] lines1 = Regex.Split(lines[1], "'");
string[] lines2 = Regex.Split(lines1[1], "\"");
vDeg = Double.Parse(lines[0]);
vMin = Double.Parse(lines1[0]);
vSec = Double.Parse(lines2[0]);
vConv1 = vDeg + (vMin / 60) + (vSec / 3600);
result = vConv1.ToString();
return result;

How to convert decimal to Degree Mins Secs

private string convertToDegrees(decimal decValue)
//Method to convert to Decimal values to Degrees.
int Degree = 0, Mins = 0, Secs = 0;
decimal dec_Mins = 0.0M, dec_Secs = 0.0M;
string output = null;

Degree = (int)decValue;
dec_Mins = Math.Abs(decValue - Degree) * 60;
Mins = (int)dec_Mins;
dec_Secs = Math.Abs(dec_Mins - Mins) * 60;
dec_Secs = Math.Round(dec_Secs);
Secs = (int)dec_Secs;
output = Degree + "°" + Mins + "." + Secs;
return output;

Sep 3, 2009

How to improve the performance of Asp.Net web application

Below are the valid tips to improve the web app performance.

1. Disable Session State
Disable Session State if you’re not going to use it. By default it’s on. You can actually turn this off for specific pages, instead of for every page:

%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="WebApplication1.WebForm1"
EnableSessionState="false" %

You can also disable it across the application in the web.config by setting the mode value to Off.

2. Output Buffering:
Take advantage of this great feature. Basically batch all of your work on the server, and then run a Response.Flush method to output the data. This avoids chatty back and forth with the server.

Then use:


3. Avoid Server-Side Validation:
Try to avoid server-side validation, use client-side instead. Server-Side will just consume valuable resources on your servers, and cause more chat back and forth.

4. Repeater Control Good, DataList, DataGrid, and DataView controls is a great platform, unfortunately a lot of the controls that were developed are heavy in html, and create not the greatest scaleable html from a performance standpoint. repeater control is awesome! Use it! You might write more code, but you will thank me in the long run!

5. Take advantage of HttpResponse.IsClientConnected before performing a large operation: if (Response.IsClientConnected)
// If still connected, redirect
// to another page.
Response.Redirect("Page2CS.aspx", false);

6. Use HTTPServerUtility.Transfer instead of Response.RedirectRedirect’s are also very chatty. They should only be used when you are transferring people to another physical web server. For any transfers within your server, use .transfer! You will save a lot of needless HTTP requests.

7. Always check Page.IsValid when using Validator ControlsSo you’ve dropped on some validator controls, and you think your good to go because does everything for you! Right? Wrong!
All that happens if bad data is received is the IsValid flag is set to false. So make sure you check Page.IsValid before processing your forms!

8. Deploy with Release Build:
Make sure you use Release Build mode and not Debug Build when you deploy your site to production. If you think this doesn’t matter, think again. By running in debug mode, you are creating PDB’s and cranking up the timeout. Deploy Release mode and you will see the speed improvements.

9. Turn off TracingTracing is awesome, however have you remembered to turn it off? If not, make sure you edit your web.config and turn it off! It will add a lot of overhead to your application that is not needed in a production environment.
trace enabled="false" pageOutput="false"
trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"
compilation debug="false"

10. Page.IsPostBack is your friend:
Make sure you don’t execute code needlessly.

11. Avoid Exceptions :
Avoid throwing exceptions, and handling useless exceptions. Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications. Write your code so they don’t happen! Don’t code by exception!

12. Caching is Possibly the number one tip!
Use Quick Page Caching and the Cache API! Lots to learn, its not as simple as you might think. There is a lot of strategy involved here. When do you cache? what do you cache?

13. Create Per-Request CacheUse HTTPContect.Items to add single page load to create a per-request cache.

14. StringBuilder :
StringBuilder.Append is faster than String + String. However in order to use StringBuilder, you must use
new StringBuilder()
Therefore it is not something you want to use if you don’t have large strings. If you are concatenating less than 3 times, then stick with String + String.
You can also try

15. Turn Off ViewState :
If you are not using form postback, turn off viewsate, by default, controls will turn on viewsate and slow your site.
public ShowOrdersTablePage()
this.Init += new EventHandler(Page_Init);
private void Page_Init(object sender, System.EventArgs e)
this.EnableViewState = false;

16. Use Paging :
Take advantage of paging’s simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster. Just be careful when you mix in caching. How many times do you hit the page 2, or page 3 button? Hardly ever right! So don’t cache all the data in the grid! Think of it this way: How big would the first search result page be for “music” on Google if they cached all the pages from 1 to goggle

17. Use the AppOffline.htm when updating binariesI hate the generic error messages! If I never had to see them again I would be so happy. Make sure your users never see them! Use the AppOffline.htm file!

18. Use ControlState and not ViewState for Controls If you followed the last tip, you are probably freaking out at the though of your controls not working. Simply use Control State.
Microsoft has an excellent example of using ControlState here,

19. Use the Finally Method:
If you have opened any connections to the database, or files, etc, make sure that you close them at the end! The Finally block is really the best place to do so, as it is the only block of code that will surely execute.

20. Option Strict and Option Explicit :
This is an oldy, and not so much a strictly tip, but a .net tip in general. Make sure you turn BOTH on. you should never trust .net or any compiler to perform conversions for you. That’s just shady programming, and low quality code anyway. If you have never turned both on, go turn them on right now and try and compile. Fix all your errors.

There are hundreds more where these came from, however I really feel that these are the most critical of the speed improvements you can make in that will have a dramatic impact on the user experience of your application.


Sep 2, 2009

Client side Email validation + Javascript

Below is the javascript used to check for a valid email.

var testresults;
function checkEmail() {
var str = document.getElementById('txtMail').value;
var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
radalert("Please input a valid email address!", 300, 100);
testresults = false

As an alternative you can also use the same Regex check for the valid email using the RegularExpressionValidator validation control in like

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
   Display="Dynamic" ErrorMessage="Please Enter valid Email Address"
  ValidationExpression='[\w\.-]*[a-zA-Z0-9_]@[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA- Z\.]*[a-zA-Z]'       

<asp:ImageButton id="btnSendEmail" runat="server" OnClick="btnSendEmail_Click" ImageUrl="~/NewImages/SendButton.png" ValidationGroup="Email" />


Sep 1, 2009

How to show and hide a div in FireFox + Javascript

Normal show and hide code which we normally implement for IE wont work for FireFox. So we go for a generalised code like the below which will work both in FireFox and IE.
The below code show and hide a div on the imagebutton OnClientClick Client side event.

var state = 'none';
function showhide(divtest) {
if (state == 'block') {
state = 'none';
else {
state = 'block';
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval("document.all." + divtest+ ".style.display = state");
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[divtest].display = state;
if (document.getElementById && !document.all) {
hza = document.getElementById(divtest); = state;
// To set focus to the div instead of scrolling

asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="showhide('div1');return false;" ImageUrl="~/NewImages/Email.png"

Aug 13, 2009

How to generate a random unique 5 digit number + C#

Below is the method used to generate random 5 digit number.

public int getRandomID ()


Random r = new Random()

return r.Next(10000,99999);


The number 10000, 99999 specifies the range.

Aug 12, 2009

How to find and remove Special Characters from a given string. + C#

Here is the method which can remove all the special characters from a given stirng

public string RemoveSpecialChars(string str)
string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "-", "_", "(", ")", ":", "", "[", "]" };
for (int i = 0; i < chars.Length; i++)
if (str.Contains(chars[i]))
str = str.Replace(chars[i], "");
return str;


May 1, 2009

Useful Links

1 JavaScript

1.1 How to get client date and time

1.2 How to access a control by using JavaScript

1.3 How to invoke a server-side function with JavaScript

1.4 How to retrieve server side variables using JavaScript code

1.5 How to assign a value to a hidden field using JavaScript in ASP.NET

1.6 How to register the JavaScript function at Code-Behind

1.7 How to display images with a delay of five seconds

1.8 How to get browser screen settings and apply it to page controls

1.9 How to clear the session when the user closes a window

2 Ways to pass data between pages

2.1 How to use cookies

2.2 How to use QueryString

2.3 How to use Session

2.4 How to use Context

2.5 How to use PreviousPage

2.6 How to use Submit Form

2.7 How to use Server.Transfer

3 File Upload

3.1 How to upload a file

3.2 How to upload multiple files at once

3.3 Why upload fails when using an ASP.NET FileUpload control to upload large files

3.4 How to upload an image files only

3.5 How to get a File Upload control work with an UpdatePanel

4 Calendar

4.1 How to change the culture settings for a Calendar

4.2 How to select multiple non-sequential dates at Code-Behind

4.3 How to disable some dates in Calendar control

4.4 How to extend Calendar control for Server-Side validation

4.5 How to set ToolTips and links in Calendar control’s DayRender event

4.6 How to give some dates different appearances

5 List controls

5.1 How to enable ASP.NET DropDownList with OptionGroup support

5.2 How to disable an item in DropDownList

5.3 How to hold the selected value for a DropDownList

6 User control

6.1 How to add a new property to UserControl

6.2 How to access a dynamically created UserControl

6.3 How to access a control inside a UserControl

7 Dynamic controls

7.1 How to create a dynamic control

7.2 How to access a user entered value in a dynamic created TextBox control

7.3 Dynamic controls accessed by JavaScript

7.4 How to retain all added server controls dynamically after post back

7.5 Why dynamically created controls disappear after a post back

8 Style

8.1 How to use with Code-Behind

8.2 How to use with JavaScript

8.3 How to remove a space

8.4 How to use with html

8.5 How to set an image as Button’s background

8.6 How to color items in ListBox

9 Print

9.1 How to print a part of a web page with CSS

9.2 How to print a part of a web page with JavaScript (1)

9.3 How to print a part of a web page with JavaScript (2)

10 Mail

10.1 What classes are needed to send e-mails in ASP.NET

10.2 How to send emails by using System.Net.Mail

10.3 How to configure a SMTP Server

10.4 How to send an email with Gmail server

How to Select the Asp.Net server controls + JQuery

People while using MasterPages in your applications client ID of controls will differ from "server" ID. That's because ASP.NET creates a new ID for controls on a page. So this is probably very familiar to you:


You set the ID of the textbox to "txtName" and ASP.NET adds "ctl00_cphContent_". Although there were some tries to prevent ASP.NET from generating unique ID's, I think it's better to use quick and "dirty" solutions :-)

So, how to select a server control using JS/jQuery? The usual way to select an element in JavaScript is to use server tags:

document.getElementById("<%=txtName.ClientID %>");

You can use the same approach with jQuery:

$("#'<%=txtName.ClientID %>'");

JQuery enables you to avoid server tags completely. Since we can search for element just by the part of the name, we can do the next:


This will find elements which id's ends with "_txtName". But why the dash in the front of the name? This will ensure you selected the element by its full control ID, not just a part of it.

Pretty simple, isn't it? The only issue here would be if you have controls with the same name placed in different content pages.

How to access Page's session variable or create a new session variable in a normal C# class

This is Quite simple,

1 . We have lot of classes in the web application where the have the need to maintain or access the page's data or the server controls data between classes.
2. And there may be a situation where we need to send the data to the UI Page from the AppCode class or any class. For eg: i have processed something and need to send the data to the textbox in the UI Page.

This would be achieved by using

And like this you can create a session variable in a non UI class and access it in the page's class.

HttpContext.Current.Session["test1"] = "Got from test";

and the same way you can access the page's session variable in the non UI class like

string test = string.Empty;
test = HttpContext.Current.Session["test1"].ToString();

Thus we can maintain the data between the classes no matter whether it is UI or normal class.