.
WinWeb
Microsoft Windows Hosting, ASP, ASP.NET, Multiple Domain Name Plans
home
|
about us
|
contact us
Hosting web sites since 1997
WEB HOSTING
ECOMMERCE
DOMAIN NAMES
SUPPORT
REFERRAL PARTNERS
ORDER
LOGIN
For Phone Support Call:
1.212.753.1520
TOOLS
ASP Scripts
asp.NET Scripts
HTML Scripts
JAVA Scripts
PERL Scripts
PHP Scripts
WML Scripts
Support Tools
ASP Scripts
.
Adovbs
/
Ado adsi
/
ADO version
/
Cache
/
Cache expire
/
Cache stop
/
CDONTS Retrieving messages
/
Database
/
Databaselisttables
/
Databasereadtable
/
DataDSNConnection
/
DataDSN-LessConnection
/
DataMSSQLconnection
/
Date
/
Dateadd
/
Datecountdown
/
Datediff
/
Datefirstlast
/
Dateformat
/
Datejulian
/
Dateleap
/
Datepart
/
Datesub
/
Dbcommon
/
Dbconnect
/
Dbselect
/
Directory
/
Dirattr
/
Dircreate
/
Dirdelete
/
Dirfiles
/
DirRecursive
/
DirRecDetails
/
DomainNameValidation
/
Doublequote
/
File
/
Fileappend
/
Fileappend2
/
Filecopy
/
Filedelete
/
Filedir
/
Filefilter
/
FileFindString
/
Filemove
/
Fileread
/
Filewrite
/
FPoswsadm.exe
/
GetUrl
/
Global
/
Globalredirect
/
Globalsession
/
Httpheader
/
ListFiles
/
Mail
/
Mailascii
/
Mailattach
/
Mailhtml
/
Newmailobject
/
Number
/
Numberfileread
/
Numberrandom
/
Permissionscaclsref
/
Permissionschange
/
Referer
/
RegularExpression
/
SaveAndSend
/
Save to file
/
SearchStringinFile
/
SendForm
/
Serverpath
/
Serverprevious
/
Serverredirect
/
Servertrack
/
Servervariables
/
SetScriptTimeOut
/
Sitesearch
/
Sleep
/
Sort2Arrays
/
SortArray
/
SortDouble
/
SortInteger
/
SortLong
/
SortSingle
/
SortString
/
SortVariant
/
Special
/
Specialchars
/
String
/
Stringcase
/
Stringmatch
/
Stringpart
/
Stringsplit
/
Time
/
Timeadd
/
Timediff
/
Timeformat
/
Timepart
/
Timesub
/
UsernameValidation
/
GetXMLAuth
/
POSTForm
/
ConnecttoMySQL
/
EditTableMySQL
/
ListTablesMySQL
.
..
Adovbs
<% '-------------------------------------------------------------------- ' Microsoft ADO ' ' (c) 1996-1998 Microsoft Corporation. All Rights Reserved. ' ' ' ' ADO constants include file for VBScript ' '-------------------------------------------------------------------- '---- CursorTypeEnum Values ---- Const adOpenForwardOnly = 0 Const adOpenKeyset = 1 Const adOpenDynamic = 2 Const adOpenStatic = 3 '---- CursorOptionEnum Values ---- Const adHoldRecords = &H00000100 Const adMovePrevious = &H00000200 Const adAddNew = &H01000400 Const adDelete = &H01000800 Const adUpdate = &H01008000 Const adBookmark = &H00002000 Const adApproxPosition = &H00004000 Const adUpdateBatch = &H00010000 Const adResync = &H00020000 Const adNotify = &H00040000 Const adFind = &H00080000 Const adSeek = &H00400000 Const adIndex = &H00800000 '---- LockTypeEnum Values ---- Const adLockReadOnly = 1 Const adLockPessimistic = 2 Const adLockOptimistic = 3 Const adLockBatchOptimistic = 4 '---- ExecuteOptionEnum Values ---- Const adRunAsync = &H00000010 Const adAsyncExecute = &H00000010 Const adAsyncFetch = &H00000020 Const adAsyncFetchNonBlocking = &H00000040 Const adExecuteNoRecords = &H00000080 '---- ConnectOptionEnum Values ---- Const adAsyncConnect = &H00000010 '---- ObjectStateEnum Values ---- Const adStateClosed = &H00000000 Const adStateOpen = &H00000001 Const adStateConnecting = &H00000002 Const adStateExecuting = &H00000004 Const adStateFetching = &H00000008 '---- CursorLocationEnum Values ---- Const adUseServer = 2 Const adUseClient = 3 '---- DataTypeEnum Values ---- Const adEmpty = 0 Const adTinyInt = 16 Const adSmallInt = 2 Const adInteger = 3 Const adBigInt = 20 Const adUnsignedTinyInt = 17 Const adUnsignedSmallInt = 18 Const adUnsignedInt = 19 Const adUnsignedBigInt = 21 Const adSingle = 4 Const adDouble = 5 Const adCurrency = 6 Const adDecimal = 14 Const adNumeric = 131 Const adBoolean = 11 Const adError = 10 Const adUserDefined = 132 Const adVariant = 12 Const adIDispatch = 9 Const adIUnknown = 13 Const adGUID = 72 Const adDate = 7 Const adDBDate = 133 Const adDBTime = 134 Const adDBTimeStamp = 135 Const adBSTR = 8 Const adChar = 129 Const adVarChar = 200 Const adLongVarChar = 201 Const adWChar = 130 Const adVarWChar = 202 Const adLongVarWChar = 203 Const adBinary = 128 Const adVarBinary = 204 Const adLongVarBinary = 205 Const adChapter = 136 Const adFileTime = 64 Const adDBFileTime = 137 Const adPropVariant = 138 Const adVarNumeric = 139 '---- FieldAttributeEnum Values ---- Const adFldMayDefer = &H00000002 Const adFldUpdatable = &H00000004 Const adFldUnknownUpdatable = &H00000008 Const adFldFixed = &H00000010 Const adFldIsNullable = &H00000020 Const adFldMayBeNull = &H00000040 Const adFldLong = &H00000080 Const adFldRowID = &H00000100 Const adFldRowVersion = &H00000200 Const adFldCacheDeferred = &H00001000 Const adFldKeyColumn = &H00008000 '---- EditModeEnum Values ---- Const adEditNone = &H0000 Const adEditInProgress = &H0001 Const adEditAdd = &H0002 Const adEditDelete = &H0004 '---- RecordStatusEnum Values ---- Const adRecOK = &H0000000 Const adRecNew = &H0000001 Const adRecModified = &H0000002 Const adRecDeleted = &H0000004 Const adRecUnmodified = &H0000008 Const adRecInvalid = &H0000010 Const adRecMultipleChanges = &H0000040 Const adRecPendingChanges = &H0000080 Const adRecCanceled = &H0000100 Const adRecCantRelease = &H0000400 Const adRecConcurrencyViolation = &H0000800 Const adRecIntegrityViolation = &H0001000 Const adRecMaxChangesExceeded = &H0002000 Const adRecObjectOpen = &H0004000 Const adRecOutOfMemory = &H0008000 Const adRecPermissionDenied = &H0010000 Const adRecSchemaViolation = &H0020000 Const adRecDBDeleted = &H0040000 '---- GetRowsOptionEnum Values ---- Const adGetRowsRest = -1 '---- PositionEnum Values ---- Const adPosUnknown = -1 Const adPosBOF = -2 Const adPosEOF = -3 '---- enum Values ---- Const adBookmarkCurrent = 0 Const adBookmarkFirst = 1 Const adBookmarkLast = 2 '---- MarshalOptionsEnum Values ---- Const adMarshalAll = 0 Const adMarshalModifiedOnly = 1 '---- AffectEnum Values ---- Const adAffectCurrent = 1 Const adAffectGroup = 2 Const adAffectAll = 3 Const adAffectAllChapters = 4 '---- ResyncEnum Values ---- Const adResyncUnderlyingValues = 1 Const adResyncAllValues = 2 '---- CompareEnum Values ---- Const adCompareLessThan = 0 Const adCompareEqual = 1 Const adCompareGreaterThan = 2 Const adCompareNotEqual = 3 Const adCompareNotComparable = 4 '---- FilterGroupEnum Values ---- Const adFilterNone = 0 Const adFilterPendingRecords = 1 Const adFilterAffectedRecords = 2 Const adFilterFetchedRecords = 3 Const adFilterPredicate = 4 Const adFilterConflictingRecords = 5 '---- SearchDirectionEnum Values ---- Const adSearchForward = 1 Const adSearchBackward = -1 '---- PersistFormatEnum Values ---- Const adPersistADTG = 0 Const adPersistXML = 1 '---- StringFormatEnum Values ---- Const adStringXML = 0 Const adStringHTML = 1 Const adClipString = 2 '---- ConnectPromptEnum Values ---- Const adPromptAlways = 1 Const adPromptComplete = 2 Const adPromptCompleteRequired = 3 Const adPromptNever = 4 '---- ConnectModeEnum Values ---- Const adModeUnknown = 0 Const adModeRead = 1 Const adModeWrite = 2 Const adModeReadWrite = 3 Const adModeShareDenyRead = 4 Const adModeShareDenyWrite = 8 Const adModeShareExclusive = &Hc Const adModeShareDenyNone = &H10 '---- IsolationLevelEnum Values ---- Const adXactUnspecified = &Hffffffff Const adXactChaos = &H00000010 Const adXactReadUncommitted = &H00000100 Const adXactBrowse = &H00000100 Const adXactCursorStability = &H00001000 Const adXactReadCommitted = &H00001000 Const adXactRepeatableRead = &H00010000 Const adXactSerializable = &H00100000 Const adXactIsolated = &H00100000 '---- XactAttributeEnum Values ---- Const adXactCommitRetaining = &H00020000 Const adXactAbortRetaining = &H00040000 '---- PropertyAttributesEnum Values ---- Const adPropNotSupported = &H0000 Const adPropRequired = &H0001 Const adPropOptional = &H0002 Const adPropRead = &H0200 Const adPropWrite = &H0400 '---- ErrorValueEnum Values ---- Const adErrInvalidArgument = &Hbb9 Const adErrNoCurrentRecord = &Hbcd Const adErrIllegalOperation = &Hc93 Const adErrInTransaction = &Hcae Const adErrFeatureNotAvailable = &Hcb3 Const adErrItemNotFound = &Hcc1 Const adErrObjectInCollection = &Hd27 Const adErrObjectNotSet = &Hd5c Const adErrDataConversion = &Hd5d Const adErrObjectClosed = &He78 Const adErrObjectOpen = &He79 Const adErrProviderNotFound = &He7a Const adErrBoundToCommand = &He7b Const adErrInvalidParamInfo = &He7c Const adErrInvalidConnection = &He7d Const adErrNotReentrant = &He7e Const adErrStillExecuting = &He7f Const adErrOperationCancelled = &He80 Const adErrStillConnecting = &He81 Const adErrNotExecuting = &He83 Const adErrUnsafeOperation = &He84 '---- ParameterAttributesEnum Values ---- Const adParamSigned = &H0010 Const adParamNullable = &H0040 Const adParamLong = &H0080 '---- ParameterDirectionEnum Values ---- Const adParamUnknown = &H0000 Const adParamInput = &H0001 Const adParamOutput = &H0002 Const adParamInputOutput = &H0003 Const adParamReturnValue = &H0004 '---- CommandTypeEnum Values ---- Const adCmdUnknown = &H0008 Const adCmdText = &H0001 Const adCmdTable = &H0002 Const adCmdStoredProc = &H0004 Const adCmdFile = &H0100 Const adCmdTableDirect = &H0200 '---- EventStatusEnum Values ---- Const adStatusOK = &H0000001 Const adStatusErrorsOccurred = &H0000002 Const adStatusCantDeny = &H0000003 Const adStatusCancel = &H0000004 Const adStatusUnwantedEvent = &H0000005 '---- EventReasonEnum Values ---- Const adRsnAddNew = 1 Const adRsnDelete = 2 Const adRsnUpdate = 3 Const adRsnUndoUpdate = 4 Const adRsnUndoAddNew = 5 Const adRsnUndoDelete = 6 Const adRsnRequery = 7 Const adRsnResynch = 8 Const adRsnClose = 9 Const adRsnMove = 10 Const adRsnFirstChange = 11 Const adRsnMoveFirst = 12 Const adRsnMoveNext = 13 Const adRsnMovePrevious = 14 Const adRsnMoveLast = 15 '---- SchemaEnum Values ---- Const adSchemaProviderSpecific = -1 Const adSchemaAsserts = 0 Const adSchemaCatalogs = 1 Const adSchemaCharacterSets = 2 Const adSchemaCollations = 3 Const adSchemaColumns = 4 Const adSchemaCheckConstraints = 5 Const adSchemaConstraintColumnUsage = 6 Const adSchemaConstraintTableUsage = 7 Const adSchemaKeyColumnUsage = 8 Const adSchemaReferentialConstraints = 9 Const adSchemaTableConstraints = 10 Const adSchemaColumnsDomainUsage = 11 Const adSchemaIndexes = 12 Const adSchemaColumnPrivileges = 13 Const adSchemaTablePrivileges = 14 Const adSchemaUsagePrivileges = 15 Const adSchemaProcedures = 16 Const adSchemaSchemata = 17 Const adSchemaSQLLanguages = 18 Const adSchemaStatistics = 19 Const adSchemaTables = 20 Const adSchemaTranslations = 21 Const adSchemaProviderTypes = 22 Const adSchemaViews = 23 Const adSchemaViewColumnUsage = 24 Const adSchemaViewTableUsage = 25 Const adSchemaProcedureParameters = 26 Const adSchemaForeignKeys = 27 Const adSchemaPrimaryKeys = 28 Const adSchemaProcedureColumns = 29 Const adSchemaDBInfoKeywords = 30 Const adSchemaDBInfoLiterals = 31 Const adSchemaCubes = 32 Const adSchemaDimensions = 33 Const adSchemaHierarchies = 34 Const adSchemaLevels = 35 Const adSchemaMeasures = 36 Const adSchemaProperties = 37 Const adSchemaMembers = 38 '---- SeekEnum Values ---- Const adSeekFirstEQ = &H1 Const adSeekLastEQ = &H2 Const adSeekAfterEQ = &H4 Const adSeekAfter = &H8 Const adSeekBeforeEQ = &H10 Const adSeekBefore = &H20 '---- ADCPROP_UPDATECRITERIA_ENUM Values ---- Const adCriteriaKey = 0 Const adCriteriaAllCols = 1 Const adCriteriaUpdCols = 2 Const adCriteriaTimeStamp = 3 '---- ADCPROP_ASYNCTHREADPRIORITY_ENUM Values ---- Const adPriorityLowest = 1 Const adPriorityBelowNormal = 2 Const adPriorityNormal = 3 Const adPriorityAboveNormal = 4 Const adPriorityHighest = 5 '---- CEResyncEnum Values ---- Const adResyncNone = 0 Const adResyncAutoIncrement = 1 Const adResyncConflicts = 2 Const adResyncUpdates = 4 Const adResyncInserts = 8 Const adResyncAll = 15 '---- ADCPROP_AUTORECALC_ENUM Values ---- Const adRecalcUpFront = 0 Const adRecalcAlways = 1 %>
back to top
..
..
Ado adsi
Using ADO for Querying The following example shows how Automation clients can use ActiveX Data Objects (ADO) to query directory services using ADSI and its OLE DB implementation. The ADO object model consists of the following objects: Connection An open connection to an OLE DB data source such as ADSI. Command Defines a specific command to execute against the data source. Parameters An optional collection for any parameters to provide to the command object. Recordset A set of records from a table, command object, or SQL syntax. A recordset can be created without any underlying Connection object. Field A single column of data in a recordset. Property A collection of values supplied by the provider for ADO. Error Contains details about data access errors, refreshed for each time an error occurs in a single operation. For more information, see the Microsoft Platform SDK under ActiveX Data Objects. The following example disables the user accounts on an ldap server. Dim X as IADs Dim con As New Connection, rs As New Recordset Dim MyUser As IADsUser con.Provider = "ADsDSOObject" con.Open "Active Directory Provider", "CN=Foobar,CN=Users,DC=MICROSOFT,DC=COM,O=INTERNET", "Password" Set rs = con.Execute("
;(objectClass=User);ADsPath;onelevel") While Not rs.EOF MyUser = GetObject(rs.Fields(0).Value) MyUser.AccountDisabled = True rs.MoveNext Wend
back to top
..
..
ADO version
<% Set conn = CreateObject("ADODB.Connection") VersionInfo = "ADO Version: " & conn.Version Response.Write VersionInfo %>
back to top
..
..
Cache
How to stop a page from being cached How to force the cache to expire How to force the cache to expire Write the following on top of the HTML Page
Your Page Title Here
Note : Netscape Users might have some problem with this as the browser might have some problems in caching: How to stop a page from being cached Write the follwing code on the HTML Page
Your Page Title Here
back to top
..
..
Cache expire
Force Browser Cache How to stop a page from being cached Write the follwing code on the HTML Page
Your Page Title Here
back to top
..
..
Cache stop
Stop Browser Cache How to force the cache to expire Write the following on top of the HTML Page
Your Page Title Here
Note : Netscape Users might have some problem with this as the browser might have some problems in caching:
back to top
..
..
CDONTS Retrieving messages
How to Retrieve E-mail Messages from SMTP server running under IIS Set objSession = CreateObject ("CDONTS.Session") objSession.LogonSMTP "My name", "some_email_address@domain.com" Set objInbox = objSession.GetDefaultFolder(1) Set collMessages = objInbox.Messages Response.write "You have : " & collMessages.Count & " messages
" For Each Mess in collMessages Response.write "
New message begin
" Response.write Mess.text next
back to top
..
..
Database
How to connect to database I do not wish to write DB connect code in every page, How ? How to write a simple select statement and display the result? How to connect to database in ASP There are tow ways of connecting ot a database. Using a System DSN 1.) Create a system DSN using the ODBC Wizard in the Control Panel 2.) Connect to the database using a simple connection string: "DSN=System DSN Name" Using a DSN-less connection 1.) Place the Access database file (the *.mdb file) in a web-shared directory 2.) Specify the driver and the physical location of the database file Setting Up a DSN You need to set up a DSN (Data Source Name) for each database that you uses. Following is the process of setting DSN Simply double-click the ODBC applet in the Control Panel -> Choose the System DSN tab -> Click Add Choose the type of database (MS Acccess in this case) -> Click finish. Now type in the Database Name in the Data Source Name box -> Click Select. -> Navigate to the drive and directory where the database is located, and select it. -> Close the window now. Now, its all set to call the database by name in your scripts The system will know which ODBC driver to use and also the location database is located. Now each time you need to access the Database just create the connection object as follows. <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %> I do not wish to write connect script each time. How do I do it ? Now each time you need to access the Database just create the connection object as follows. <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %> Hey, But don't you think that writing this script on each page would not be a good idea in terms of scalability ! A better approach would be to have this code in an include file centrally. Create a file called say 'dbObject.asp' and perhaps place it in the /scripts directory. dbObject.asp might look something like this <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %> Add the following in every page page that you need to use database connectivity. How to write a simple select statement and display the result Select the Last and First Name from Employee Table <% 'On Error Resume Next Dim conn ' Create Connection Object set conn = Server.CreateObject("Adodb.Connection") conn.open "empDSN" set rs = Server.CreateObject("Adodb.Recordset") empSQL = "SELECT lasttname, firstname from Employee" rs.open empSQL, conn If rs.eof then response.write "There are no records in the database" Else Do While Not rs.EOF Response.write rs.fields("lastname") & rs.fields("firstname") & "" rs.MoveNext Loop End If %> <% con.Close %>
back to top
..
..
Databaselisttables
<%@Language=VBScript %> <% ' Create a connection object Set Conn = Server.CreateObject ("ADODB.Connection") ' Open the connection to the database by using ODBC DSN Conn.Open "DSN=MyDSN" ' Open the database schema to query the list of tables. Set Rs = Conn.OpenSchema (adSchemaTables) ' Loop through the list and print the table names Do While Not Rs.EOF Response.Write "
" & Rs ("TABLE_NAME") Rs.MoveNext Loop ' Close and destroy the recordset and connection objects Rs.Close Set Rs = Nothing Conn.Close Set Conn = Nothing %>
back to top
..
..
Databasereadtable
<% ' Example how to read database file by using ODBC Data Source Name (DSN) '======= Change here ! ============ myDataSourceName = "myDSN" ' your ODBC DSN TableToRead = "myTable" ' The name of the table from your ".mdb" file '=================================== '==== Connecting to the database ====================== If IsObject(Session("myDataSourceName_conn")) Then Set conn = Session("myDataSourceName_conn") Else Set conn = Server.CreateObject("ADODB.Connection") conn.open myDataSourceName,"","" Set Session("myDataSourceName_conn") = conn End If sql = "SELECT * From " & TableToRead Set rs= Server.CreateObject("ADODB.Recordset") rs.Open sql, conn, 3, 3 '==== conection is done =============================== %>
Database reading example
Below should be a list of elements
<% '=========== Read and display the data from the table ===== On Error Resume Next rs.MoveFirst count=1 Do while not rs.eof Response.Write count & " ------------------------" & "
" For i = 0 To rs.Fields.Count-1 Response.Write rs.Fields(i).Name & " : " & rs.Fields(i) & "
" next rs.MoveNext count=count+1 Loop '=========== end =========================================== %>
back to top
..
..
DataDSNConnection
Connecting to a database using DSN If IsObject(Session("myDataSourceName_conn")) Then Set conn = Session("myDataSourceName_conn") Else Set conn = Server.CreateObject("ADODB.Connection") conn.open myDataSourceName,"","" Set Session("myDataSourceName_conn") = conn End If
back to top
..
..
DataDSN-LessConnection
ASP Database connection ODBC DSNLess connection example <% Set dbc = Server.CreateObject("ADODB.Connection") MdbFilePath = Server.MapPath("/data/data.mdb") strConn= "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & MdbFilePath & ";uid=Admin;pwd=;" dbc.open strconn %>
back to top
..
..
DataMSSQLconnection
Example how to connect to MS SQL server database
MS SQL CONNECTION TEST
<% set rs = server.createobject("ADODB.Recordset") DsnWebSQL = "Provider=SQLOLEDB;Server=128.121.4.12;Database=DataName;UID=user;PWD=password;" rs.CursorLocation = 3 timer1 = timer response.write "beginning time=" & timer1 & "
" rs.Open "SELECT top 20 * FROM TableName", DsnWebSQL timer2 = timer response.write "time to select record=" & (timer2 - timer1) & "
" Do While rs.EOF = False response.write "
" & rs.Fields(1) rs.MoveNext Loop response.write "
time to fetch " & rs.recordcount & " records =" & timer - timer2 rs.close set rs = nothing %>
back to top
..
..
Date
Date formats Date Parts Date Add and Subtract Date Difference Is this year a Leap year How to calculate Julian Date Date countdown till a given date First and Last day of Month Date Format [ Relative to the date as 2/7/2000 10:37:48 AM ] <%=FormatDateTime(Now(),1) %> Outputs as : Monday, February 07, 2000 <%=FormatDateTime(Now(),2)%> Outputs as : 2/7/2000 <%=Now%> Outputs as : 2/7/2000 10:24:57 AM Date Part [ Relative to the date 2/7/2000 10:37:48 AM ] Day Today is <%=Day(Date)%> Outputs as : Today is 7 Week This is week # <%= DatePart("ww",date)%> of the this year Outputs as : This is week # 7 of this year This is weekday <%= WeekDay(Date)%> of this year Outputs as : This is weekday 2 of this year Today is <%=WeekDayName(WeekDay(Date))%> Outputs as : Today is Monday Month The month Now is <%=Month(Date)%> Outputs : The month Now is 2 Another way, of saying the current month is <%=(DatePart("m",date))%> Outputs : Another way, of saying the current month is 2 The MonthName is <%=MonthName(Month(Date))%> Outputs : The MonthName is February Year The year is <%=Year(Date)%> Outputs : The year is 2000 Date Add and Subtract Add Day 2 Days from 2/9/2000 it will be <%=DateAdd("d",2,CDate("2/9/2000"))%> Outputs : 2 Days from now it will be 2/11/2000 Month 2 Months from 2/9/2000 it will be <%=DateAdd("m",2,CDate("2/9/2000"))%> Outputs : 2 Months from 2/9/2000 it will be 4/9/2000 Year 2 Years from 2/9/2000 it will be <%=DateAdd("yyyy",2,CDate("2/9/2000"))%> Outputs : 2 Years from 2/9/2000 it will be 2/9/2002 Subtract Day 2 Days back from 2/9/2000 it was <%=DateAdd("d",-2,CDate("2/9/2000"))%> Outputs : 2 Days back from now it was be 2/7/2000 Month 2 Months back from 2/9/2000 it was be <%=DateAdd("m",-2,CDate("2/9/2000"))%> Outputs : 2 Months back from 2/9/2000 it was 12/9/1999 Year 2 Years from 2/9/2000 it will be <%=DateAdd("yyyy",-2,CDate("2/9/2000"))%> Outputs : 2 Years back from 2/9/2000 it was 2/9/1998 Date Difference [ Relative Date : 2/7/2000 ] Day Its <%=DateDiff("d","2/7/2000","8/15/1947")*-1 %> days between '8/15/1947' and '2/7/2000' Outputs : Its 19169 days between '8/15/1947' and '2/7/2000' Week Its <%=DateDiff("ww","2/7/2000","8/15/1947")*-1 %> weeks between '8/15/1947' and '2/7/2000' Outputs : Its 2739 weeks between '8/15/1947' and '2/7/2000' Month Its <%=DateDiff("m","2/7/2000","8/15/1947")*-1 %> months between '8/15/1947' and '2/7/2000' Outputs : Its 630 months between '8/15/1947' and '2/7/2000' Quarter Its <%=DateDiff("q","2/7/2000","8/15/1947")*-1 %> quarters between '8/15/1947' and '2/7/2000' Outputs : Its 210 Quarters between '8/15/1947' and '2/7/2000' Year Its <%=DateDiff("yyyy","2/7/2000","8/15/1947")*-1 %> years between '8/15/1947' and '2/7/2000' Outputs : Its 53 between '8/15/1947' and '2/7/2000' Leap Year <% Dim lYear lYear = Year(CDate("2/9/2000")) leap_yes = "is a leap year" leap_no = "is not a leap year" If (lYear mod 4 = 0) AND ((lYear mod 1 0) OR (lYear mod 4 = 0)) then ' It is a Leap Year Response.Write lYear & " " & leap_yes else ' it is not a leap year Response.Write lYear & " " & leap_no End if %gt; Outputs : 2000 is a leap year Julian Date <% d0=DateSerial ("2000", "1", "1") d1=Date - d0 + 1 Response.write "Today's Julian Date Is #" & d1 %> Outputs : Today's Julian Date Is #38 Date Countdown <% dim strDateTime strDateTime = CDate("2/9/2000") strFutureDay = #12/31# Response.write "There are" & INT(strFutureDay - strDateTime) & " more days till December 31st." %> Outputs : There are 327 more days till December 31st. How to find first and last day of the month Calculate first date of current month <% BaseDate = CDate("2/9/2000") FirstOfMonth = DateSerial(Year(BaseDate), Month(BaseDate) + iOffset, 1) Response.write "The first date of this month is " & FirstOfMonth %> Outputs : The first date of this month is 2/1/2000 Calculate last date of current month <% BaseDate = CDate("2/9/2000") EndOfMonth = DateSerial(Year(BaseDate), Month(BaseDate) + 1, 0) Response.write "The last date of this month is " & EndOfMonth %> Outputs : The last date of this month is 2/29/2000
back to top
..
..
Dateadd
Date Add Day 2 Days from 2/9/2000 it will be <%=DateAdd("d",2,CDate("2/9/2000"))%> Outputs : 2 Days from now it will be 2/11/2000 Month 2 Months from 2/9/2000 it will be <%=DateAdd("m",2,CDate("2/9/2000"))%> Outputs : 2 Months from 2/9/2000 it will be 4/9/2000 Year 2 Years from 2/9/2000 it will be <%=DateAdd("yyyy",2,CDate("2/9/2000"))%> Outputs : 2 Years from 2/9/2000 it will be 2/9/2002
back to top
..
..
Datecountdown
Date Countdown <% dim strDateTime strDateTime = CDate("2/9/2000") strFutureDay = #12/31# Response.write "There are" & INT(strFutureDay - strDateTime) & " more days till December 31st." %> Outputs : There are 327 more days till December 31st.
back to top
..
..
Datediff
Date Difference [ Relative Date : 2/7/2000 ] Day Its <%=DateDiff("d","2/7/2000","8/15/1947")*-1 %> days between '8/15/1947' and '2/7/2000' Outputs : Its 19169 days between '8/15/1947' and '2/7/2000' Week Its <%=DateDiff("ww","2/7/2000","8/15/1947")*-1 %> weeks between '8/15/1947' and '2/7/2000' Outputs : Its 2739 weeks between '8/15/1947' and '2/7/2000' Month Its <%=DateDiff("m","2/7/2000","8/15/1947")*-1 %> months between '8/15/1947' and '2/7/2000' Outputs : Its 630 months between '8/15/1947' and '2/7/2000' Quarter Its <%=DateDiff("q","2/7/2000","8/15/1947")*-1 %> quarters between '8/15/1947' and '2/7/2000' Outputs : Its 210 Quarters between '8/15/1947' and '2/7/2000' Year Its <%=DateDiff("yyyy","2/7/2000","8/15/1947")*-1 %> years between '8/15/1947' and '2/7/2000' Outputs : Its 53 between '8/15/1947' and '2/7/2000'
back to top
..
..
Datefirstlast
First and Last day of Month How to find first and last day of the month Calculate first date of current month <% BaseDate = CDate("2/9/2000") FirstOfMonth = DateSerial(Year(BaseDate), Month(BaseDate) + iOffset, 1) Response.write "The first date of this month is " & FirstOfMonth %> Outputs : The first date of this month is 2/1/2000 Calculate last date of current month <% BaseDate = CDate("2/9/2000") EndOfMonth = DateSerial(Year(BaseDate), Month(BaseDate) + 1, 0) Response.write "The last date of this month is " & EndOfMonth %> Outputs : The last date of this month is 2/29/2000
back to top
..
..
Dateformat
Date Format [ Relative to the date as 2/7/2000 10:37:48 AM ] <%=FormatDateTime(Now(),1) %> Outputs as : Monday, February 07, 2000 <%=FormatDateTime(Now(),2)%> Outputs as : 2/7/2000 <%=Now%> Outputs as : 2/7/2000 10:24:57 AM
back to top
..
..
Datejulian
Julian Date <% d0=DateSerial ("2000", "1", "1") d1=Date - d0 + 1 Response.write "Today's Julian Date Is #" & d1 %> Outputs : Today's Julian Date Is #38
back to top
..
..
Dateleap
Leap Year <% Dim lYear lYear = Year(CDate("2/9/2000")) leap_yes = "is a leap year" leap_no = "is not a leap year" If (lYear mod 4 = 0) AND ((lYear mod 1 0) OR (lYear mod 4 = 0)) then ' It is a Leap Year Response.Write lYear & " " & leap_yes else ' it is not a leap year Response.Write lYear & " " & leap_no End if %> Outputs : 2000 is a leap year
back to top
..
..
Datepart
Date Part [ Relative to the date 2/7/2000 10:37:48 AM ] Day Today is <%=Day(Date)%> Outputs as : Today is 7 Week This is week # <%= DatePart("ww",date)%> of the this year Outputs as : This is week # 7 of this year This is weekday <%= WeekDay(Date)%> of this year Outputs as : This is weekday 2 of this year Today is <%=WeekDayName(WeekDay(Date))%> Outputs as : Today is Monday Month The month Now is <%=Month(Date)%> Outputs : The month Now is 2 Another way, of saying the current month is <%=(DatePart("m",date))%> Outputs : Another way, of saying the current month is 2 The MonthName is <%=MonthName(Month(Date))%> Outputs : The MonthName is February Year The year is <%=Year(Date)%> Outputs : The year is 2000
back to top
..
..
Datesub
Date Subtract Day 2 Days back from 2/9/2000 it was <%=DateAdd("d",-2,CDate("2/9/2000"))%> Outputs : 2 Days back from now it was be 2/7/2000 Month 2 Months back from 2/9/2000 it was be <%=DateAdd("m",-2,CDate("2/9/2000"))%> Outputs : 2 Months back from 2/9/2000 it was 12/9/1999 Year 2 Years from 2/9/2000 it will be <%=DateAdd("yyyy",-2,CDate("2/9/2000"))%> Outputs : 2 Years back from 2/9/2000 it was 2/9/1998
back to top
..
..
Dbcommon
I do not wish to write connect script each time. How do I do it ? Now each time you need to access the Database just create the connection object as follows. <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %> Hey, But don't you think that writing this script on each page would not be a good idea in terms of scalability ! A better approach would be to have this code in an include file centrally. Create a file called say 'dbObject.asp' and perhaps place it in the /scripts directory. dbObject.asp might look something like this <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %> Add the following in every page page that you need to use database connectivity.
back to top
..
..
Dbconnect
Connect to Database How to connect to database in ASP There are two ways of connecting ot a database. Using a System DSN 1.) Create a system DSN using the ODBC Wizard in the Control Panel 2.) Connect to the database using a simple connection string: "DSN=System DSN Name" Using a DSN-less connection 1.) Place the Access database file (the *.mdb file) in a web-shared directory 2.) Specify the driver and the physical location of the database file Setting Up a DSN You need to set up a DSN (Data Source Name) for each database that you uses. Following is the process of setting DSN Simply double-click the ODBC applet in the Control Panel -> Choose the System DSN tab -> Click Add Choose the type of database (MS Acccess in this case) -> Click finish. Now type in the Database Name in the Data Source Name box -> Click Select. -> Navigate to the drive and directory where the database is located, and select it. -> Close the window now. Now, its all set to call the database by name in your scripts The system will know which ODBC driver to use and also the location database is located. Now each time you need to access the Database just create the connection object as follows. <% Dim objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myDSN" objConn.Open %>
back to top
..
..
Dbselect
A simple Database Select How to write a simple select statement and display the result Select the Last and First Name from Employee Table <% 'On Error Resume Next Dim conn ' Create Connection Object set conn = Server.CreateObject("Adodb.Connection") conn.open "empDSN" set rs = Server.CreateObject("Adodb.Recordset") empSQL = "SELECT lasttname, firstname from Employee" rs.open empSQL, conn If rs.eof then response.write "There are no records in the database" Else Do While Not rs.EOF Response.write rs.fields("lastname") & rs.fields("firstname") & "" rs.MoveNext Loop End If %> <% con.Close %>
back to top
..
..
Directory
Get the filenames of a directory Attributes of a Directory Create a Directory Delete of a Directory Get the filenames in a directory Replace "directoryname" with your directory name. Note : Replace 'directoryname' with the name od directory you wish to read In case of NT the directory mush have read permission for being read from anonymous account <%Set MyDirectory=Server.CreateObject("Scripting.FileSystemObject") Set MyFiles=MyDirectory.GetFolder(Server.MapPath("directoryname")) For each filefound in MyFiles.files Response.write filefound.Name Next %> Attributes of a directory <% ' Code for setting the target directory 'images' Set fso = Server.CreateObject ("scripting.filesystemobject") location = server.mappath("images") Set folder = fso.GetFolder(location) %> Size : <% =folder.size %> Output : Size : 84 bytes Created : <% =folder.datecreated %> Output : Created : 1/23/2000 10:13:13 AM Modified : <% =folder.datelastmodified %> Output : Modified : 1/23/2000 10:13:14 AM Name : <% =folder.name %> Output : Name : images Create a directory Note : You'll need permissions on the parent directory set to allow the IUSR_machinename to create the directory. This means that the IUSR will need to be given NTFS Change permissions <% set fs=createobject("scripting.filesystemobject") MyFolder=server.mappath("/download/incoming/") If NOT fs.folderexists(MyFolder) then fs.createfolder(MyFolder) End If ' Check if the creation was a success or not If fs.folderexists(MyFolder) then Response.write "Success" Else Response.write "Failure." End If %> Delete a directory Note : You'll need permissions on the parent directory set to allow the IUSR_machinename to create the directory. This means that the IUSR will need to be given NTFS Change permissions <% set fs=createobject("scripting.filesystemobject") MyFolder=server.mappath("/download/incoming/") set delDir = fs.getfolder(myFolder) delDir.delete set delDir = Nothing 'Check if the deletion was a success or Not If fs.folderexists(myFolder) then Response.write "Deleted" Else Response.write "Error" End If %>
back to top
..
..
Dirattr
Attributes of a directory <% ' Code for setting the target directory 'images' Set fso = Server.CreateObject ("scripting.filesystemobject") location = server.mappath("images") Set folder = fso.GetFolder(location) %> Size : <% =folder.size %> Output : Size : 84 bytes Created : <% =folder.datecreated %> Output : Created : 1/23/2000 10:13:13 AM Modified : <% =folder.datelastmodified %> Output : Modified : 1/23/2000 10:13:14 AM Name : <% =folder.name %> Output : Name : images
back to top
..
..
Dircreate
Create a directory Note : You'll need permissions on the parent directory set to allow the IUSR_machinename to create the directory. This means that the IUSR will need to be given NTFS Change permissions <% set fs=createobject("scripting.filesystemobject") MyFolder=server.mappath("/download/incoming/") If NOT fs.folderexists(MyFolder) then fs.createfolder(MyFolder) End If ' Check if the creation was a success or not If fs.folderexists(MyFolder) then Response.write "Success" Else Response.write "Failure." End If %>
back to top
..
..
Dirdelete
Delete a directory Note : You'll need permissions on the parent directory set to allow the IUSR_machinename to create the directory. This means that the IUSR will need to be given NTFS Change permissions <% set fs=createobject("scripting.filesystemobject") MyFolder=server.mappath("/download/incoming/") set delDir = fs.getfolder(myFolder) delDir.delete set delDir = Nothing 'Check if the deletion was a success or Not If fs.folderexists(myFolder) then Response.write "Deleted" Else Response.write "Error" End If %>
back to top
..
..
Dirfiles
Get the filenames in a directory Replace "directoryname" with your directory name. Note : Replace 'directoryname' with the name od directory you wish to read In case of NT the directory mush have read permission for being read from anonymous account <%Set MyDirectory=Server.CreateObject("Scripting.FileSystemObject") Set MyFiles=MyDirectory.GetFolder(Server.MapPath("directoryname")) For each filefound in MyFiles.files Response.write filefound.Name Next %>
back to top
..
..
DirRecursive
<% '********** DirFolder - Returns Delimited String of All folders and files Dim ArrayOutput, StringOutput, StringOutputType, StringOutputName, delimiter delimiter = "|" Function DirFolder ( StartPath ) On error resume next Dim fso, folderObject, folderObject2, subFolder, Files, File Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(StartPath) Set folderObject2 = folderObject.SubFolders For Each subFolder in FolderObject2 StringOutput = StringOutput & subFolder & delimiter StringOutputType = StringOutputType & "Folder" & delimiter StringOutputName = StringOutputName & subFolder & delimiter DirFolder (subFolder) 'Recursive Set Files = subFolder.Files For Each File in Files StringOutput = StringOutput & File & delimiter StringOutputType = StringOutputType & File.Type & delimiter StringOutputName = StringOutputName & File.Name & delimiter Next Next end function '************************************************** DirFolder (Server.MapPath("/")) ArrayOutput = Split (StringOutput, delimiter) For Each Item in ArrayOutput Response.Write Item & "
" next %>
back to top
..
..
DirRecDetails
<% '********** DirFolder - Returns Delimited String of All folders and files Dim ArrayOutput, StringOutput, StringOutputType, StringOutputName, delimiter delimiter = "|" Function DirFolder ( StartPath ) On error resume next Dim fso, folderObject, folderObject2, subFolder, Files, File Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(StartPath) Set folderObject2 = folderObject.SubFolders For Each subFolder in FolderObject2 StringOutput = StringOutput & subFolder & delimiter StringOutputType = StringOutputType & "Folder" & delimiter StringOutputName = StringOutputName & subFolder.Name & delimiter DirFolder (subFolder) 'Recursive Set Files = subFolder.Files For Each File in Files StringOutput = StringOutput & File & delimiter StringOutputType = StringOutputType & File.Type & delimiter StringOutputName = StringOutputName & File.Name & delimiter Next Next end function '************************************************** DirFolder (Server.MapPath("/")) ArrayOutput = Split (StringOutput, delimiter) ArrayOutputType = Split (StringOutputType, delimiter) ArrayOutputName = Split (StringOutputName, delimiter) i=0 For Each Item in ArrayOutput Response.Write Item & " " & ArrayOutputType(i) & " " & ArrayOutputName(i) & "
" i = i+1 next %>
back to top
..
..
DomainNameValidation
function Is_Invalid_Domainname(domainname) dim re set re = new RegExp ' list of invalid characters in a domain name. re.Pattern = "[/\\""\[\]:<>\+=;,@!#$%^&\(\)\{\}\|~]" Is_Invalid_DomainName = re.Test(domainname) end function
back to top
..
..
Doublequote
How to insert quote into a string: MyString = "He said " & chr(34) & "Hello" & chr(34) & " to me!" If displayed, the string would appear as : He said "Hello" to me!
back to top
..
..
File
Get the filenames of a directory Copy a File or Files Move a File or Files Delete a File or Files Read contents of File Write to a File Append to a File Get the filenames in a directory Replace "directoryname" with your directory name. Note : Replace 'directoryname' with the name od directory you wish to read In case of NT the directory mush have read permission for being read from anonymous account <% Set MyDirectory=Server.CreateObject("Scripting.FileSystemObject") Set MyFiles=MyDirectory.GetFolder(Server.MapPath("directoryname")) For each filefound in MyFiles.files Response.write filefound.Name Next %> Copy a File Use the file system operations, Copy is supported by the FileSystemObject object. CopyFile source, destination[, overwrite] <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.CopyFile "C:\InetPub\wwwroot\*.txt", "C:\Windows\Temp" Set fileObj = Nothing >% Note : The user must have write permissions to copy a file from one directory to another. Move a File or Files Use the file system operations, Rename is supported by the FileSystemObject object. MoveFile source, destination <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.MoveFile "C:\InetPub\wwwroot\*.txt", "C:\Windows\Temp" Set fileObj = Nothing %> Note : The user must have minimum delete permissions on the source directory and write permissions on the destination directory. Delete a File or Files <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.DeleteFile "C:\InetPub\wwwroot\*.txt", False Set fileObj = Nothing %> Note : The optional parameter for the DeleteFile method is Force. This defaults to False, and determines whether or not read-only files will be deleted. Only if Force is set to True will read-only files be deleted. Read a File <% Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/readfile.txt") Set thisfile= fs.OpenTextFile(filename,1,False) Do until thisfile.AtEndOfStream thisline = thisfile.readline If thisline "" then Response.write thisline End If Loop thisfile.close set thisfile = Nothing set fs = Nothing %> Write to a File <% Set myText = "Hi, I am writing to a file " Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/writefile.txt") Set thisfile= fs.OpenTextFile(filename,2,True) thisfile.writeline(myText) thisfile.close Set thisfile = Nothing Set fs = Nothing %> Append to a File <% Set myText = "Hi, I am writing to a file " Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/appendfile.txt") Set thisfile = fs.OpenTextFile(filename,8,True) thisfile.writeline(myText) thisfile.close Set thisfile = Nothing Set fs = Nothing %> Note : Notice the numbers 1,2 and 8 in the above examples. Here is what they represent 1: Opens file for reading. Cannot write to this file 2: Opens file for writing. This file can't be read. Writing anything to this file would overwrite the previous contents. 8: Opens the file for appending. The previous contents is not overwritten. Notice the "True" and "False" parameters in examples above True: The file will be created if it doesn't exist False: A new will not be created if it doesn't already exist.
back to top
..
..
Fileappend
Append to a File <% Set myText = "Hi, I am writing to a file " Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/appendfile.txt") Set thisfile = fs.OpenTextFile(filename,8,True) thisfile.writeline(myText) thisfile.close Set thisfile = Nothing Set fs = Nothing %> Notice the numbers 1,2 and 8 in the above examples. Here is what they represent 1: Opens file for reading. Cannot write to this file 2: Opens file for writing. This file can't be read. Writing anything to this file would overwrite the previous contents. 8: Opens the file for appending. The previous contents is not overwritten. Notice the "True" and "False" parameters in examples above True: The file will be created if it doesn't exist False: A new will not be created if it doesn't already exist.
back to top
..
..
Fileappend2
<% Function AppendToFile (RelativeFilePath, LineToAppend) Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath(RelativeFilePath) Set thisfile = fs.OpenTextFile(filename,8,True) thisfile.writeline(LineToAppend) thisfile.close Set thisfile = Nothing Set fs = Nothing end function RelativeFilePath = "/config/config.txt" LineToAppend = "User=NewUser" AppendToFile RelativeFilePath, LineToAppend %>
back to top
..
..
Filecopy
Copy a File Use the file system operations, Copy is supported by the FileSystemObject object. CopyFile source, destination[, overwrite] <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.CopyFile "C:\InetPub\wwwroot\*.txt", "C:\Windows\Temp" Set fileObj = Nothing %> Note : The user must have write permissions to copy a file from one directory to another.
back to top
..
..
Filedelete
Delete a File or Files <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.DeleteFile "C:\InetPub\wwwroot\*.txt", False Set fileObj = Nothing %> Note : The optional parameter for the DeleteFile method is Force. This defaults to False, and determines whether or not read-only files will be deleted. Only if Force is set to True will read-only files be deleted.
back to top
..
..
Filedir
Get the filenames in a directory Replace "directoryname" with your directory name. Note : Replace 'directoryname' with the name od directory you wish to read In case of NT the directory mush have read permission for being read from anonymous account <% Set MyDirectory=Server.CreateObject("Scripting.FileSystemObject") Set MyFiles=MyDirectory.GetFolder(Server.MapPath("directoryname")) For each filefound in MyFiles.files Response.write filefound.Name Next %>
back to top
..
..
Filefilter
<% Function IfCanceled(ID) CanceledFile = "/canceled/canceled.txt" IfCanceled=False Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath(CanceledFile) Set thisfile= fs.OpenTextFile(filename,1,False) Do until thisfile.AtEndOfStream thisline = thisfile.readline If LCase(ID)=LCase(thisline) then IfCanceled=True Loop thisfile.close set thisfile = Nothing set fs = Nothing end function If (IfCanceled(ID) then Response.Write "Canceled." else Response.Write "Valid." end if %>
back to top
..
..
FileFindString
<% Function RegExpTest(patrn, strng) Dim regEx, Match, Matches ' Create variable. Set regEx = New RegExp ' Create regular expression. regEx.Pattern = "\b" & patrn & "\b" ' Set pattern. regEx.IgnoreCase = True ' Set case insensitivity. regEx.Global = True ' Set global applicability. Set Matches = regEx.Execute(strng) ' Execute search. RegExpTest = Matches.Count End Function Function SearchInFileResult(PathToFile, SearchString) If Len(SearchString) < 3 Then SearchInFileResult = 0 Else SearchString = Replace(SearchString, ",", "") SearchString = Replace(SearchString, ".", "") SearchWords = Split(SearchString, " ") Dim FoundCounter FoundCounter = 0 Set fso = CreateObject("Scripting.FileSystemObject") Set File = fso.GetFile(PathToFile) For Each SearchWord In SearchWords Set TextStream = File.OpenAsTextStream If Len(SearchWord) < 3 Then Else S = TextStream.ReadAll ThisSearchResult = RegExpTest(Trim(SearchWord), S) FoundCounter = FoundCounter + ThisSearchResult End If TextStream.Close Next Set fso = Nothing Set File = Nothing Set TextStream = Nothing SearchInFileResult = FoundCounter End If End Function Sub File_Find_String (StartPath, SearchString) On error resume next Dim fso, folderObject, folderObject2, subFolder, Files, File Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(StartPath) Set folderObject2 = folderObject.SubFolders For Each subFolder In folderObject2 'If IfPublicDir(subFolder.Name) = 1 Then 'StringOutput = StringOutput & subFolder & delimiter 'StringOutputType = StringOutputType & "Folder" & delimiter 'StringOutputName = StringOutputName & subFolder.Name & delimiter DirFolder (subFolder) 'Recursive Set Files = subFolder.Files For Each File In Files 'Response.Write File Hits = SearchInFileResult(File, SearchString) If Hits > 0 Then StringOutput = StringOutput & Hits & " " & File & delimiter StringOutputType = StringOutputType & File.Type & delimiter StringOutputName = StringOutputName & File.Name & delimiter End If Next 'End If Next End Sub Dim nl, delimiter, StringOutput, StringOutputType, StringOutputName nl = Chr(13) & Chr(10) delimiter = "|" StartPath = Server.MapPath("/") SearchString = "mail" Response.Write "Search result from : " & StartPath & "
" Response.Write "Search Criteria : " & SearchString & "
" File_Find_String StartPath, SearchString ResultArray = Split(StringOutput, Delimiter) For Each Item In ResultArray Response.Write Item & "
" next %>
back to top
..
..
Filemove
Move a File or Files Use the file system operations, Rename is supported by the FileSystemObject object. MoveFile source, destination <% Dim fileObj Set fileObj = Server.CreateObject("Scripting.FileSystemObject") fileObj.MoveFile "C:\InetPub\wwwroot\*.txt", "C:\Windows\Temp" Set fileObj = Nothing %> Note : The user must have minimum delete permissions on the source directory and write permissions on the destination directory.
back to top
..
..
Fileread
Read a File <% Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/readfile.txt") Set thisfile= fs.OpenTextFile(filename,1,False) Do until thisfile.AtEndOfStream thisline = thisfile.readline If thisline "" then Response.write thisline End If Loop thisfile.close set thisfile = Nothing set fs = Nothing %> Read ALL <% Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/files/data.txt") Set thisfile= fs.OpenTextFile(filename,1,False) S = thisfile.ReadAll thisfile.close Response.Write S set thisfile = Nothing set fs = Nothing %> Notice the numbers 1,2 and 8 in the above examples. Here is what they represent 1: Opens file for reading. Cannot write to this file 2: Opens file for writing. This file can't be read. Writing anything to this file would overwrite the previous contents. 8: Opens the file for appending. The previous contents is not overwritten. Notice the "True" and "False" parameters in examples above True: The file will be created if it doesn't exist False: A new will not be created if it doesn't already exist.
back to top
..
..
Filewrite
Write to a File <% Set myText = "Hi, I am writing to a file " Set fs = CreateObject("Scripting.FileSystemObject") filename = server.mappath("/somedirectory/writefile.txt") Set thisfile= fs.OpenTextFile(filename,2,True) thisfile.writeline(myText) thisfile.close Set thisfile = Nothing Set fs = Nothing %> Notice the numbers 1,2 and 8 in the above examples. Here is what they represent 1: Opens file for reading. Cannot write to this file 2: Opens file for writing. This file can't be read. Writing anything to this file would overwrite the previous contents. 8: Opens the file for appending. The previous contents is not overwritten. Notice the "True" and "False" parameters in examples above True: The file will be created if it doesn't exist False: A new will not be created if it doesn't already exist.
back to top
..
..
FP oswsadm.exe
To view the command-line options for Owsadm.exe, follow these steps: Click Start, and then click Run. In the Open box, type cmd and then press ENTER. At the operating system prompt, go to the \Program Files\Common Files\Microsoft Shared\Web Server Extensions\50\Bin folder, and then type the following: owsadm.exe -h Command-line Options for Owsadm.exe Usage: owsadm.exe [-help] [-operation
] [-web
] [-multihost
] [-username
] [-password
] [-ipaddress
] [-destination
] [-filename
] [-propertyname
] [-propertyvalue
] [-name
] [-command
] [-databaseserver
] [-databasename
] [-databaseuser
] [-databasepassword
] [-siteprovision
] [-access
] Short form of each option is the first letter, except for -pw for -password, -pn for -propertyname, -pv for -propertyvalue, -cr for cloneright, -cu for cloneusers, -ds for -databaseserver, -dn for -databasename, -du for -databaseuser, -dp for -databasepassword, -sp for -siteprovision SMTP mail server settings owsadm -o setproperty -p
-pn SMTPHost -pv smarthost Additionally, you can set subscriptions properties with the following: owsadm -o setproperty -p /lm/w3svc/1 -pn MailReplyTo -pv webmaster@owslab1.com owsadm -o setproperty -p /lm/w3svc/1 -pn MailSender -pv robot@owslab11.gov examples: owsadm.exe -o merge -p 80 -w webname owsadm.exe -o delete -p 80 -w webname owsadm.exe -o rename -p 80 -w webname -d newname owsadm.exe -o setDirExec -p 80 -w webname -d folder owsadm.exe -o roles -p 80 -w webname -n nameofrole -c command -cr rolename -cu owsadm.exe -o anonrole -p 80 -w webname -c enable -n rolename owsadm.exe -o anonrole -p 80 -w webname -c disable -n rolename owsadm.exe -o roleusers -p 80 -w webname -n nameofrole -c command -u usernames owsadm.exe -o users -p 80 -w webname -c command -u username -pw password owsadm.exe -o rolerights -p 80 -w webname -n nameofrole -c command -r rightnames owsadm.exe -o recalc -p 80 -w webname owsadm.exe -o putfile -p 80 -w webname -d url -f filename owsadm.exe -o recalcfile -p 80 -w webname -d url owsadm.exe -o setproperty -p 80 -w webname -pn SourceControlProject -pv "
" owsadm.exe -o install -p 80 -u user owsadm.exe -o create -p 80 -w webname owsadm.exe -o setadminport -p 10865 owsadm.exe -o accountlimits -p 80 -limit 10 owsadm.exe -o upgrade -p 80 owsadm.exe -o uninstall -p 80 owsadm.exe -o check -p 80 owsadm.exe -o check -p all owsadm.exe -o disable -p 80 owsadm.exe -o getproperty -pn AccessControl owsadm.exe -o databaseconnection -ds machinename -du accountname -dp accountpassword owsadm.exe -o backupdb -p 80 owsadm.exe -o restoredb -p 80
back to top
..
..
GetUrl
<% 'It is needs to be registered with "regsvr32 c:\winnt\system32\msinet.ocx" Set d = CreateObject("InetCtls.Inet") d.AccessType=0 'd.Document= 'd.hInternet="13369348" 'd.Password= d.Protocol=4 'd.Proxy= d.RemoteHost="www.microsoft.com" d.RemotePort=80 d.RequestTimeout=60 d.URL="http://www.microsoft.com" S = d.OpenURL("http://www.microsoft.com") B=d.ResponseCode Response.Write S Response.Write B Set d = Nothing %>
back to top
..
..
Global
Redirect user using Global.asa Generate a Unique Session ID How to redirect using Global.asa file Sub Session_OnStart `Check to see if current page is the correct login page loginPage = "/Login/userLogin.asp" `Get the current page currentPage = Request.ServerVariables("SCRIPT_NAME") `If page is not correct then send the visitor to the correct login page If strcomp(currentPage, loginPage, 1) Then Response.Redirect( StartPage) End If End Sub Generate Unique Session ID <% If session("userid")="" or session("userid") = 0 then Randomize userid = Int(99999 * Rnd + 3) session("userid") = userid else userid = session("userid") end if session("userid") = userid %> This script allows to generate a unique number, called session ID to each visitor. Since its for a single session, the number would repeat but is safe enough.
back to top
..
..
Globalredirect
How to redirect using Global.asa file
back to top
..
..
Globalsession
Generate Unique Session ID <% If session("userid")="" or session("userid") = 0 then Randomize userid = Int(99999 * Rnd + 3) session("userid") = userid else userid = session("userid") end if session("userid") = userid %> This script allows to generate a unique number, called session ID to each visitor. Since its for a single session, the number would repeat but is safe enough.
back to top
..
..
Httpheader
How to read the http header : <% Response.Writ