Wednesday, August 18, 2010

Valiodation JavaScript

/*
'File Name : valjavavalidate.asp
'File Date : 14th December 2000
'Developer : Shailesh
'Company : E Vision Technologies Pvt Ltd.
'Modified By : Rupa Modha , Uday kadam
'Modified Date : 25th July 06
'Comments : function to validate in javascript
1) string trim(string)
2) boolean checkempty(object,errmsg)
3) boolean checkemail(object,errmsg)
4) boolean chemnumeric(object,errmsg)
5) boolean checktelno(object,errmsg)
6) boolean checkmaxlength(object,length,errmsg)
7) boolean checkminlength(object,length,errmsg)
8) boolean checkinteger(object,errmsg)
9) boolean CompareDates(fromdate,todate,errmsg) Compares two dates.
10) IsLeapYear(intYear)
11) boolean CheckMultipleSelection(objlist,errmsg)
12) boolean checkList(objlist,errmsg)
13) boolean checkConfirmPassword(object,object)
*/

//Function trim similiar to Visual Basic Trim()
//Removes Leading and trailing spaces and tabs from the argument passed
//returns a string
//trim all the required fields using this function

//Developed By Mishal
function trim(str)
{
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
/*var x;
var ch;

for(x=0;x {
ch=str.substr(x,1);
if(ch==' ' || ch=='\t')
{
str=str.substr(x+1,str.length-1);
}
else
break;
}

for(x=str.length-1;x>=0;x=x-1)
{
ch=str.substr(x,1);
if(ch==' ' || ch=='\t')
{
str=str.substr(0,str.length-1);
}
else
break;
}

return str;*/
}
//developed by Rupa Modha
function checkMark(objMark)
{
if(objMark.Checked)
return true;
return false ;
}

// developed by Rupa Modha
function CheckMultipleSelection(objlist,errmsg)
{
var i;
for(i = 0 ; i< objlist.length;i++)
{
if(objlist[i].selected)
{
if(objlist[i].value <= 0)
{
alert(errmsg);
return false;
}
}
}
return true ;
}

// for checking to lisitem is selected or not
// developed by Rupa Modha
function checkList(objlist,errmsg)
{
var i ,flag ;
flag = false;
for(i=0;i< objlist.length;i++)
{
if(objlist[i].selected)
{
flag = true ;
break;
}
}
if(flag)
return true ;
else
{
alert(errmsg);
return false;
}
}

function checkDrp(objDrp,errmsg)
{
if(objDrp.selectedIndex == 0)
{
alert(errmsg);
objDrp.focus();
return false
}
return true ;
}

//this function acceots two object as parameter
//and compare the value for similarity & display the Appropriate msg
function checkConfirmPassword(objNew,objConfirm)
{
if(trim(objNew.value) != trim(objConfirm.value))
{
alert("Password mismatch in New & Confirm Password ");
return false
}
return true ;
}


//this function accepts the object as a parameter and display the appropriate error messages if the text box is empty
function checkempty(objname,errmsg)
{
// alert("checkempty");
if (trim(objname.value)=="")
{ //alert("hello Empty");
alert(errmsg);
objname.focus();
return false
}
return true;
}

function IsEmpty(objname)
{
if (trim(objname.value)=="")
return true
else
return false;
}

//this function accepts the object as a parameter and display the appropriate error messages if the text box is empty
//similar to the above function only that it checks for combo box
function checkcomboempty(objname,errmsg)
{
if (trim(objname[objname.selectedIndex].value)=="")
{
alert(errmsg);
objname.focus();
return false
}
return true;
}

function checkcomboempty_0(objname,errmsg)
{
if (trim(objname[objname.selectedIndex].value)=="0")
{
alert(errmsg);
objname.focus();
return false
}
return true;
}

function checknumeric(objname,errmsg)
{
if (isNaN(trim(objname.value)))
{
alert(errmsg);
objname.focus();
return false;
}
return true;
}
//Email validation starts from here
function checkemail(objname,errmsg)
{
/*
vvalue=trim(objname.value);
atPos = vvalue.indexOf('@');
sppos = vvalue.indexOf(" ");
dopos = vvalue.indexOf(".");
if (atPos < 1 || atPos == (vvalue.length - 1) || (sppos != -1)|| (dopos == 1))
{
alert(errmsg);
objname.focus();
return false;
}
return true;*/


if(objname.value!="")//added by Sunil
{
vvalue=trim(objname.value);
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(vvalue))
{
return true;
}
alert(errmsg);
objname.focus();
return false ;
}
return true;

}
//Email validation ends from here

function checkalreadyemail(objname,errmsg)
{
//var str = trim(objname.value);
//var conn;
//set conn =


}

//telno validation starts from here
//it checks that the entered value does not contain anything except numeric characters and hyphen
function checktelno(objname,errmsg)
{
var str = trim(objname.value);
for(x=0;x {
ch=str.substr(x,1);
if ((ch < '0' || ch >'9')&&(ch!='-'))
{
alert(errmsg);
objname.focus();
return false;
}
}
return true;
}
//telno validation ends over here

//maxlength validation starts over here
function checkmaxlength(objname,maxlength,errmsg)
{
var str = objname.value;
if (str.length>maxlength)
{
alert(errmsg);
objname.focus();
return false;
}
return true;
}
//maxlength validation ends over here

//minlength validation starts over here
function checkminlength(objname,minlength,errmsg)
{
var str = objname.value;
if (str.length {
alert(errmsg);
objname.focus();
return false;
}
return true;
}
//minlength validation ends over here
function checkinteger(objname,errmsg)
{
var str = trim(objname.value);
for(x=0;x {
ch=str.substr(x,1);
if ((ch < '0' || ch >'9'))
{
alert(errmsg);
objname.focus();
return false;
}
}
return true;
}
//

function checkDecimals(fieldName, fieldValue)
{
decallowed = 2; // how many decimals are allowed?

//if (isNaN(fieldValue) || fieldValue == "")
if (isNaN(fieldValue))
{
alert("Please Enter a Valid Number");

fieldName.select();
fieldName.focus();
return false;
}
else
{
if (fieldValue.indexOf('.') == -1) fieldValue += ".";
dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);

if (dectext.length > decallowed)
{
alert ("Please Enter A Number With Upto " + decallowed + " Decimal Places");
fieldName.select();
fieldName.focus();
return false;
}
else
return true;
}
return true;
}

function CompareDates(fromDate,toDate,errmsg)
{
//By Uday.
// modified by Rupa Modha
/* for mm/dd/yyyy format */

//alert(fromDate);
if (Date.parse(fromDate.value) >= Date.parse(toDate.value))
{
//alert("To date must occur after the from date.");
alert(errmsg);
toDate.focus();
return false;
}
else
{
return true;
}
}

function IsLeapYear(intYear)
{
//By Uday
if (intYear % 100 == 0)
{
if (intYear % 400 == 0) { return true; }
}
else
{
if ((intYear % 4) == 0) { return true; }
}
return false;
}

function ValidateDateRange(from,to)
{
/* For dd/MM/yyyy format */

var dtFrom = new Date(from.value.substring(6,10),from.value.substring(3,5)-1,from.value.substring(0,2));
var dtTo = new Date(to.value.substring(6,10),to.value.substring(3,5)-1,to.value.substring(0,2));

if(dtFrom <= dtTo)
{
return true;
}
else
{
alert("To date must occur after the from date.");
to.focus();
return false;
}
}

// added on 26-04-06 by manoj
//functions block checks dates with combo ( dd / MM / yyyy )

function checkdate(objName) {
var datefield = objName;
if (chkdate(objName) == false) {
//datefield.select(); // original code line manoj
//alert("That date is invalid. Please try again.");

return false;
}
else {
return true;
}
}
function chkdate(objName) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU"; //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
/*var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";*/

strMonthArray[0] = "1";
strMonthArray[1] = "2";
strMonthArray[2] = "3";
strMonthArray[3] = "4";
strMonthArray[4] = "5";
strMonthArray[5] = "6";
strMonthArray[6] = "7";
strMonthArray[7] = "8";
strMonthArray[8] = "9";
strMonthArray[9] = "10";
strMonthArray[10] = "11";
strMonthArray[11] = "12";

// strDate = datefield.value;// original code manoj
strDate = datefield;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
}
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
}
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
}
}
if (isNaN(intMonth)) {
err = 3;
return false;
}
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}
return true;
}

function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}

function doDateCheck(from, to) {
if (Date.parse(from.value) <= Date.parse(to.value)) {
//alert("The dates are valid.");
return true;
}
else {
if (from.value == "" || to.value == "")
{
alert("Both dates must be entered.");
return false;
}
else
{
//alert("To date must occur after the from date.");
return false;
}
}
}


function chkdate_ddmmyyyy(objName) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU"; //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
/*strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
*/

strMonthArray[0] = "1";
strMonthArray[1] = "2";
strMonthArray[2] = "3";
strMonthArray[3] = "4";
strMonthArray[4] = "5";
strMonthArray[5] = "6";
strMonthArray[6] = "7";
strMonthArray[7] = "8";
strMonthArray[8] = "9";
strMonthArray[9] = "10";
strMonthArray[10] = "11";
strMonthArray[11] = "12";


strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
}
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
}
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
}
}
if (isNaN(intMonth)) {
err = 3;
return false;
}
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}
function doDateCheck(from, to) {
if (Date.parse(from.value) <= Date.parse(to.value)) {
//alert("The dates are valid.");
return true;
}
else {
if (from.value == "" || to.value == "")
{
alert("Both dates must be entered.");
return false;
}
else
{
//alert("To date must occur after the from date.");
return false;
}
}
}
// above functions block checks dates with combo


function CheckFileExtension(FileName,FileType)
{

//alert(FileName.value);
//alert(FileType);
sFileType = Right(FileName.value,4);
sFileType = sFileType.toLowerCase();
if (sFileType != FileType )
{
FileName.focus();
return false;
}
else
return true;
}

function Right(str, n)
{
/* This Function Returns n number of right letters of String.
Used mostly in file extension checking.
*/
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
{
var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);
}
}

//Developed by mishal
function validateWebSite(WebSite)
{
var RegExp = /[w]\.(\w+)\.(\w+)/i;


if(WebSite.value.match(RegExp))
{
return true;
}
else
{
WebSite.focus();
alert('Invalid WebSite Name');
return false;
}

}
// Developed by Mishal
function FixedPoint(str,Precision)
{
var ValPart = str.split('.');
if (ValPart.length > 1)
{
if (ValPart[1].length >= Precision)
return ValPart[0] + "." + ValPart[1].substr(0, Precision);
else
{
for (var i = ValPart[1].length; i < Precision; i++)
{
ValPart[1] = ValPart[1] + "0";
}
return ValPart[0] + "." + ValPart[1];
}
}
else
{
var valpart = "";
for (var i = 0; i < Precision; i++)
{
valpart = valpart + "0";
}
return str + "." + valpart;
}
}

//Developed by Sunil
function checkempty1(objname)
{
if (trim(objname.value)=="")
{
return false
}
return true;
}

function getInt(objInt)
{
if (isNaN(trim(objInt.value)))
{
alert("Please Enter a Valid Number");
alert("hello");
objInt.select();
objInt.focus();
return false;
}
else
{
if(checkempty1(objInt))
{
retInt=parseInt(objInt.value);
return retInt;
}
else
{
return 0;
}
}
}

function getIntFromValue(objInt)
{
var retInt;
if (isNaN(trim(objInt)))
{
alert("Please Enter a Valid Number");
return false;
}
else
{
retInt=parseInt(objInt);
return retInt;
}
}

function getTwoDec(fieldValue)
{
decallowed = 2; // how many decimals are allowed?
var retTwoDec;

if (isNaN(fieldValue))
{
alert("Please Enter a Valid Number");

fieldName.select();
fieldName.focus();
return false;
}
else
{
if (fieldValue.indexOf('.') != -1)
{
//if (fieldValue.indexOf('.') == 0) fieldValue += ".00";
var decvalue=String(fieldValue)
dectext = fieldValue.substring(fieldValue.indexOf('.'), 2);

inttext = fieldValue.substring(0,fieldValue.indexOf('.'));
if (dectext.length > decallowed)
{
if(getIntFromValue(dectext.substring(3,2))>=5)
{
dectext = getIntFromValue(dectext.substring(0,2))+1
}
else
{
dectext = dectext.substring(0,2);
}
retTwoDec = inttext + "."+ dectext;
return retTwoDec;
}
else
{
retTwoDec = inttext + "."+ dectext;
return retTwoDec;
}
}
else
{
return fieldValue;
}
}
}

function getIntOrDec(fieldValue,fieldName)
{
decallowed = 2; // how many decimals are allowed?
// retTwoDec;
if(fieldValue=="")
{
fieldValue="1";
return fieldValue;
}

if (isNaN(fieldValue))
{
alert("Please Enter a Valid Number");
fieldName.focus();
return false;
}
else
{

if (fieldValue.indexOf('.') != -1)
{
dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);

inttext = fieldValue.substring(0,fieldValue.indexOf('.'));
if (dectext.length > decallowed)
{
if(getIntFromValue(dectext.substring(3,2))>=5)
{
dectext = getIntFromValue(dectext.substring(0,2))+1
}
else
{
dectext = dectext.substring(0,2);
}
retTwoDec = inttext + "."+ dectext;
return retTwoDec;
}
else
{
retTwoDec = inttext + "."+ dectext;
return retTwoDec;
}
}
else
{
fieldValue=parseInt(fieldValue);
return fieldValue;
}
}
}

function getIntOrDec1(fieldValue,fieldName)
{
if(fieldValue=="")
{
fieldValue="1";
//return fieldValue;
}
if (isNaN(fieldValue))
{
alert("Please Enter a Valid Number");
fieldName.focus();
return false;
}
else
{
return fieldValue;
}
}

function getMultiply(fieldValue1,fieldValue2)
{
if(fieldValue1=="1" && fieldValue2 =="1")
{
fieldValue="0";
return fieldValue;
}
if(fieldValue1!="1" && fieldValue2 =="1")
{
fieldValue2="0";
}
fieldValue=fieldValue1*fieldValue2;
return fieldValue;
}

function getTotalA(fieldValue1,fieldValue2,fieldValue3,fieldValue4,fieldValue5,fieldValue6,fieldValue7,fieldValue8,fieldValue9,fieldValue10,fieldValue11)
{
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
if(fieldValue4=="") fieldValue4="0";
if(fieldValue5=="") fieldValue5="0";
if(fieldValue6=="") fieldValue6="0";
if(fieldValue7=="") fieldValue7="0";
if(fieldValue8=="") fieldValue8="0";
if(fieldValue9=="") fieldValue9="0";
if(fieldValue10=="") fieldValue10="0";
if(fieldValue11=="") fieldValue11="0";
var ret=parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)+parseFloat(fieldValue4)+parseFloat(fieldValue5)+parseFloat(fieldValue6)+parseFloat(fieldValue7)+parseFloat(fieldValue8)+parseFloat(fieldValue9)+parseFloat(fieldValue10)+parseFloat(fieldValue11);

return ret;
}

function getServiceTaxMain(fieldValue1,fieldValue2,fieldValue3,fieldValue4,fieldValue5,fieldValue6,fieldValue7,fieldValue8,fieldValue9,fieldValue10,fieldValue11)
{
var ret;
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
if(fieldValue4=="") fieldValue4="0";
if(fieldValue5=="") fieldValue5="0";
if(fieldValue6=="") fieldValue6="0";
if(fieldValue7=="") fieldValue7="0";
if(fieldValue8=="") fieldValue8="0";
if(fieldValue9=="") fieldValue9="0";
if(fieldValue10=="") fieldValue10="0";
if(fieldValue11=="") fieldValue11="0";
if(fieldValue1 == "" && fieldValue2 == "" && fieldValue3 == "" && fieldValue4 == "" && fieldValue5 == "" && fieldValue6 == "" && fieldValue7 == "" && fieldValue8 == "" && fieldValue9 == "" && fieldValue10 == "" && fieldValue11 == "")
{
ret= "0";

return ret;
}
alert(fieldValue1);
alert(fieldValue2);
alert(fieldValue3);
alert(fieldValue4);
alert(fieldValue5);
alert(fieldValue6);
alert(fieldValue7);
alert(fieldValue8);
alert(fieldValue9);
alert(fieldValue10);
// ret=((parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)+parseFloat(fieldValue4)+parseFloat(fieldValue5)+parseFloat(fieldValue6)+parseFloat(fieldValue7)+parseFloat(fieldValue8)+parseFloat(fieldValue9)+parseFloat(fieldValue10))*parseFloat(fieldValue11))/100;
ret=((eval(fieldValue1)+eval(fieldValue2)+eval(fieldValue3)+eval(fieldValue4)+eval(fieldValue5)+eval(fieldValue6)+eval(fieldValue7)+eval(fieldValue8)+eval(fieldValue9)+eval(fieldValue10))*eval(fieldValue11))/100;
alert((eval(fieldValue1)+eval(fieldValue2)+eval(fieldValue3)+eval(fieldValue4)+eval(fieldValue5)+eval(fieldValue6)+eval(fieldValue7)+eval(fieldValue8)+eval(fieldValue9)+eval(fieldValue10)));
return ret;
}

function getTotalB(fieldValue1,fieldValue2)
{
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
var ret=parseFloat(fieldValue1)+parseFloat(fieldValue2);

return ret;
}

function getTotalC(fieldValue1,fieldValue2,fieldValue3,fieldValue4,fieldValue5,fieldValue6,fieldValue7,fieldValue8,fieldValue9,fieldValue10,fieldValue11,fieldValue12,fieldValue13,fieldValue14,fieldValue15,fieldValue16,fieldValue17)
{
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
if(fieldValue4=="") fieldValue4="0";
if(fieldValue5=="") fieldValue5="0";
if(fieldValue6=="") fieldValue6="0";
if(fieldValue7=="") fieldValue7="0";
if(fieldValue8=="") fieldValue8="0";
if(fieldValue9=="") fieldValue9="0";
if(fieldValue10=="") fieldValue10="0";
if(fieldValue11=="") fieldValue11="0";
if(fieldValue12=="") fieldValue12="0";
if(fieldValue13=="") fieldValue13="0";
if(fieldValue14=="") fieldValue14="0";
if(fieldValue15=="") fieldValue15="0";
if(fieldValue16=="") fieldValue16="0";
if(fieldValue17=="") fieldValue17="0";
var ret=parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)+parseFloat(fieldValue4)+parseFloat(fieldValue5)+parseFloat(fieldValue6)+parseFloat(fieldValue7)+parseFloat(fieldValue8)+parseFloat(fieldValue9)+parseFloat(fieldValue10)+parseFloat(fieldValue11)+parseFloat(fieldValue12)+parseFloat(fieldValue13)+parseFloat(fieldValue14)+parseFloat(fieldValue15)+parseFloat(fieldValue16)+parseFloat(fieldValue17);

return ret;
}

function getTotalD(fieldValue1,fieldValue2,fieldValue3,fieldValue4)
{
var ret;
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
if(fieldValue4=="") fieldValue4="0";
if(fieldValue1 == "" && fieldValue2 == "" && fieldValue3 == "" && fieldValue4 == "")
{
ret= "0";
return ret;
}
ret=parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)+parseFloat(fieldValue4);

return ret;
}

function getSerTax(fieldValue1,fieldValue2,fieldValue3)
{
//alert("1");
var ret;
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
//alert("2");
if(fieldValue1 == "" && fieldValue2 == "" && fieldValue3 == "")
{
// alert("3");
ret= "0";

ret=parseFloat(ret)*0.1236;
// alert("4");
return ret;
}
ret=parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)*0.1236;
//alert(ret);
return ret;
}

function getGrantTotal(fieldValue1,fieldValue2,fieldValue3,fieldValue4,fieldValue5,fieldValue6)
{
if(fieldValue1=="") fieldValue1="0";
if(fieldValue2=="") fieldValue2="0";
if(fieldValue3=="") fieldValue3="0";
if(fieldValue4=="") fieldValue4="0";
if(fieldValue5=="") fieldValue5="0";
if(fieldValue6=="") fieldValue6="0";
var ret=parseFloat(fieldValue1)+parseFloat(fieldValue2)+parseFloat(fieldValue3)+parseFloat(fieldValue4)+parseFloat(fieldValue5)+parseFloat(fieldValue6);

return ret;
}

function CheckIntOrDec(fieldName,fieldValue)
{
if (isNaN(fieldValue))
{
alert("Please Enter a Valid Number");
fieldName.select();
fieldName.focus();
return false;
}
else
{
return true;
}
}

Important code and Script

+++++++++++++ Print in next page +++++++++++++++++++
Print in next page
style="page-break-before: always
++++++++ Opending popup ++++++++++++++
dfsdfdsf anup
dfsdfdsf anup

++++++++++++++++++++++
sys.objects
type type_desc
C CHECK_CONSTRAINTD DEFAULT_CONSTRAINTF FOREIGN_KEY_CONSTRAINTFN SQL_SCALAR_FUNCTIONIT INTERNAL_TABLEP SQL_STORED_PROCEDUREPK PRIMARY_KEY_CONSTRAINTS SYSTEM_TABLESQ SERVICE_QUEUETF SQL_TABLE_VALUED_FUNCTIONU USER_TABLE
++++++ Delete all procedure and function +++++++++++++++++
Select 'Dxrop Procedure ' + name from sys.procedures Where [type] = 'P'Select 'Dxrop tables ' + name from sys.tables Where [type] = 'U'select * from sys.objects Where [type] = 'U'select * from sys.objects Where [type] = 'P'select * from sys.objects Where [type] = 'FN'
++++++++++++++++++++++++ Read page View source code ++++++++++++++++++
http://www.devasp.net/net/articles/display/994.html
++++++++++++++++++++++++ bind two filld in one lable of grid ++++++++++++++++++
'>
++++++++++++++++ Validation message +++++++++++++++
http://sandblogaspnet.blogspot.com/2009/04/hideshow-validator-callout-control.html
+++++++++++++++++++ Back Button ++++++++++++++++++++++

++++++++++++++++ Get SP according to Table Name ++++++++++++++++++++
select obj.Name, * from syscomments cmLeft outer join sys.objects obj on cm.id=obj.object_idwhere cm.text like '%dbo%'
select * from syscomments where text like '%ckr_tblclaims_mst%'
++++++++++++++++ Testing HTML page ++++++++++++++++++++
http://validator.w3.org/
+++++++++++++Display SP list according modified date descending++++++++++++++++
SELECT name, create_date, modify_dateFROM sys.objectsWHERE type = 'P' order by modify_date desc
+++++++++ Display Table list according modified date ++++++++++++++++++++
SELECT name, create_date, modify_dateFROM sys.objectsWHERE type = 'U' order by modify_date desc
+++++++++++++++++++++++
use the asp.net variable in javascript
var jVarName;jVarName = '<%#aVarName%>';

++++++++++++++++++++ insert script procedure ms sql server 2000 +++++++++++++++++++++++++++++
create PROC sp_DataAsInsCommand ( @TableList varchar (8000))ASSET NOCOUNT ONDECLARE @position int, @exec_str varchar (2000), @TableName varchar (50)DECLARE @name varchar(128), @xtype int, @status tinyint, @IsIdentity tinyintSELECT @TableList = @TableList + ','SELECT @IsIdentity = 0SELECT @position = PATINDEX('%,%', @TableList)WHILE (@position <> 0) BEGIN
SELECT @TableName = SUBSTRING(@TableList, 1, @position - 1) SELECT @TableList = STUFF(@TableList, 1, PATINDEX('%,%', @TableList),'') SELECT @position = PATINDEX('%,%', @TableList)
SELECT @exec_str = 'DECLARE fetch_cursor CURSOR FOR ' + 'SELECT a.name, a.xtype, a.status FROM syscolumns a, sysobjects b WHERE a.id = b.id and b.name = ''' + @TableName + '''' EXEC (@exec_str) OPEN fetch_cursor FETCH fetch_cursor INTO @name, @xtype, @status IF (@status & 0x80) <> 0 BEGIN SELECT @IsIdentity = 1 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON' SELECT 'GO' END SELECT @exec_str = "SELECT 'INSERT INTO " + @TableName + " VALUES (' + " Select ' -- The table name is: ' + @TableName --text or ntext IF (@xtype = 35) OR (@xtype = 99) SELECT @exec_str = @exec_str + '''"None yet"''' ELSE
--image IF (@xtype = 34) SELECT @exec_str = @exec_str + '"' + '0xFFFFFFFF' + '"' ELSE
--smalldatetime or datetime IF (@xtype = 58) OR (@xtype = 61) SELECT @exec_str = @exec_str + 'Coalesce(' + ' + ''"'' + ' + ' + CONVERT(varchar,' + @name + ',101)' + ' + ''"''' + ',"null")' ELSE
--varchar or char or nvarchar or nchar IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239) SELECT @exec_str = @exec_str + 'Coalesce(' + '''"'' + ' + @name + ' + ''"''' + ',"null")' ELSE
--uniqueidentifier IF (@xtype = 36) SELECT @exec_str = @exec_str + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''"''' + ',"null")' ELSE
--binary or varbinary IF (@xtype = 173) OR (@xtype = 165) SELECT @exec_str = @exec_str + '"' + '0x0' + '"' ELSE
SELECT @exec_str = @exec_str + 'Coalesce(CONVERT(varchar,' + @name + '), "null")'
WHILE @@FETCH_STATUS <> -1 BEGIN FETCH fetch_cursor INTO @name, @xtype, @status IF (@@FETCH_STATUS = -1) BREAK IF (@status & 0x80) <> 0 BEGIN SELECT @IsIdentity = 1 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON' SELECT 'GO' END
--text or ntext IF (@xtype = 35) OR (@xtype = 99) SELECT @exec_str = @exec_str + ' + ","' + ' + ''"None yet"''' ELSE
--image IF (@xtype = 34) SELECT @exec_str = @exec_str + ' + "," + ' + '"' + '0xFFFFFFFF' + '"' ELSE
--smalldatetime or datetime IF (@xtype = 58) OR (@xtype = 61) SELECT @exec_str = @exec_str + ' + ","' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar,' + @name + ',101)' + ' + ''"''' + ',"null")' ELSE
--varchar or char or nvarchar or nchar IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239) SELECT @exec_str = @exec_str + ' + ","' + ' + Coalesce(''"'' + ' + @name + ' + ''"''' + ',"null")' ELSE
--uniqueidentifier IF (@xtype = 36) SELECT @exec_str = @exec_str + ' + ","' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''"''' + ',"null")' ELSE
--binary or varbinary IF (@xtype = 173) OR (@xtype = 165) SELECT @exec_str = @exec_str + ' + "," + ' + '"' + '0x0' + '"' ELSE
SELECT @exec_str = @exec_str + ' + ","' + ' + Coalesce(CONVERT(varchar,' + @name + '), "null")' END
CLOSE fetch_cursor DEALLOCATE fetch_cursor
SELECT @exec_str = @exec_str + '+ ")" FROM ' + @TableName EXEC(@exec_str)-- print (@exec_str) SELECT 'GO'
IF @IsIdentity = 1 BEGIN SELECT @IsIdentity = 0 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' OFF' SELECT 'GO' END END





----------- execute dynamic Query ---------------
EXEC ("DROP TRIGGER " + @chvTrigger)
-------- Use of sysobjects classs ------------------
select * from sysobjectswhere type='p'
C = check constraint;D = default;F = foreign key constraint;L = transaction log;P = stored procedure;K = primary key or unique constraint;R rule;RF = replication stored procedure;S = system table;TR = trigger;U = user table;V = view;X = extended stored procedure
--------------------------
How to know MDF and LDF file location of database
Select * from sysfiles
------------ customize Scrollbar --------------------
http://www.hesido.com/web.php?page=customscrollbar
--------------- table list which have field name is phone ------------
--- note properly tested
SELECT sys.objects. name FROM sys.objects INNER JOIN sys.columns ON sys.objects.object_id = sys.columns. object_id WHERE sys.objects.type = 'U' AND sys. columns. name = 'Phone';
------- Quick Starts ---------------------------
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspx
-----------------Trace network -----------------
http://network-tools.com/default.asp?prog=trace&host=203.199.89.172
------------ Insert Query generate procedure -----------------
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGO ALTER PROC [dbo].[sp_DataAsInsCommand] ( @TableList varchar (8000), @where varchar(8000) = '')ASSET NOCOUNT ONDECLARE @position int, @exec_str varchar (2000), @TableName varchar (50)DECLARE @name varchar(128), @xtype int, @status tinyint, @IsIdentity tinyintSELECT @TableList = @TableList + ','SELECT @IsIdentity = 0SELECT @position = PATINDEX('%,%', @TableList)WHILE (@position <> 0) BEGIN SELECT @TableName = SUBSTRING(@TableList, 1, @position - 1) SELECT @TableList = STUFF(@TableList, 1, PATINDEX('%,%', @TableList),'') SELECT @position = PATINDEX('%,%', @TableList) SELECT @exec_str = 'DECLARE fetch_cursor CURSOR FOR ' + 'SELECT a.name, a.xtype, a.status FROM syscolumns a, sysobjects b WHERE a.id = b.id and b.name = ''' + @TableName + ''''
EXEC (@exec_str) OPEN fetch_cursor FETCH fetch_cursor INTO @name, @xtype, @status IF (@status & 0x80) <> 0 BEGIN SELECT @IsIdentity = 1 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON' SELECT 'GO' END SELECT @exec_str = 'SELECT ''INSERT INTO ' + @TableName + ' VALUES ('' + '
--Select ' -- The table name is: ' + @TableName --text or ntext IF (@xtype = 35) OR (@xtype = 99) begin SELECT @exec_str = @exec_str + '''"None yet"''' print @exec_str end ELSE --image IF (@xtype = 34) begin SELECT @exec_str = @exec_str + '"' + '0xFFFFFFFF' + '"' end ELSE --smalldatetime or datetime IF (@xtype = 58) OR (@xtype = 61) begin SELECT @exec_str = @exec_str + 'Coalesce(' + ' + ''"'' + ' + ' + CONVERT(varchar,' + @name + ',113)' + ' + ''"''' + ')' end ELSE --varchar or char or nvarchar or nchar IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239) SELECT @exec_str = @exec_str + 'Coalesce(' + '''"'' + ' + @name + ' + ''"''' + ',''null'')' ELSE --uniqueidentifier IF (@xtype = 36) SELECT @exec_str = @exec_str + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''"''' + ',''null'')' ELSE --binary or varbinary IF (@xtype = 173) OR (@xtype = 165) begin SELECT @exec_str = @exec_str + '"' + '0x0' + '"' print @exec_str end ELSE SELECT @exec_str = @exec_str + 'Coalesce(CONVERT(varchar,' + @name + '), ''null'')'
WHILE @@FETCH_STATUS <> -1 BEGIN FETCH fetch_cursor INTO @name, @xtype, @status IF (@@FETCH_STATUS = -1) BREAK IF (@status & 0x80) <> 0 BEGIN SELECT @IsIdentity = 1 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON' SELECT 'GO' END --text or ntext IF (@xtype = 35) OR (@xtype = 99) SELECT @exec_str = @exec_str + ' + '',''' + ' + ''"None yet"''' ELSE --image IF (@xtype = 34) begin SELECT @exec_str = @exec_str + ' + '','' + ' + '"' + '0xFFFFFFFF' + '"' end ELSE --smalldatetime or datetime IF (@xtype = 58) OR (@xtype = 61) begin SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar,' + @name + ',113)' + ' + ''"''' + ',''null'')' end ELSE
--varchar or char or nvarchar or nchar IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239) begin SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + @name + ' + ''"''' + ',''null'')' end ELSE
--uniqueidentifier IF (@xtype = 36) begin SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''''''' + ',''null'')' end ELSE
--binary or varbinary IF (@xtype = 173) OR (@xtype = 165) begin SELECT @exec_str = @exec_str + ' + '','' + ' + '"' + '0x0' + '"' end ELSE begin SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(CONVERT(varchar,' + @name + '), ''null'')' end END CLOSE fetch_cursor DEALLOCATE fetch_cursor SELECT @exec_str = @exec_str + '+ '')'' FROM ' + @TableName if ltrim(rtrim(@where)) <> '' set @exec_str = @exec_str + ' where ' + @where set @exec_str = @exec_str + ' ORDER BY 1' set @exec_str = replace(@exec_str, '"', '''''') print @exec_str EXEC(@exec_str)-- print (@exec_str) --SELECT 'GO' IF @IsIdentity = 1 BEGIN SELECT @IsIdentity = 0 SELECT 'SET IDENTITY_INSERT ' + @TableName + ' OFF' --SELECT 'GO' END END


------------ Random password and s00000009 ------------------------
CREATE proc [dbo].[Pro_Insert_Seller_Reg] @User_Id bigint, @First_Name varchar(150), @Last_Name varchar(150), @Proffession_Id bigint, @Address varchar(800), @City varchar(100), @Country_Id bigint, @Seller_Email varchar(300), @Tel_No varchar(30), @Mobile_No varchar(50), @Professional_Body_Ref_No varchar(50), @Reference varchar(100), @Land_Reg_Certificate_Path varchar(100), @Id_License_Path varchar (100), @Utility_Bill_Path varchar(100), @Terms_Yn char(1), @Created_By varchar(50),@Income varchar(50),@Portfolio varchar(50),@Profession_Name varchar(100),@Lucum_Member_Yn varchar(3),@Lucum_No varchar(50) as Declare @User_No as varchar(10)
Declare @Password varchar(50) Declare @String char(62) SET @String = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
if exists (select User_Id from tblUser_Mst where Is_Deleted='N' and Type='Seller' and Email=@Seller_Email) begin raiserror('This Email already Exists.',16,1) return end

set @Password=SUBSTRING(SUBSTRING(@String,CONVERT(tinyint,RAND()*62)+1,1) + SUBSTRING(@String,CONVERT(tinyint,RAND()*62)+1,1) + SUBSTRING(@String,CONVERT(tinyint,RAND()*62)+1,1) + SUBSTRING(@String,CONVERT(tinyint,RAND()*62)+1,1) + SUBSTRING(@String,CONVERT(tinyint,RAND()*62)+1,1),1,CONVERT(tinyint,RAND()*5)+6)
Begin tran t1 if(@Proffession_Id=0) begin if exists (Select * from tblProfession where Is_Deleted='N' and Profession=@Profession_Name) begin raiserror('Profession already exists.',16,1) return end select @Proffession_Id=isnull(Max(Profession_Id),0)+1 from tblProfession insert into tblProfession(Profession_Id,Profession,Creation_Date,Created_By,Is_Deleted) values(@Proffession_Id,@Profession_Name,getdate(),'Seller','N') end if @@ERROR=0 begin set @User_No = 'S'+replace(str(@User_Id,9),' ','0') Insert into tblUser_Mst(User_Id,User_No,Type,Login_Name,Password,Email,Approved_Yn,Created_By) values(@User_Id,@User_No,'Seller',@User_No,@Password,@Seller_Email,'N',@Created_by) Insert Into tblSeller_Mst ( User_Id, User_No, First_Name, Last_Name, Proffession_Id, Address, City, Country_Id, Seller_Email, Tel_No, Mobile_No, Professional_Body_Ref_No, Reference, Land_Reg_Certificate_Path, Id_License_Path , Utility_Bill_Path, Terms_Yn, Created_By,Income,Portfolio,Lucum_Member_Yn,Lucum_No ) values ( @User_Id, @User_No, @First_Name, @Last_Name, @Proffession_Id, @Address, @City, @Country_Id, @Seller_Email, @Tel_No, @Mobile_No, @Professional_Body_Ref_No, @Reference, @Land_Reg_Certificate_Path, @Id_License_Path , @Utility_Bill_Path, @Terms_Yn, @Created_By,@Income,@Portfolio,@Lucum_Member_Yn,@Lucum_No ) commit tran t1 End else begin rollback tran t1 end------------------- alter table script for oracle --------------
alter table testdataadd(address varchar2(500));
alter table testdatadrop(address,homephone);
------------------ Convert To Decimal -----------------------
Convert.ToDecimal(ds.Tables[2].Rows[0]["Total_Price_Without_Discount"].ToString()).ToString("#0.00")
-------------------- Dynamically Create Data Table ------------------------ try { if (ViewState["dtProduct"] != null) { DataTable dtProduct = (DataTable)ViewState["dtProduct"]; if (dtProduct.Rows.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("Spl_Price_Id"); dt.Columns.Add("Product_Code"); dt.Columns.Add("Brand_Name"); dt.Columns.Add("Description"); dt.Columns.Add("User_Name"); //name dt.Columns.Add("Base_Price"); dt.Columns.Add("Special_Price");
for (int i = 0; i < dtProduct.Rows.Count; i++) { DataRow dr = dt.NewRow(); dr["Spl_Price_Id"] = dtProduct.Rows[i]["Spl_Price_Id"].ToString().Trim(); dr["Product_Code"] = dtProduct.Rows[i]["Product_Code"].ToString().Trim(); dr["Brand_Name"] = dtProduct.Rows[i]["Brand_Name"].ToString().Trim(); dr["Description"] = dtProduct.Rows[i]["Description"].ToString().Trim(); dr["User_Name"] = dtProduct.Rows[i]["name"].ToString().Trim(); dr["Base_Price"] = dtProduct.Rows[i]["Base_Price"].ToString().Trim(); dr["Special_Price"] = dtProduct.Rows[i]["Special_Price"].ToString().Trim(); dt.Rows.Add(dr); } commonFunctions.ExportToExcel_DT(dt, "CardinalUser_SpecialPrice", HttpContext.Current.Response);
//DataTable dt = (DataTable)ViewState["dtProduct"]; //CommonFunction.ExportToExcel("RFD_List", HttpContext.Current.Response, tdDetail); //}
} } } catch (Exception ex) { lblMessage.Text = "Error! " + ex.Message.ToString(); }
----------------------SQL function , cursor return string-------------------------
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER FUNCTION [dbo].[Fun_TargetAudiance]( @Product_Id bigint)RETURNS varchar(8000)ASBEGINDECLARE @Sum varchar(2000)DECLARE @total varchar(200)
set @Sum=''DECLARE contact_cursor CURSOR FOR
select TAM.TargetAudiance from Sk_tbl_Product_TargetA_Relation_Mst TRMinner join Sk_tbl_Product_Target_Aud_Mst TAM on TAM.TargetAId=TRM.TargetAudId where TRM.ProductId=@Product_Id and TRM.is_deleted='N'
OPEN contact_cursor
-- Perform the first fetch.FETCH NEXT FROM contact_cursor into @total
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.WHILE @@FETCH_STATUS = 0BEGIN -- This is executed as long as the previous fetch succeeds. if(@Sum ='') begin set @Sum=@Sum+@total end else begin set @Sum=@Sum+'
'+@total end
-- print(@total) -- print (@Sum) FETCH NEXT FROM contact_cursor into @totalEND
CLOSE contact_cursorDEALLOCATE contact_cursor--print @Sum
RETURN @Sum
END

----------------------- Row Command in Gridveiw and Retriving Data -------------------------
protected void dgv_RowCommand(object sender, GridViewCommandEventArgs e) { //tracert
if (e.CommandName == "add") {
GridViewRow rw = (GridViewRow)(((Button)e.CommandSource).NamingContainer); string id = ((Label)rw.FindControl("lblId")).Text.Trim();
string Description = ((Label)rw.FindControl("lblDescription")).Text.Trim();
}
}

--------------------- Date Wise Filter -------------------------
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER procedure [dbo].[Pro_Select_Seller_Property_view_status_By_PropertId] @Property_id bigint , @FromDate varchar(100), @ToDate varchar(100) as Declare @Sql varchar(3000) Declare @DateFilter varchar(500) set @Sql='' set @DateFilter='' if (@FromDate <>'') begin set @DateFilter=' and convert(datetime,convert(varchar, svs.Creation_date,101),101) >=CONVERT(datetime, '''+@FromDate+''',101) ' end if (@ToDate <>'') begin set @DateFilter=' and convert(datetime,convert(varchar, svs.Creation_date,101),101) <=CONVERT(datetime, '''+@ToDate+''',101) ' end if (@FromDate <>'' and @ToDate <>'') begin set @DateFilter=' and convert(datetime,convert(varchar, svs.Creation_date,106),106) between CONVERT(datetime, '''+@FromDate+''',101) and CONVERT(datetime,'''+@ToDate+''',101) ' end set @Sql =' Select svs.User_Id, svs.Property_Id, CONVERT(VARCHAR(9), svs.Creation_date, 6) as Creation_date, um.User_No,um.Type, dbo.Fun_User_First_Name(svs.User_Id) as first_name, dbo.Fun_User_Last_Name(svs.User_Id) as last_name from tblSeller_Property_view_status svs Left outer join tblUser_Mst um on svs.user_id = um.user_id where svs.is_deleted=''N''' if (@Property_id <>0) begin set @Sql=@Sql+ 'and svs.property_id='+convert(varchar,@Property_id) end set @Sql=@Sql +@DateFilter set @Sql=@Sql + ' order by svs.Creation_date desc ' exec (@sql)


-------- calling server side event from javascript ------------
----> javascript function
function Test() { __doPostBack('AutoProceed', 'AutoProceed_Click'); return false; }
page load Statement , Not write code is postback==false
this.GetPostBackEventReference(AutoProceed);

------------- selecting random record from table sql server -----------------------
SELECT TOP 1 column FROM tableORDER BY NEWID()
------------- Clearing a transaction log ------------------http://blogs.acceleration.net/ryan/archive/2004/09/09/285.aspx

Log files can sometimes get out of control and use up too much space.This tends to be a problem when testing import scripts that do a lot of operations, then rollback, you can get crazy log file sizes. Here's how to clear them:
1. Open up Query analyzer, connected as a user with admin priveleges. 2. Run this query, substituting "db_name" with the proper database name:
BACKUP LOG db_name WITH NO_LOG GO DBCC SHRINKDATABASE( db_name, 0) GO
3. Check the size of the log file
Don't do this when the transaction log is important, though. Anyone know of a better way to do this?

---------------- lighbox --------------------------
http://www.emanueleferonato.com/2007/08/22/create-a-lightbox-effect-only-with-css-no-javascript-needed/
------------ calucation ---------------------
http://www.easycalculation.com/
----------- Datetime formate , Display indian date formate ---------------
select convert(varchar(11), getdate(), 113) + right(convert(varchar(20), getdate(), 100), 8)
---------------------------
contactation multiple filed in one colulmn of grid
Name: ' >
---------------------------
http://www.sqlteam.com/forums/pop_profile.asp?mode=display&id=54513
--------------------------
GREYBOX LINK
http://dev.xoofoo.org/modules/content/dd/d42/a00109_79286ac9f6301556a2622cc9f12e6ad8.html
--------------------------
Uploader Demo
http://ajaxuploader.com/Demo/default.aspx ----------------- Contacatation with eval Method ------------------- '>

--------------- Display upload document in Grid --------------------
function View_PortFolio(FileName) { size = "left=150,top=50,status=0,toolbar=0,menubar=0,directories =0,resizable =1,scrollbars=1,height=500,width=500" window.open("/Common/Seller_Documents/PortFolio/" +FileName,"document",size); }
')" ><%# DataBinder.Eval(Container, "DataItem.Employee_PortFolio")%>

------------- UPlaod File of specific size , check upload file size ----------------
if (fileuploadpropimages.HasFile) { // return No of Byte long len = fileuploadpropimages.PostedFile.ContentLength; //1048576= 1024 * kb(1024 byte) if (len > 2 * 1048576) throw (new Exception("Uploaded image is more then 2 MB."));
string path = Server.MapPath("/Sales/PropertyMainImage/"); if (lblMainImgPath.Text.Trim() != "no_image_2.gif") { if (File.Exists(path + lblMainImgPath.Text.Trim())) File.Delete((path + lblMainImgPath.Text.Trim())); } string Name = hidProperty_Id.Value + "_PropMainImage_" + fileuploadpropimages.FileName; oPropertySeller.PropertyMainImagePath = Name; fileuploadpropimages.SaveAs(path + Name); }
----------- Write Script in CS Code ----------------- String s = ""; Type cstype = this.GetType(); ClientScriptManager cs = Page.ClientScript; cs.RegisterClientScriptBlock(cstype, s, s.ToString());
-------- SQL server 2005 Declare Decimal ----------
Max_Rate decimal no 9 14 4
convert to two digit decimal
Convert(Decimal(14,2),J.Max_Rate)As Max_Rate
----------------- IDS table 2005 --------------------------------
CREATE TABLE [dbo].[tblDriiem_Ids]( [table_name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [column_name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [fid] [bigint] NULL, [id] [bigint] NOT NULL)
CREATE PROCEDURE Pro_Get_Ids( @newid bigint OUTPUT, @table_name varchar(100), @column_name varchar(100))ASBEGIN

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRANSACTIONdeclare @oldid bigint
if not exists(select * from tblDriiem_Ids with (NOLOCK) where table_name = @table_name and column_name = @column_name) BEGIN insert into tblDriiem_Ids(table_name, column_name, id) values (@table_name, @column_name, 1) set @newid=1 ENDELSEbegin set @oldid = (select id from tblDriiem_Ids with (NOLOCK) where table_name = @table_name and column_name = @column_name) set @newid = @oldid + 1 end
update tblDriiem_Ids set id = @newid where table_name = @table_name and column_name = @column_name COMMIT TRANSACTIONEND

public static Int64 GenerateId(string TableName,string ColumnName,SqlConnection conn) { SqlParameter[] Params=new SqlParameter[3]; string strSql ;
Params[0] = new SqlParameter("@newid", SqlDbType.BigInt, 8, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Default, 1); Params[1] = new SqlParameter("@table_name", TableName); Params[2] = new SqlParameter("@column_name", ColumnName);
strSql = "Pro_Get_Ids"; SqlHelper.ExecuteNonQuery(conn, CommandType.StoredProcedure, strSql, Params); return Convert.ToInt64(Params[0].Value); }

------------- removing HTML tag from string ----------------------
using System.Text.RegularExpressions;
string strResult=Regex.Replace(ds.Tables[0].Rows[i]["txtContent"].ToString(), @"<(.\n)*?>", string.Empty);
int iPosition = strResult.IndexOf(".");
//if (strResult.Length > 100) //{ // strResult = strResult.Substring(0, 100); //}
if (iPosition > 0) { iPosition++; strResult = strResult.Substring(0, iPosition); }
strResult = Regex.Replace(strResult, strSearchContent, "" + strSearchContent + "", RegexOptions.IgnoreCase); ds.Tables[0].Rows[i]["txtContent"] = strResult;
------- How to retrive value of session in javascript ------------var MyClientSideVar = '<%= Session["UserId"]%>';
------- for connection create UDL file -----------------
conn.udl
---------- copy data/ Back up of data -------------------------
select * into bck_tblProperty_Admin from tblProperty_Admin
---------- Deleting duplicate record -------------------------set rowcount 1delete tblProperty_Adminfrom tblProperty_Admin awhere (select count(*) from tblProperty_Admin b where b.property_id=a.property_id)>1while @@rowcount >0delete tblProperty_Adminfrom tblProperty_Admin awhere(select count(*) from tblProperty_Admin b where b.property_id=a.property_id )>1set rowcount 0
---------- Create a connection file -------------------------conn.udl------------------------ ---------------------
"C:\Program Files\Internet Explorer\iexplore.exe" http://localhost:2609/Test_Proj/bpcl_tt.aspx"C:\Program Files\Internet Explorer\iexplore.exe" http://localhost:2609/Test_Proj/bpcl_tt.aspx
--------------- country Code --------------------
http://www.worldatlas.com/aatlas/ctycodes.htm

----------- insert, update and delete data of another server ----------------------
select * from OPENDATASOURCE('SQLOLEDB','server=209.62.85.76;UID=fastdbtrack;PWD=P8z4BqM').dbfast.fastdbtrack.test_Emp
insert into OPENDATASOURCE('SQLOLEDB','server=209.62.85.76;UID=fastdbtrack;PWD=P8z4BqM').dbfast.fastdbtrack.test_Empvalues (1,'test')
insert into OPENDATASOURCE('SQLOLEDB','server=209.62.85.76;UID=fastdbtrack;PWD=P8z4BqM').dbfast.fastdbtrack.test_Empvalues (2,'test1')
update OPENDATASOURCE('SQLOLEDB','server=209.62.85.76;UID=fastdbtrack;PWD=P8z4BqM').dbfast.fastdbtrack.test_Empset emp_Name='anup'where emp_no=1
delete from OPENDATASOURCE('SQLOLEDB','server=209.62.85.76;UID=fastdbtrack;PWD=P8z4BqM').dbfast.fastdbtrack.test_Empwhere emp_no=1
---------------------- create connection with another server ---------------------
sp_configure 'show advanced options', 1RECONFIGURE WITH OVERRIDE;

sp_configure 'Ad Hoc Distributed Queries', 1RECONFIGURE WITH OVERRIDE;
select * from OPENROWSET('SQLOLEDB','server=78.109.163.104,1334;UID=sa;PWD=OoB4qHgh','select * from driiem.dbo.tblBundle_Type')t1

++++++++++++++++++
ShowDialog for Value Passing
http://www.codeproject.com/KB/aspnet/Modal_Dialog.aspx
++++++++++ Pass two value in anchore +++++++++++++++++
&qty=<%# DataBinder.Eval(Container.DataItem,"Quantity")%> "> <%#DataBinder.Eval(Container.DataItem, "OrderNumber")%>
+++++++++ How to add Multiple Button in Grid ++++++++++++++++







protected void dgDateList_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Edit") { string date = e.CommandArgument.ToString(); string zId = e.Item.Cells[1].Text; string rId = e.Item.Cells[3].Text; string pId = e.Item.Cells[5].Text; string date = e.Item.Cells[6].Text; string sId = e.Item.Cells[7].Text; Response.Redirect("frmAddEdit_Gadget.aspx?sId=" + sId + "&zId=" + zId + "&rId=" + rId + "&pId=" + pId + "&date=" + date);
} if (e.CommandName == "Detail") { string zId = e.Item.Cells[1].Text; string rId = e.Item.Cells[3].Text; string pId = e.Item.Cells[5].Text; string date = e.Item.Cells[6].Text; string sId = e.Item.Cells[7].Text; Button btnDetail = (Button)e.Item.FindControl("btnDetail"); btnDetail.Attributes.Add("onclick", "ViewDetail('" + sId + "','" + zId + "','" + rId + "','" + pId + "','" + date + "')");
} }
=============
VARIABLE cus1 REFCURSOR;EXEC scott.she_Plant_Select_list (:cus1,0,0);print :cus1================
How to blank Database
SELECT * FROM SYSOBJECTS WHERE TYPE='u'
=========
Formating Editor
D:\Project Work\Driiem\DriiemProj\Admin\FCKeditor\fckconfig.js
===========
Google Map Example
http://secure.google.maps/ on ssl
Register URLhttp://code.google.com/apis/maps/signup.html
http://code.google.com/apis/maps/documentation/examples/
http://www.gorissen.info/Pierre/maps/googleMapLocation.php
http://www.gorissen.info/Pierre/maps/googleMapLocation.php
18.939939 72.835101
18.939939;72.835101
18.907645,72.805195
geotagged geo:lat=18.939939 geo:lon=72.835101

=============================
SELECT SUM(bytes)/1024/1024 "Meg" FROM DBA_DATA_FILESWHERE Tablespace_Name='USERS'
SELECT * FROM DBA_DATA_FILES


======================= function ViewComments(Path) { size = "left=150,top=50,height=750,width=770,resizable=no,scrollbars=yes"; window.open("She_Report_Fire_Drill.aspx?Id=" +Path,"document",size); }

==================
Re: script to generate all the tables and objects in a schema Posted: Jun 18, 2008 12:26 AM in response to: Sidhant Reply
Dear Sidhant,
Try this script:
set termout offset feedback offset serveroutput on size 100000spool ddl_schema.sqlbegindbms_output.put_line('--');dbms_output.put_line('-- DROP TABLES --');dbms_output.put_line('--'); for rt in (select tname from tab order by tname) loop dbms_output.put_line('DROP TABLE 'rt.tname' CASCADE CONSTRAINTS;'); end loop;end;/declare v_tname varchar2(30); v_cname char(32); v_type char(20); v_null varchar2(10); v_maxcol number; v_virg varchar2(1);begindbms_output.put_line('--');dbms_output.put_line('-- CREATE TABLES --');dbms_output.put_line('--'); for rt in (select table_name from user_tables order by 1) loop v_tname:=rt.table_name; v_virg:=','; dbms_output.put_line('CREATE TABLE 'v_tname' ('); for rc in (select table_name,column_name,data_type,data_length, data_precision,data_scale,nullable,column_id from user_tab_columns tc where tc.table_name=rt.table_name order by table_name,column_id) loop v_cname:=rc.column_name; if rc.data_type='VARCHAR2' then v_type:='VARCHAR2('rc.data_length')'; elsif rc.data_type='NUMBER' and rc.data_precision is null and rc.data_scale=0 then v_type:='INTEGER'; elsif rc.data_type='NUMBER' and rc.data_precision is null and rc.data_scale is null then v_type:='NUMBER'; elsif rc.data_type='NUMBER' and rc.data_scale='0' then v_type:='NUMBER('rc.data_precision')'; elsif rc.data_type='NUMBER' and rc.data_scale<>'0' then v_type:='NUMBER('rc.data_precision','rc.data_scale')'; elsif rc.data_type='CHAR' then v_type:='CHAR('rc.data_length')'; else v_type:=rc.data_type; end if; if rc.nullable='Y' then v_null:='NULL'; else v_null:='NOT NULL'; end if; select max(column_id) into v_maxcol from user_tab_columns c where c.table_name=rt.table_name; if rc.column_id=v_maxcol then v_virg:=''; end if; dbms_output.put_line (v_cnamev_typev_nullv_virg); end loop; dbms_output.put_line(');'); end loop;end;/declare v_virg varchar2(1); v_maxcol number;begindbms_output.put_line('--');dbms_output.put_line('-- PRIMARY KEYS --');dbms_output.put_line('--'); for rcn in (select table_name,constraint_name from user_constraints where constraint_type='P' order by table_name) loop dbms_output.put_line ('ALTER TABLE 'rcn.table_name' ADD ('); dbms_output.put_line ('CONSTRAINT 'rcn.constraint_name); dbms_output.put_line ('PRIMARY KEY ('); v_virg:=','; for rcl in (select column_name,position from user_cons_columns cl where cl.constraint_name=rcn.constraint_name order by position) loop select max(position) into v_maxcol from user_cons_columns c where c.constraint_name=rcn.constraint_name; if rcl.position=v_maxcol then v_virg:=''; end if; dbms_output.put_line (rcl.column_namev_virg); end loop; dbms_output.put_line(')'); dbms_output.put_line('USING INDEX );'); end loop;end;/declare v_virg varchar2(1); v_maxcol number; v_tname varchar2(30);begindbms_output.put_line('--');dbms_output.put_line('-- FOREIGN KEYS --');dbms_output.put_line('--'); for rcn in (select table_name,constraint_name,r_constraint_name from user_constraints where constraint_type='R' order by table_name) loop dbms_output.put_line ('ALTER TABLE 'rcn.table_name' ADD ('); dbms_output.put_line ('CONSTRAINT 'rcn.constraint_name); dbms_output.put_line ('FOREIGN KEY ('); v_virg:=','; for rcl in (select column_name,position from user_cons_columns cl where cl.constraint_name=rcn.constraint_name order by position) loop select max(position) into v_maxcol from user_cons_columns c where c.constraint_name=rcn.constraint_name; if rcl.position=v_maxcol then v_virg:=''; end if; dbms_output.put_line (rcl.column_namev_virg); end loop; select table_name into v_tname from user_constraints c where c.constraint_name=rcn.r_constraint_name; dbms_output.put_line(') REFERENCES 'v_tname' ('); select max(position) into v_maxcol from user_cons_columns c where c.constraint_name=rcn.r_constraint_name; v_virg:=','; select max(position) into v_maxcol from user_cons_columns c where c.constraint_name=rcn.r_constraint_name; for rcr in (select column_name,position from user_cons_columns cl where rcn.r_constraint_name=cl.constraint_name order by position) loop if rcr.position=v_maxcol then v_virg:=''; end if; dbms_output.put_line (rcr.column_namev_virg); end loop; dbms_output.put_line(') );'); end loop;end;/begindbms_output.put_line('--');dbms_output.put_line('-- DROP SEQUENCES --');dbms_output.put_line('--'); for rs in (select sequence_name from user_sequences where sequence_name like 'SQ%' order by sequence_name) loop dbms_output.put_line('DROP SEQUENCE 'rs.sequence_name';'); end loop;dbms_output.put_line('--');dbms_output.put_line('-- CREATE SEQUENCES --');dbms_output.put_line('--'); for rs in (select sequence_name from user_sequences where sequence_name like 'SQ%' order by sequence_name) loop dbms_output.put_line('CREATE SEQUENCE 'rs.sequence_name' NOCYCLE;'); end loop;end;/declare v_virg varchar2(1); v_maxcol number;begindbms_output.put_line('--');dbms_output.put_line('-- INDEXES --');dbms_output.put_line('--'); for rid in (select index_name, table_name from user_indexes where index_name not in (select constraint_name from user_constraints) and index_type<>'LOB' order by index_name) loop v_virg:=','; dbms_output.put_line('CREATE INDEX 'rid.index_name' ON 'rid.table_name' ('); for rcl in (select column_name,column_position from user_ind_columns cl where cl.index_name=rid.index_name order by column_position) loop select max(column_position) into v_maxcol from user_ind_columns c where c.index_name=rid.index_name; if rcl.column_position=v_maxcol then v_virg:=''; end if; dbms_output.put_line (rcl.column_namev_virg); end loop; dbms_output.put_line(');'); end loop;end;/spool offset feedback onset termout on

===================Still along the lines of dropping and recreating the table, but if you want to save the data you could
1) CREATE TABLE TEMPTAB AS SELECT COL1, COL4, COL2, COL3 FROM ORIGTAB;2) DROP TABLE ORIGTAB3) RENAME TEMPTAB TO ORIGTAB;
You'll need to put any constraints back on origtab as they dont carry over with CREATE TABLE AS SELECT..
Hope it helps,
===================How to create New project according to EVTL rules
1. first Creat Project folter like "HPcL_Scrap"
2. then create "HPCL_proj" folder in it
3. then creat new website through vs.2005
4. Project Solution Created in my document , so copy pest in "HPCL_Scarp" folder5. Add Class Liabrary "DataAccess"6. Add Class Liabrary "Scrap_Manager"
7. "DataAccess" project refreace give in Scrap_Manager , by addrefrence and select Project Tab
8. point number 7 refrence also give to "HPCL_proj" Folder
9. "Scrap_Manager" refrence give to "HpCL_Proj" , by addrefrence and select Project Tab


===================
alter table Table_Name
Add(
CREATION_DATE DATE DEFAULT Current_Date NOT NULL, CREATED_BY VARCHAR2(50 BYTE), UPDATION_DATE DATE, UPDATED_BY VARCHAR2(50 BYTE), DELETION_DATE DATE, DELETED_BY VARCHAR2(50 BYTE), IS_DELETED CHAR(1 BYTE) DEFAULT 'N' NOT NULL);
=====================ALTER TABLE cust_table ADD ( cust_sex char(1) NOT NULL, cust_credit_rating number );

============ Out look express mail to code ============== ========= How to work with output parameter ========
------->>>>>>> How to pass parameterstring strSql = "evtl_sp_getid"; SqlParameter[] param = new SqlParameter[3]; param[0] = new SqlParameter("@newid", SqlDbType.BigInt, 8, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Default, 1); param[1] = new SqlParameter("@table_name", TableName); param[2] = new SqlParameter("@column_name", columnname);
----->>>>> How procedure treat
CREATE PROCEDURE evtl_sp_getid ( @newid bigint OUTPUT, @table_name varchar(100), @column_name varchar(100) ) AS BEGIN SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED BEGIN TRANSACTION declare @oldid bigint if not exists(select * from evtl_ids with (NOLOCK) where table_name = @table_name and column_name = @column_name) BEGIN insert into evtl_ids(table_name, column_name, id) values (@table_name, @column_name, 1) set @newid=1
============== Debugging Java Script =================StepsEnable client-side script debugging in Internet Explorer Open Microsoft Internet Explorer. On the Tools menu, click Internet Options. On the Advanced tab, locate the Browsing section, and uncheck the Disable script debugging check box, and then click OK. Close Internet Explorer.In your JavasSript function add the keyword debugger . This causes VS.NET to switch to debug mode when it runs that line. Run your ASP.Net application in debug mode.
======== Delete record from all the table======== it will give delete quary for all the table
-- Delete from all tables from seleted Database
declare @tableName varchar(300) declare @strsql varchar(3000) DECLARE Fetch_Table_Name CURSOR FOR SELECT name from sysObjects where xType = 'U' and name not like 'dtproperties' order by name
Open Fetch_Table_Name
FETCH Next From Fetch_Table_Name INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN set @strsql = 'delete from ' + @TableName --exec (@strsql) print @strsql FETCH Next From Fetch_Table_Name INTO @TableName end Close Fetch_Table_Name
deallocate Fetch_Table_Name

==== 28/05/2008
Thi is the Carlton work that we need to start , save this and will explain Front end:
http://carlton.ev/index.aspAdmin: http://carlton.ev/admin/adminlogin.aspx
----------------------------News/frmNewsDetail.aspx?Key=53

---------------http://mkis.ev/admin1/News/frmSearchNews.aspx------ Server Path ---------
Pro_Search_News@Category varchar(20),

change is sp: Pro_Search_NewsLetter@Category varchar(100)
http://www.imcrbnqa.com/IMCRBNQ_Awards/Fee_Structure.aspxhttp://imcrbnqa.ev/index.aspx
inetmgr
anupanup@evisiontechnologies.com anup08

IMCserver=67.15.35.74;uid=imcrbnqa;pwd=imcrbnqa;database=imcrbnqa

http://www.imcrbnqa.com/IMCRBNQ_Awards/Fee_Structure.aspxhttp://localhost/careers.asp

http://localhost/admin/login.asp
admin admin
http://localhost/admin1/News/frmNews.aspx

Store Procedure for genrate Insert Script of Table Data

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROC [sp_DataAsInsCommand] (
@TableList varchar (8000),
@where varchar(8000) = ''
)
AS
SET NOCOUNT ON
DECLARE @position int, @exec_str varchar (2000), @TableName varchar (50)
DECLARE @name varchar(128), @xtype int, @status tinyint, @IsIdentity tinyint
SELECT @TableList = @TableList + ','
SELECT @IsIdentity = 0
SELECT @position = PATINDEX('%,%', @TableList)
WHILE (@position <> 0)
BEGIN
SELECT @TableName = SUBSTRING(@TableList, 1, @position - 1)
SELECT @TableList = STUFF(@TableList, 1, PATINDEX('%,%', @TableList),'')
SELECT @position = PATINDEX('%,%', @TableList)
SELECT @exec_str = 'DECLARE fetch_cursor CURSOR FOR ' + 'SELECT a.name, a.xtype, a.status FROM syscolumns a, sysobjects b WHERE a.id = b.id and b.name = ''' + @TableName + ''''
EXEC (@exec_str)
OPEN fetch_cursor
FETCH fetch_cursor INTO @name, @xtype, @status
IF (@status & 0x80) <> 0
BEGIN
SELECT @IsIdentity = 1
SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON'
SELECT 'GO'
END
SELECT @exec_str = 'SELECT ''INSERT INTO ' + @TableName + ' VALUES ('' + '
--Select ' -- The table name is: ' + @TableName
--text or ntext
IF (@xtype = 35) OR (@xtype = 99)
begin
SELECT @exec_str = @exec_str + '''"None yet"'''
print @exec_str
end
ELSE
--image
IF (@xtype = 34)
begin
SELECT @exec_str = @exec_str + '"' + '0xFFFFFFFF' + '"'
end
ELSE
--smalldatetime or datetime
IF (@xtype = 58) OR (@xtype = 61)
begin
SELECT @exec_str = @exec_str + 'Coalesce(' + ' + ''"'' + ' + ' + CONVERT(varchar,' + @name + ',113)' + ' + ''"''' + ')'
end
ELSE
--varchar or char or nvarchar or nchar
IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239)
SELECT @exec_str = @exec_str + 'Coalesce(' + '''"'' + ' + @name + ' + ''"''' + ',''null'')'
ELSE
--uniqueidentifier
IF (@xtype = 36)
SELECT @exec_str = @exec_str + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''"''' + ',''null'')'
ELSE
--binary or varbinary
IF (@xtype = 173) OR (@xtype = 165)
begin
SELECT @exec_str = @exec_str + '"' + '0x0' + '"'
print @exec_str
end
ELSE
SELECT @exec_str = @exec_str + 'Coalesce(CONVERT(varchar,' + @name + '), ''null'')'
WHILE @@FETCH_STATUS <> -1
BEGIN
FETCH fetch_cursor INTO @name, @xtype, @status
IF (@@FETCH_STATUS = -1) BREAK
IF (@status & 0x80) <> 0
BEGIN
SELECT @IsIdentity = 1
SELECT 'SET IDENTITY_INSERT ' + @TableName + ' ON'
SELECT 'GO'
END
--text or ntext
IF (@xtype = 35) OR (@xtype = 99)
SELECT @exec_str = @exec_str + ' + '',''' + ' + ''"None yet"'''
ELSE
--image
IF (@xtype = 34)
begin
SELECT @exec_str = @exec_str + ' + '','' + ' + '"' + '0xFFFFFFFF' + '"'
end
ELSE
--smalldatetime or datetime
IF (@xtype = 58) OR (@xtype = 61)
begin
SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar,' + @name + ',113)' + ' + ''"''' + ',''null'')'
end
ELSE
--varchar or char or nvarchar or nchar
IF (@xtype = 167) OR (@xtype = 175) OR (@xtype = 231) OR (@xtype = 239)
begin
SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + @name + ' + ''"''' + ',''null'')'
end
ELSE
--uniqueidentifier
IF (@xtype = 36)
begin
SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(''"'' + ' + ' + CONVERT(varchar(255),' + @name + ')' + ' + ''''''' + ',''null'')'
end
ELSE
--binary or varbinary
IF (@xtype = 173) OR (@xtype = 165)
begin
SELECT @exec_str = @exec_str + ' + '','' + ' + '"' + '0x0' + '"'
end
ELSE
begin
SELECT @exec_str = @exec_str + ' + '',''' + ' + Coalesce(CONVERT(varchar,' + @name + '), ''null'')'
end
END
CLOSE fetch_cursor
DEALLOCATE fetch_cursor
SELECT @exec_str = @exec_str + '+ '')'' FROM ' + @TableName
if ltrim(rtrim(@where)) <> '' set @exec_str = @exec_str + ' where ' + @where
set @exec_str = @exec_str + ' ORDER BY 1'
set @exec_str = replace(@exec_str, '"', '''''')
print @exec_str
EXEC(@exec_str)
-- print (@exec_str)
--SELECT 'GO'
IF @IsIdentity = 1
BEGIN
SELECT @IsIdentity = 0
SELECT 'SET IDENTITY_INSERT ' + @TableName + ' OFF'
--SELECT 'GO'
END
END

Tuesday, July 13, 2010

Export To Excel for DataSet

#region
//public static void ExportToExcel1(DataTable dt,string fileName,HttpResponse response)
public static void ExportToExcel1(DataTable dt,HttpResponse response)
{
response.Clear();
//response.AddHeader("content-disposition", "attachment;filename="+ fileName + ".xls");
response.AddHeader("content-disposition", "attachment;filename=File1.xls");
//response.Charset = "";
//response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
response.Write(stringWrite.ToString());
response.End();
}
#endregion

ExportToExcelFromstring


#region

public static void ExportToExcelFromstring(string fileName, HttpResponse response, string str)
{
response.Clear();
response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
response.Charset = "";
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "application/vnd.xls";
response.Write(str);
response.End();
}
#endregion

Export To Excel for WEB Table

public static void ExportToExcelFromWebTable(string fileName, HttpResponse response, Table Wtable)
{
response.Clear();
response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
response.Charset = "";
//Htable.Border = 1;
//Htable.BorderColor = "Black";
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
DataSet ds = new DataSet("Wtable");
// ds = ((System.Data.DataSet)Wtable).Copy();
DataGrid dg = new DataGrid();
dg.DataSource = ds;
dg.DataBind();
dg.RenderControl(htmlWrite);
response.Write(stringWrite.ToString());
//response.Write(Wtable.ToString());
response.End();
}

Export To Excel for HTML Table

public static void ExportToExcelFromTable(string fileName, HttpResponse response, HtmlTable Htable)

{

response.Clear();

response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");

response.Charset = "";

Htable.Border = 1;

Htable.BorderColor = "Black";

response.Cache.SetCacheability(HttpCacheability.NoCache);

response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);

Htable.RenderControl(htmlWrite);

response.Write(stringWrite.ToString());

response.End();

}