Pages

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)">
  </asp:TextBox>


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

else

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

btn.click();

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
 
if(!IsPostBack())
{
   // To do
}
else
{
  // 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)
{
alert(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)
{
alert(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)
{
alert(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)
{
alert(value);
}

Thanks
Mukunda

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('\/'));
}
else
return 'Netscape';
}
else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
else
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.

Thanks
Mukunda

Sep 4, 2009

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

DECIMAL TO DEGREE CONVERTION ON SERVER SIDE :

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

DEGREE TO DECIMAL CONVERTION ON SERVER SIDE :

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 Asp.net 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.

%response.buffer=true%
Then use:

%response.flush=true%

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 BadAsp.net 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.
ASP.net 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 ASP.net 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.
configuration
system.web
trace enabled="false" pageOutput="false"
trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"
compilation debug="false"
system.web
configuration


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 ASP.net 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
String.Concat

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 asp.net 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 ASP.net 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 ASP.net that will have a dramatic impact on the user experience of your application.

Refer: www.realsoftwaredevelopment.com

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;
alert(str);
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 asp.net like


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


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



Thanks
Mukunda

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);
hza.style.display = state;
}
// To set focus to the div instead of scrolling
div1.scrollIntoView();
}


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