Friday 28 December 2012

copy table content from one db to another db

Copy Table Content from one DB to another DB.
----------------------------------------------------------------------------------------------------------------------
SELECT * INTO targetdbname..tablename FROM sourcedb..tablename
Using the above command you can copy the table content from one SQL DB to Another SQL DB 

----------------------------------------------------------------------------------------------------------------------
INSERT INTO tablename(field1,field2) SELECT field1,field2 FROM tablename

Using the above command you can copy the table content from one table to Another table   


Tuesday 6 November 2012

Video Players in ASP

Download the Web's most advanced video player.
----------------------------------------------------------------------------------------------------------------------
http://www.longtailvideo.com/players/jw-flv-player/



Wednesday 17 October 2012

list multiple files in single folder - asp

How to List Multiple Files in a Single Folder
----------------------------------------------------------------------------------------------------------


Dim myobjFS, myobjFile, myobjFolder

Set myobjFS = Server.CreateObject("Scripting.FileSystemObject")
Set myobjFolder = myobjFS.GetFolder(Server.MapPath("/folderpath"))

For Each myFile in myobjFolder.Files
Response.Write myFile.Name & "<br>"
Next
Set myobjFolder = Nothing
Set myobjFS = Nothing

----------------------------------------------------------------------------------------------------------

How To Move Multiple Files from One Folder to another



Dim myobjFSO, myobjFolder, myFile
Dim myFolder, myTarFolder

Set myobjFSO = Server.CreateObject("Scripting.FileSystemObject")

Set myobjFolder = myobjFSO.GetFolder("D:\Sourcefolder\")
myTarFolder = "D:\Targetfolder\backup\"

For Each myFolder in myobjFolder.SubFolders

For Each myFile in myFolder.Files
if myobjFSO.FileExists(myFile)=true then
myobjFSO.CopyFile myFile,myTarFolder&myFolder.Name&"\"
                'myobjFSO.MoveFile myFile,myTarFolder&myFolder.Name&"\"
myobjFSO.DeleteFile myFile
end if
Next
Next

Set myobjFolder = Nothing
Set myobjFSO = Nothing


----------------------------------------------------------------------------------------------------------
Count Files in a Folder

myFolder.Files.count (Check the above code for reference)

----------------------------------------------------------------------------------------------------------

Tuesday 16 October 2012

Replace Single Quotes in SQL SERVER

Replace Single Quotes in SQL SERVER
---------------------------------------------------------------------------------------------------------


@result=how to remove single quote's
REPLACE(@result,char(39),'')  (or) REPLACE(@result,char(39),char(39)+char(39))


---------------------------------------------------------------------------------------------------------

Friday 12 October 2012

Delete, Move, Copy, File Exists in asp


DeleteFile

The following example uses the DeleteFile method to delete a single file. It requires a physical path to the file so we have used Server.MapPath to find the physical path of a file, which is in the same directory as the script.

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.DeleteFile Server.MapPath("file.ext")

The DeleteFile method does not have a return value and if it fails it will generate an internal server error. If the file does not exist it will have the message "File not found" with the error code 0x800A0035.

Multiple files can be deleted using wildcards. The following example deletes all text files from the directory containing the script.

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.DeleteFile Server.MapPath(".") & "\*.txt"

Notice that DeleteFile can accept wildcards, but Server.MapPath cannot, so the physical path of the files to be deleted must be built by string addition. This code will also generate an error if no files match the description.

The star character is the most commonly used wildcard because matches any string of characters. The question mark can be used to replace a single character. The following example deletes all text files that have a name that is one character long.

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.DeleteFile Server.MapPath(".") & "\?.txt"

MoveFile

The MoveFile method takes two parameters, the source and destination, which are physical paths. The destination file can be given a different name from the original so that it can be renamed as well as moved. This command will also give an error if the source files or the destination folder do not exist.

The following example moves a file from one directory to another while keeping the name unchanged.

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.MoveFile "D:\source\a.txt", "D:\destintation\a.txt"

CopyFile

The CopyFile method is similar to the MoveFile method described above, except that the source file is not deleted. The following example copies a file from one directory to another while keeping the name unchanged.

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.CopyFile "D:\source\a.txt", "D:\destintation\a.txt"

If a file by that name already exists in the destination folder, it will be overwritten. CopyFile has an optional third parameter which can be set to false to prevent overwriting. for example:

Set FS = Server.CreateObject("Scripting.FileSystemObject")
FS.CopyFile "D:\source\a.txt", "D:\destintation\a.txt", false

If the file already exists in the destination folder this code will generate an error saying "File already exists" with the code 0x800A003A.

Check if a file exists using the File System Object

The following example checks if a file exists. It uses a physical path to the file and returns true or false.

Set FSO = Server.CreateObject("Scripting.FileSystemObject")
Response.Write FSO.FileExists(FilePath)

Replace XML Special Characters in asp


Replace XML Special Characters in asp

==========================================================================

’ 226 128 153 
– 226 128 147 
“ 226 128 156 
†226 128 
… 226 128 166 


==========================================================================


DATA = Replace(DATA, Chr(226) & Chr(128) & Chr(153) , "'")
DATA = Replace(DATA, Chr(226) & Chr(128) & Chr(147) , "-")
DATA = Replace(DATA, Chr(226) & Chr(128) & Chr(166), "...")
DATA = Replace(DATA, Chr(226) & Chr(128) & Chr(156) , "''")
DATA = Replace(DATA, Chr(226) & Chr(128) , "''")
DATA = Replace(replace(DATA,"&lt;","<"),"&gt;",">")

==========================================================================

Thursday 13 September 2012

Java Script Calendar Control in ASP

Java Script Calendar Control in ASP
------------------------------------------------------------------------------------------------------------------
Use the following code in ASP Page


<link href="css/CalendarControl.css" rel="stylesheet" type="text/css">


<script src="js/CalendarControl.js" language="javascript"></script>




<input name="txtdate" type="text" id="txtdate"  value="<%=Date%>" onclick="showCalendarControl(this);" readonly="">

------------------------------------------------------------------------------------------------------------------
Include the following Java script code 


function positionInfo(object) {

  var p_elm = object;

  this.getElementLeft = getElementLeft;
  function getElementLeft() {
    var x = 0;
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    while (elm != null) {
      x+= elm.offsetLeft;
      elm = elm.offsetParent;
    }
    return parseInt(x);
  }

  this.getElementWidth = getElementWidth;
  function getElementWidth(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetWidth);
  }

  this.getElementRight = getElementRight;
  function getElementRight(){
    return getElementLeft(p_elm) + getElementWidth(p_elm);
  }

  this.getElementTop = getElementTop;
  function getElementTop() {
    var y = 0;
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    while (elm != null) {
      y+= elm.offsetTop;
      elm = elm.offsetParent;
    }
    return parseInt(y);
  }

  this.getElementHeight = getElementHeight;
  function getElementHeight(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetHeight);
  }

  this.getElementBottom = getElementBottom;
  function getElementBottom(){
    return getElementTop(p_elm) + getElementHeight(p_elm);
  }
}

function CalendarControl() {

  var calendarId = 'CalendarControl';
  var currentYear = 0;
  var currentMonth = 0;
  var currentDay = 0;

  var selectedYear = 0;
  var selectedMonth = 0;
  var selectedDay = 0;

  var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  var dateField = null;

  function getProperty(p_property){
    var p_elm = calendarId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if (elm != null){
      if(elm.style){
        elm = elm.style;
        if(elm[p_property]){
          return elm[p_property];
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
  }

  function setElementProperty(p_property, p_value, p_elmId){
    var p_elm = p_elmId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if((elm != null) && (elm.style != null)){
      elm = elm.style;
      elm[ p_property ] = p_value;
    }
  }

  function setProperty(p_property, p_value) {
    setElementProperty(p_property, p_value, calendarId);
  }

  function getDaysInMonth(year, month) {
    return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
  }

  function getDayOfWeek(year, month, day) {
    var date = new Date(year,month-1,day)
    return date.getDay();
  }

  this.clearDate = clearDate;
  function clearDate() {
    dateField.value = '';
    hide();
  }

  this.setDate = setDate;
  function setDate(year, month, day) {
    if (dateField) {
      if (month < 10) {month =  month;}
      if (day < 10) {day =  day;}

      var dateString = month+"/"+day+"/"+year;
      dateField.value = dateString;
      hide();
    }
    return;
  }

  this.changeMonth = changeMonth;
  function changeMonth(change) {
    currentMonth += change;
    currentDay = 0;
    if(currentMonth > 12) {
      currentMonth = 1;
      currentYear++;
    } else if(currentMonth < 1) {
      currentMonth = 12;
      currentYear--;
    }

    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  this.changeYear = changeYear;
  function changeYear(change) {
    currentYear += change;
    currentDay = 0;
    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  function getCurrentYear() {
    var year = new Date().getYear();
    if(year < 1900) year += 1900;
    return year;
  }

  function getCurrentMonth() {
    return new Date().getMonth() + 1;
  }

  function getCurrentDay() {
    return new Date().getDate();
  }

  function calendarDrawTable() {

    var dayOfMonth = 1;
    var validDay = 0;
    var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
    var daysInMonth = getDaysInMonth(currentYear, currentMonth);
    var css_class = null; //CSS class for each day

    var table = "<table cellspacing='0' cellpadding='0' border='0'>";
    table = table + "<tr class='header'>";
    table = table + "  <td colspan='2' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'>&lt;</a> <a href='javascript:changeCalendarControlYear(-1);'>&laquo;</a></td>";
    table = table + "  <td colspan='3' class='title'>" + months[currentMonth-1] + "<br>" + currentYear + "</td>";
    table = table + "  <td colspan='2' class='next'><a href='javascript:changeCalendarControlYear(1);'>&raquo;</a> <a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";
    table = table + "</tr>";
    table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

    for(var week=0; week < 6; week++) {
      table = table + "<tr>";
      for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
        if(week == 0 && startDayOfWeek == dayOfWeek) {
          validDay = 1;
        } else if (validDay == 1 && dayOfMonth > daysInMonth) {
          validDay = 0;
        }

        if(validDay) {
          if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
            css_class = 'current';
          } else if (dayOfWeek == 0 || dayOfWeek == 6) {
            css_class = 'weekend';
          } else {
            css_class = 'weekday';
          }

          table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
          dayOfMonth++;
        } else {
          table = table + "<td class='empty'>&nbsp;</td>";
        }
      }
      table = table + "</tr>";
    }

    table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
    table = table + "</table>";

    return table;
  }

  this.show = show;
  function show(field) {
    can_hide = 0;
 
    // If the calendar is visible and associated with
    // this field do not do anything.
    if (dateField == field) {
      return;
    } else {
      dateField = field;
    }

    if(dateField) {
      try {
        var dateString = new String(dateField.value);
        var dateParts = dateString.split("-");
       
        selectedMonth = parseInt(dateParts[0],10);
        selectedDay = parseInt(dateParts[1],10);
        selectedYear = parseInt(dateParts[2],10);
      } catch(e) {}
    }

    if (!(selectedYear && selectedMonth && selectedDay)) {
      selectedMonth = getCurrentMonth();
      selectedDay = getCurrentDay();
      selectedYear = getCurrentYear();
    }

    currentMonth = selectedMonth;
    currentDay = selectedDay;
    currentYear = selectedYear;

    if(document.getElementById){

      calendar = document.getElementById(calendarId);
      calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

      setProperty('display', 'block');

      var fieldPos = new positionInfo(dateField);
      var calendarPos = new positionInfo(calendarId);

      var x = fieldPos.getElementLeft();
      var y = fieldPos.getElementBottom();

      setProperty('left', x + "px");
      setProperty('top', y + "px");

      if (document.all) {
        setElementProperty('display', 'block', 'CalendarControlIFrame');
        setElementProperty('left', x + "px", 'CalendarControlIFrame');
        setElementProperty('top', y + "px", 'CalendarControlIFrame');
        setElementProperty('width', calendarPos.getElementWidth() + "px", 'CalendarControlIFrame');
        setElementProperty('height', calendarPos.getElementHeight() + "px", 'CalendarControlIFrame');
      }
    }
  }

  this.hide = hide;
  function hide() {
    if(dateField) {
      setProperty('display', 'none');
      setElementProperty('display', 'none', 'CalendarControlIFrame');
      dateField = null;
    }
  }

  this.visible = visible;
  function visible() {
    return dateField
  }

  this.can_hide = can_hide;
  var can_hide = 0;
}

var calendarControl = new CalendarControl();

function showCalendarControl(textField) {
  // textField.onblur = hideCalendarControl;
  calendarControl.show(textField);
}

function clearCalendarControl() {
  calendarControl.clearDate();
}

function hideCalendarControl() {
  if (calendarControl.visible()) {
    calendarControl.hide();
  }
}

function setCalendarControlDate(year, month, day) {
  calendarControl.setDate(year, month, day);
}

function changeCalendarControlYear(change) {
  calendarControl.changeYear(change);
}

function changeCalendarControlMonth(change) {
  calendarControl.changeMonth(change);
}

document.write("<iframe id='CalendarControlIFrame' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>");
document.write("<div id='CalendarControl'></div>");


------------------------------------------------------------------------------------------------------------------
Include the following Css 


#CalendarControlIFrame {
  display: none;
  left: 0px;
  position: absolute;
  top: 0px;
  height: 200px;
  width: 250px;
  z-index: 50;
}

#CalendarControl {
  position:absolute;
  background-color:#FFF;
  margin:0;
  padding:0;
  display:none;
  z-index: 100;
}

#CalendarControl table {
  font-family: arial, verdana, helvetica, sans-serif;
  font-size: 8pt;
  border-left: 1px solid #336;
  border-right: 1px solid #336;
}

#CalendarControl th {
  font-weight: normal;
}

#CalendarControl th a {
  font-weight: normal;
  text-decoration: none;
  color: #FFF;
  padding: 1px;
}

#CalendarControl td {
  text-align: center;
}

#CalendarControl .header {
  background-color: #336;
  height:40px;
}

#CalendarControl .weekday {
  background-color: #DDD;
  color: #000;
}

#CalendarControl .weekend {
  background-color: #FFC;
  color: #000;
}

#CalendarControl .current {
  border: 1px solid #339;
  background-color: #336;
  color: #FFF;
}

#CalendarControl .weekday,
#CalendarControl .weekend,
#CalendarControl .current {
  display: block;
  text-decoration: none;
  border: 1px solid #FFF;
  width: 2em;
}

#CalendarControl .weekday:hover,
#CalendarControl .weekend:hover,
#CalendarControl .current:hover {
  color: #FFF;
  background-color: #336;
  border: 1px solid #999;
}

#CalendarControl .previous {
  text-align: left;
}

#CalendarControl .next {
  text-align: right;
}

#CalendarControl .previous,
#CalendarControl .next {
  padding: 1px 3px 1px 3px;
  font-size: 1.4em;
}

#CalendarControl .previous a,
#CalendarControl .next a {
  color: #FFF;
  text-decoration: none;
  font-weight: bold;
}

#CalendarControl .title {
  text-align: center;
  font-weight: bold;
  color: #FFF;
}

#CalendarControl .empty {
  background-color: #CCC;
  border: 1px solid #FFF;
}

.value { color:#333333; padding-left:5px; font-family:Arial, Helvetica, sans-serif; }


------------------------------------------------------------------------------------------------------------------

How to use FCK Editor in ASP

How to use FCK Editor in ASP
------------------------------------------------------------------------------------------------------
Download FCK Editor from the following Path

http://ckeditor.com/download

Change the following as per your requirement.

$Width = '100%';
$Height = '200';
$ToolbarSet = 'Default';


<!--#INCLUDE virtual="/fckeditor/fckeditor.asp" -->


<%
' Automatically calculates the editor base path based on the _samples directory.
' This is usefull only for these samples. A real application should use something like this:
' oFCKeditor.BasePath = '/fckeditor/' ; // '/fckeditor/' is the default value.
Dim sBasePath
sBasePath = Request.ServerVariables("PATH_INFO")
sBasePath = Left( sBasePath, InStrRev( sBasePath, "/news_add.asp" ) )
sBasePath="/fckeditor/"

Dim oFCKeditor
Set oFCKeditor = New FCKeditor
oFCKeditor.BasePath = sBasePath

If Request.QueryString("Toolbar") <> "" Then
oFCKeditor.ToolbarSet = Server.HTMLEncode( Request.QueryString("Toolbar") )
End If

oFCKeditor.Value = ""
oFCKeditor.Create "FCKeditor1"
%>
------------------------------------------------------------------------------------------------------


Creating RSS Feed in ASP


Creating RSS Feed in ASP
-----------------------------------------------------------------------------------------------------------
<%
Function ApplyXMLFormatting(strInput)
'strInput = Replace(strInput,"&", "&amp;")
'strInput = Replace(strInput,"'", "'")
'strInput = Replace(strInput,"""", "&quot;")
'strInput = Replace(strInput, ">", "&gt;")
'strInput = Replace(strInput,"<","&lt;")
strInput = Replace(strInput,"&nbsp;"," ")
strInput = Replace(strInput,"&", " ")
strInput = Replace(strInput,"", " ")
strInput = Replace(strInput,"""", " ")
strInput = Replace(strInput, "<p>", " ")
strInput = Replace(strInput,"</p>"," ")
strInput = Replace(strInput, "<P>", " ")
strInput = Replace(strInput,"</P>"," ")
strInput = Replace(strInput,"?","")
strInput = Replace(strInput,"<P align=left>"," ")
ApplyXMLFormatting = strInput
End Function
Function dateTimeToRFC1123(dt_dateTime)
dim a_shortDay, a_shortMonth
dt_dateTime = dateAdd ("N", server.createObject ("WScript.Shell").regRead ("HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias") , dt_dateTime)
a_shortDay = array ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
a_shortMonth = array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
dateTimeToRFC1123 = a_shortDay (weekDay (dt_dateTime) - 1) & ","
dateTimeToRFC1123 = dateTimeToRFC1123 & " " & right ("0" & day (dt_dateTime) , 2) & " " & a_shortMonth (month (dt_dateTime) - 1) & " " & year (dt_dateTime)
dateTimeToRFC1123 = dateTimeToRFC1123 & " " & right ("0" & hour (dt_dateTime) , 2) & ":" & right ("0" & minute (dt_dateTime) , 2) & ":" & right ("0" & second (dt_dateTime) , 2) & " GMT"
End Function

dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
dim path
path="C:\xmlpath\rss.xml"

set fname=fs.CreateTextFile(path,true)

fname.write("<?xml version='1.0'  encoding='UTF-8' standalone='yes'?>")
fname.write("<?xml-stylesheet href='http://sitename/rss.css' type='text/css'?>")
fname.write("<rss version='2.0'>")
fname.write("<channel>")
fname.write("<title>"&Sitename&" RSS</title>")
fname.write("<link>http://"&Sitename&"/</link>")
fname.write("<description>RSS for the "&Sitename&" community.</description>")
fname.write("<pubDate>"& dateTimeToRFC1123(now()) &"</pubDate>")
fname.write("<lastBuildDate>"& dateTimeToRFC1123(now()) &"</lastBuildDate>")
fname.write("<generator>SITE NAME RSS Generator 2.00</generator>")
fname.write("<language>en-us</language>")
fname.write("<image>")
fname.write("<link>http://"&Sitename&"/</link>")
fname.write("<title>SITE NAME TITLE</title>")
fname.write("<url>http://www.sitename.com/images/image.gif</url>")
fname.write("</image>")
fname.write("<div class='info' xmlns='http://www.w3.org/1999/xhtml'>This is formatted XML site feed. It is intended to be viewed in an RSS or Atom Newsreader or syndicated to another site.<br /></div>")

fname.write("<item>")
fname.write("<link>http://"&Sitename&"/"& LINK &"</link>")
fname.write("<pubDate>"& dateTimeToRFC1123(now()) &"</pubDate>")
fname.write("<guid>http://"&Sitename&"/"& LINK &"</guid>")
fname.write("<title>" &Server.HTMLEncode(SUBJECT)& "</title>")
fname.write("<description>" &Server.HTMLEncode(TOTALDESCRIPTION)& "</description>")
fname.write("</item>")

fname.write("</channel>")
fname.write("</rss>")
%>
-----------------------------------------------------------------------------------------------------------

Wednesday 12 September 2012

Stored Procedure to Search a Specific Text in one DataBase

Stored Procedure to Search a Specific Text in one DataBase
------------------------------------------------------------------------------------------------------------
CREATE PROC [dbo].[SearchAllTables]
(
@SearchStr nvarchar(100)
)
AS
BEGIN


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
      ) = 0
)

WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)

IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END

SELECT ColumnName, ColumnValue FROM #Results
END
------------------------------------------------------------------------------------------------------------
Execute the following Command to Search Specific Text


EXEC SearchAllTables '<script'

EXEC SearchAllTables '<a style'

EXEC SearchAllTables '<form'


UPDATE Table
SET    column = replace(description, '<a style=position:absolute;left:-9999px;top:-99', '')
WHERE  column LIKE '%<a style=position:absolute;left:-9999px;top:-99%';
------------------------------------------------------------------------------------------------------------

Convert text/HTML to Server-side Statements for E-mail sending in asp

Convert text/HTML to Server-side Statements for E-mail sending in asp
-------------------------------------------------------------------------------------------------------------------

You can convert text and HTML to server side statements for E-mail sending with one click

http://www.accessify.com/tools-and-wizards/developer-tools/response.right/

-------------------------------------------------------------------------------------------------------------------


Change 404 Error Page in IIS

How to Change 404 Error Page in IIS 6.0
-------------------------------------------------------------------------------------------------------------------

1) Windows - Go to Start - Run - Type "inetmgr" Then IIS will Open
2) Right Click on Website - Properties
3) Select CUSTOM Errors Tab
4) Click on HTTP Error 404
5) Edit - Message Type (File or URL) change the file type

Check The following Image



-------------------------------------------------------------------------------------------------------------------

download pdf file in ASP


Code for Downloading  PDF file in ASP using ADODB Stream Object
-----------------------------------------------------------------------------------------------------------------
<%
Dim prvURL
prvURL="http://sqlinjectiontruths.blogspot.in/test.html"
prvURL=replace(prvURL,"http://","")
prvURL=replace(prvURL,Request.ServerVariables("HTTP_HOST"),"")

dim pdfURL
Select Case prvURL
Case "test.html"
pdfURL="test.pdf"
Case Else
Response.redirect("/")
End Select


    Response.ContentType = "application/x-unknown" ' arbitrary
    FPath =  Server.MapPath(".")&"\documents\"&pdfURL
    Response.AddHeader "Content-Disposition","attachment; filename="&pdfURL

    Set adoStream = CreateObject("ADODB.Stream")
    adoStream.Open()
    adoStream.Type = 1
    adoStream.LoadFromFile(FPath)
    Response.BinaryWrite adoStream.Read()
    adoStream.Close
    Set adoStream = Nothing
%>
-------------------------------------------------------------------------------------------------------------------

Preventing SQL Injection Attacks in Classic ASP

Preventing SQL Injection Attacks in Classic ASP and SQL Injection tips for ASP 2.0 
----------------------------------------------------------------------------------------------------------
Step1:

Include <% Option Explicit %> in all the pages, So that Hacker can not create variables without declaring

----------------------------------------------------------------------------------------------------------
Step2:

Client Side Java Script Validation is must, maxlength property should be placed in forms

Example:

function frmpostreq()
{
 if(document.postreq.email.value=="")
 {
  alert("Please enter Email Address");
  document.postreq.email.focus();
  return false;
 }
return true;
}

----------------------------------------------------------------------------------------------------------
Step3:

Server Side Validation is must,Check field length in asp pages

Example:

<%
''' Email '''
if trim(Request.Form("emaill")) = "" then
    Response.Write("Enter Email !")
    Response.End
end if
%>

<%
''' Email '''
if len(Request.Form("emaill")) >50 then
    Response.Write("Email ID value can not be greater than 50 characters")
    Response.End
end if
%>

----------------------------------------------------------------------------------------------------------
Step4:

Example:

form method="post" action="getval.asp" id="frm1" name="frm1"

Include the following Code in getval.asp page.

<%
if Request.ServerVariables("HTTP_REFERER") = "" or ISEmpty(Request.ServerVariables("HTTP_REFERER")) Then
 Response.write "Please Go To www.sqlinjectiontruths.blogspot.in/"
 Response.end
End if

if instr(1, Request.ServerVariables("HTTP_REFERER"), "sqlinjectiontruths.blogspot.in", 1) > 0 Then
Else
 Response.write "Please Go To www.sqlinjectiontruths.blogspot.in/"
 Response.end
End if
%>

----------------------------------------------------------------------------------------------------------
Step5:

Remember to kill the record set object, connection string object

set recordset=nothing
recordset.close
connectionstring.close

(or)

killobject(recordset)
killobject(connectionstring)

<%
function killobject(obj)
 if isobject(obj) then
  IF obj.state = 1 THEN obj.close
 End if
 Set obj = Nothing
end function
%>

----------------------------------------------------------------------------------------------------------
Step6:

Very Very Important Technique is Validate Numeric Query String Value with Cint (or) Isnumeric ASP Function

ID=CInt(trim(Request.QueryString("ID")))

or

ID=Isnumeric(trim(Request.QueryString("ID")))


----------------------------------------------------------------------------------------------------------
Step7:

Very Very Important Technique is Validate String Value with  Replace ASP Function

When  Request.Form Value is String

email=trim(Replace(CStr(Request.Form("email")), "'", "''"))

When Query String Value is String

ID=trim(Replace(CStr(Request.QueryString("ID")), "'", "''"))

----------------------------------------------------------------------------------------------------------
Step8:

Include the following code in all ASP Pages(especially in querystring pages)

<%

Dim BlackList, ErrorPage, s, hackcode, matchstring


' "@",".inf",".html",".htm", ".pl", ".PL",".ini", "alter" can be included


BlackList = Array("+","ftp://", "INFORMATION_SCHEMA", "@@version","TABLE_NAME","replace(","replace%28",_
 "sysobjects","syscolumns","syscomments","%20where%20","where+","dbo.",_
 "TABLE_SCHEMA","ROUTINE_","READ_ONLY","charindex","OBJECT_","select * from",_
 "nchar","varchar","nvarchar","char(","char%28","+char","%2Bchar","char+",_
 "+set", "%2Bset","%20set","set+","fetch","kill",_
 "cursor","declare ","declare+","declare%20","declare%2B","delete+","drop+",_
 "drop view","drop view", "backup","update%20","update+","update ","update+",_
 "DOCTYPE","<head", "meta","<title>","</title>","</head>", "<body>","%3Cscript","<script", "</script>",_
 "</body>", "</html>","<form", "<div","</div>","<link","<a style","sp_",_
 "primary key","foreign key","primary+key","foreign+key","foreign_key","primary_key",_
 "where+","where%2Bjoin","where%20join","where ","inner join","inner+join","inner%2Bjoin","inner%20join",_
 "exec+","exec%20","exec%2B","execute+","execute%20","execute%2B","exec ","execute ",_
 "truncate+","truncate%20","truncate%2B","truncate ",_
 "</table>","<tr","</tr>","<td","</td>","<table","%3Ctable","%3C%2Ftable",_
 "create table","create%20table","create+table","create%2Btable","create view","create%20view","create+view","create%2Bview",_
 "create trigger","create%20trigger","create+trigger","create%2Btrigger","create ","create%20","create+","create%2B",_
 "insert into","insert%20into","insert+into","insert%2Binto",_
 "cast+","%20cast%20","%3Dcast","=cast","cast(","cast%28",_
 "alter+","alter%20","alter%28","alter%2B","alter ","alter(","alter table","alter%20table","alter view","alter view",_
 ".asp",".php",".jsp", ".LOG",".zip",".rar",".tar",".txt",".xml",".gzip","link=","url",_
 "--",";","/*", "*/","@@","%40%40")

    

'  Populate the error page you want to redirect to in case the
'  check fails.

ErrorPage = "/ErrorPage.asp"

'Send mail to webmaster with Hack Code

Function SendEmail(hcode,matchstring)
  'On Error Resume Next

hackcode = "Match String: " & matchstring & "<br />"
hackcode = hackcode & "HACK CODE: " & hcode & "<br />"
hackcode = hackcode & "URL: " & Request.ServerVariables("URL") & "<br />"
hackcode = hackcode & "IP ADDRESS: " & Request.ServerVariables("REMOTE_ADDR") & "<br />"
hackcode = hackcode & "You are browsing this site with: " & Request.ServerVariables("http_user_agent") & "<br />"
hackcode = hackcode & "The DNS lookup of the IP address: " & Request.ServerVariables("remote_host")  & "<br />"
hackcode = hackcode & "HTTP HEADERS SENT BY CLIENT: " & Request.ServerVariables("ALL_HTTP")  & "<br />"
hackcode = hackcode & "ALL_RAW: " & Request.ServerVariables("ALL_RAW")  & "<br />"


  dim oMail, oMailConfig
  Set oMail = Server.CreateObject("CDO.Message")
  Set oMailConfig = Server.CreateObject ("CDO.Configuration")
  oMailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "localhost"
  oMailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
  oMailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
  oMailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
  oMailConfig.Fields.Update
  Set oMail.Configuration = oMailConfig
  oMail.From = "from email address"
  oMail.To = "to email address"
  oMail.Subject = "Tried for entering hacking code - sqlinjectiontruths.blogspot.in"
  oMail.HTMLBody = hackcode
  oMail.Send  
  set oMail=nothing 
End Function

'End Send mail to webmaster with Hack Code

           
'''''''''''''''''''''''''''''''''''''''''''''''''''          
'  This function does not check for encoded characters
'  since we do not know the form of encoding your application
'  uses. Add the appropriate logic to deal with encoded characters
'  in here
'''''''''''''''''''''''''''''''''''''''''''''''''''
Function CheckStringForSQL(str)
  On Error Resume Next

  Dim lstr

  ' If the string is empty, return true
  If ( IsEmpty(str) ) Then
    CheckStringForSQL = false
    Exit Function
  ElseIf ( StrComp(str, "") = 0 ) Then
    CheckStringForSQL = false
    Exit Function
  End If

  lstr = LCase(str)

  ' Check if the string contains any patterns in our
  ' black list
  For Each s in BlackList

    If ( InStr (lstr, s) <> 0 ) Then
      CheckStringForSQL = true
      Exit Function
    End If

  Next

  CheckStringForSQL = false
End Function

'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check forms data
'''''''''''''''''''''''''''''''''''''''''''''''''''

For Each s in Request.Form

  If ( CheckStringForSQL(Request.Form(s)) ) Then
    SendEmail Request.Form,s
    ' Redirect to an error page
    Response.Redirect(ErrorPage)

  End If
Next

'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check query string
'''''''''''''''''''''''''''''''''''''''''''''''''''

For Each s in Request.QueryString

  If ( CheckStringForSQL(Request.QueryString(s)) ) Then

    SendEmail Request.QueryString,s
    ' Redirect to error page
    Response.Redirect(ErrorPage)
    End If

Next


'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check cookies
'''''''''''''''''''''''''''''''''''''''''''''''''''

'For Each s in Request.Cookies
'  If ( CheckStringForSQL(Request.Cookies(s)) ) Then
'
'      GetSecureVal(Request.Cookies(s))
'
'    ' SendEmail Request.Cookies,s
'    ' Redirect to error page
'    'Response.Redirect(ErrorPage)
'
'  End If
'
'Next


'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check Secure Value
'''''''''''''''''''''''''''''''''''''''''''''''''''

Function GetSecureVal(param)
 If IsEmpty(param) Or param = "" Then
  GetSecureVal = param
  Exit Function
 End If
 If IsNumeric(param) Then
  GetSecureVal = trim(CLng(param))
 Else
  GetSecureVal = trim(Replace(CStr(param), "'", "''"))
 End If
End Function

'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Add additional checks for input that your application
'  uses. (for example various request headers your app
'  might use)
'''''''''''''''''''''''''''''''''''''''''''''''''''
%>

----------------------------------------------------------------------------------------------------------
Step9:

Instead of using "SA" as username for all the databases, Use different user names and different passwords for each databases
----------------------------------------------------------------------------------------------------------
Step10:

Use Stored Procedures, Instead of writing raw SQL queries on .asp pages
----------------------------------------------------------------------------------------------------------
Step11:

Keep your system up to date with the most recent cumulative update package for SQL Server Service Packs.
----------------------------------------------------------------------------------------------------------
Step12:

  Use Captcha in all the forms in the website.(mandatory)
  With Captcha, you can restrict SPAM Bots

Captca code in ASP -> http://sqlinjectiontruths.blogspot.in/2013/04/recaptcha-in-classic-asp.html
----------------------------------------------------------------------------------------------------------
Step13:
Decode Query String Values

Refer the URLS:
http://sqlinjectiontruths.blogspot.in/2013/03/asp-encode-decode-functions.html
http://www.aspnut.com/reference/encoding.asp



Sending Fax with Classic ASP

Need to send a fax in ASP Classic
-------------------------------------------------------------------------------------------------------------------

The following Website Provides API for Classic ASP

www.interfax.net/en/dev/aspclassic
-------------------------------------------------------------------------------------------------------------------


Email Sending With Gmail, Google Apps in ASP 2.0


Email Sending With Gmail, Google Apps in ASP 2.0
------------------------------------------------------------------------------------------------------------
<%
'On Error Resume Next
Dim Subject, Body, SenderEmail, RecipientEmail, SMTPServer, SMTPusername, SMTPpassword
SenderEmail = "info@domain name.com"
SMTPserver = "smtp.gmail.com"
SMTPusername = "info@gmail.com"
'SMTPusername = "info@googleapps username.com" for google APPS
SMTPpassword = "PASSWORD"
'SMTPpassword = "PASSWORD" google APPS password
Subject = "Hello"
Body = "This is a test. Please ignore."
RecipientEmail= "email@domain name.com"

sch = "http://schemas.microsoft.com/cdo/configuration/"
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(sch & "smtpauthenticate") = 1
.Item(sch & "smtpusessl") = True
.Item(sch & "smtpserver") = SMTPserver
.Item(sch & "sendusername") = SMTPusername
.Item(sch & "sendpassword") = SMTPpassword
.Item(sch & "smtpserverport") = 465
.Item(sch & "sendusing") = 2
.Item(sch & "connectiontimeout") = 100
.update
End With

'Const cdoSendUsingPickup = "c:\inetpub\mailroot\pickup"
Set cdoMessage = CreateObject("CDO.Message")
With cdoMessage
Set .Configuration = cdoConfig
cdoMessage.From = SenderEmail
cdoMessage.To = RecipientEmail
cdoMessage.Subject = Subject
cdoMessage.TextBody = Body
cdoMessage.Send
End With
Set cdoMessage = Nothing
Set cdoConfig = Nothing
If Err.Number <> 0 Then
  Response.Write (Err.Description& "<br><br>")
end if
%>