2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

52
2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

Page 1: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

M0194 Web-based Programming Lanjut

Session 4

Page 2: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

2

The Scripting Runtime Library Objects Scripting Objects Scripting.Dictionary Object Scripting.FileSystemObject Object

Drive Object Folder Object File Object

Scripting.TextStream Object

Page 3: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

3

Scripting Objects

Scripting languages have an object model. The model is for the objects that the scripting language

provide As opposed to the objects like Request and Response that

are provided directly by the ASP DLL

The scripting objects are provided by the Microsoft Scripting Runtime Library (scrrun.dll), which installed with the default Active Scripting script engine.

Page 4: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

4

Different Types of Objects and Components ‘Object’ and ‘component’ are all accessible in the

same way - through COM. Conceptually, can be divided into 4 groups:

Intrinsic ASP objects such as ObjectContext, Request, Response, Application, Session, Server and ASPError.

Scripting objects that are made available through the Scripting Runtime Library. These are Dictionary, FileSystem and TextStream.

Installable components are those provided by Microsoft in a standard installation of IIS 5.0 and ASP 3.0.

Other components that we either buy from independent vendors, find on the Web, or create ourselves.

Page 5: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

5

The VBScript and JScript Scripting Objects Microsoft provides 3 main objects as part of the Scripting Runtime

Library: The Dictionary object provides a useful storage object that we can

use to storage values, accessed and referenced by their name rather than by index. For example, it’s ideal for storing the name/value pairs that we retrieve from the ASP Request object.

The FileSystemObject object provides us with access to the underlying file system on the server. We can use FileSystemObject object to iterate through the machine’s local and networked drives, folders and files.

The TextStream object provides access to files stored on disk, and is used in conjunction with the FileSystemObject. It can read from or write to text (sequential) files. It can only be instantiated via the FileSystemObject object, so you might prefer to think of it as a child of that object.

Page 6: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

6

The VBScript and JScript Scripting Objects

TextStream Object

Dictionary Object

FileSystemObject Object

Drives Collection

Drive Object

Folders Collection

Folder Object

Files Collection

File Object

FileSystemObject object acts as ‘parent’ for a series of other objects and collection that we use to interact with the file system.

Scripting Run-time

Page 7: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

7

Creating Instances of Objects and Components Using the Server.CreateObject Method

Using the <OBJECT> element

<%

Dim objThis

Set objThis = Server.CreateObject(“ADODB.Connection”)

%>

<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”>

<PARAM NAME=“param1” VALUE=“value1”>

<PARAM NAME=“param2” VALUE=“value2”>

</OBJECT>

Page 8: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

8

Creating Instances of Objects and Components Specifying a ClassID

<OBJECT ID = “objThis” RUNAT=“SERVER”

CLASSID=“clsid:892D6DA7-E0F9-11D2-B2E9-00105A42AF30”>

<PARAM NAME=“param1” VALUE=“value1”>

<PARAM NAME=“param2” VALUE=“value2”>

</OBJECT>

When we come to instantiating objects on our own server, we should be aware of what actually is installed in the way of objects and components.

So when we create instances of objects in our ASP code, we can safely use the PROGID string.

This is why the ClassID is rarely used in ASP pages.

Page 9: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

9

Creating Instances of Objects and Components Setting the Scope of Object Instances

By default, all object and component instances have page scope. This means that they exist only as long as the page is executing in ASP.

If we place the <OBJECT> declaration in the global.asa file that exists in the root directory of our Web site or virtual application, we can specify that an object or component should have application or session scope instead.

Creating objects with Application-Level Scope

Creating objects with Session-Level Scope

<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”

SCOPE=“APPLICATION” >

</OBJECT>

<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”

SCOPE=“SESSION” >

</OBJECT>

Page 10: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

10

Creating Instances of Objects and ComponentsThe Difference between Server.CreateObject &

<OBJECT> Server.CreateObject

creates an instance of the object immediately. can remove objects from a Session or Application

The <OBJECT> element only creates an instance of the object it specifies when we

first reference that object. So if we stop using the objectin our code, it won’t get created.

cannot remove objects from a Session or Application if they were created using <OBJECT>

Page 11: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

11

The Scripting.Dictionary Object Many Microsoft languages provide collections. We

can think a collection as being like an array, but we don’t have to worry about which row or column the data is in, we just access it using a unique key.

VBScript and JScript both offer a similar object with the collection, known as the Scripting Dictionary (or just Dictionary) object. This acts like a two-dimensional array, holding the key and the related item of data together.

Page 12: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

12

Creating and Using Dictionary Objects

<!-- Server-side with an OBJECT element -->

<OBJECT ID = “objMyData” RUNAT=“SERVER” SCOPE=“PAGE”

PROGID=“Scripting.Dictionary” >

</OBJECT>

‘ In VBScript

Dim objMyData

Set objMyData = Server.CreateObject(“Scripting.Dictionary”)

// In JSCript

var objMyData = Server.CreateObject(“Scripting.Dictionary”)

The Dictionary object can also be used client-side in Internet Explorer.

Page 13: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

13

The Dictionary Object Members SummaryProperty Description

CompareMode (VBScript only). Sets or returns the string comparison mode for the keys.

Count Read only. Returns the number of key/item pairs in the Dictionary.

Item (key) Sets or returns the value of the item for the specified key.

Key (key) Sets the value of a key.

Method Description

Add (key, item) Adds the key/item pair to the Dictionary.

Exists (key) Returns True if the specified key exists or False if not.

Items ( ) Returns an array containing all the items in a Dictionary object.

Keys ( ) Returns an array containing all the keys in a Dictionary object.

Remove (key) Removes a single key/item pair specified by key.

RemoveAll ( ) Removes all the key/item pairs.

The Dictionary Object’s Properties

The Dictionary Object’s Methods

Page 14: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

14

Adding Items To and Removing Items From a Dictionary‘In VBScript :objMyData.Add “MyKey”, “MyItem” ‘Add value MyItem with key MyKeyobjMyData.Add “YourKey”, “YourItem” ‘Add value YourItem with key YourKeyblnIsThere = objMyData.Exists(“MyKey”) ‘Returns True because the item existsStrItem = objMyData.Item(“YourKey”) ‘Retrieve value of YourKeyStrItem = objMyData.Remove(“MyKey”) ‘Retrieve and remove MykeyobjMyData.RemoveAll ‘Remove all the items

// In JScript :objMyData.Add (‘MyKey’, ‘MyItem’); ‘Add value MyItem with key MyKeyobjMyData.Add (‘YourKey’, ‘YourItem’); ‘Add value YourItem with key YourKeyvar blnIsThere = objMyData.Exists(‘MyKey’); ‘Returns True because the item existsvar StrItem = objMyData.Item(‘YourKey’); ‘Retrieve value of YourKeyvar StrItem = objMyData.Remove(‘MyKey’); ‘Retrieve and remove MykeyobjMyData.RemoveAll(); ‘Remove all the items

Page 15: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

15

Changing the Value of a Key or Item

objMyData.Item(“MyKey”) = “NewValue” ‘ in VBScript

objMyData.Item(‘MyKey’) = ‘NewValue’; // in JScript

If the key we specified isn’t found in the Dictionary, a new key/item pair is created with the key as MyKey and the item value as NewValue.

If we try to retrieve an item using a key that doesn’t exists, we not only get an empty string as the result (as we’d expect) but also a new key/item pair is added to the Dictionary. This has the key we specified, but with the item value left empty.

To change the value of the item with the key MyKey, we use :

To change the value of a key, without changing the value of the corresponding item, we use the Key property. If the specified key isn’t found, a Runtime error is generated.

objMyData.Key(“MyKey”) = “MyNewKey” ‘ in VBScript

objMyData.Key(‘MyKey’) = ‘MyNewKey’; // in JScript

Page 16: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

16

Iterating Through a Dictionary‘In VBScript :

arrKeys = objMyData.Keys ‘Get all the keys into arrayarrItems = objMyData.Items ‘Get all the items into array

For intLoop = 0 To objMyData.Count -1 ‘Iterate through the array strThisKey = arrKeys(intLoop) ‘This is the key value strThisItem = arrItems(intLoop) ‘This is the item (data) valueNext

// In JScript :

// Get VB-style arrays using the Keys() and Items() methodvar arrKeys = new VBArray (objMyData.Keys()).toArray();var arrItems = new VBArray (objMyData.Items()).toArray();

for (intLoop = 0; intLoop< objMyData.Count ; intLoop++) { // Iterate through the array strThisKey = arrKeys[intLoop]; // This is the key value strThisItem = arrItems[intLoop]; // This is the item (data) value}

Page 17: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

17

Iterating Through a Dictionary Alternatively in VBScript, we can use For Each… Next

construct to do the same:

‘ Iterate the Dictionary as a collection in VBScript

For Each objItem in arrItems

Response.Write objItem & “ = “ & arrItems(objItem) & “<BR>”

Next

Page 18: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

18

The Scripting.FileSystemObject Object The FileSystemObject object

provides access to the computer’s file system allowing us to manipulate text files, folders and drives Available in VBScript and JScript for use in ASP pages on the

server. Can also be used client-side in IE 5 providing that the pages have the .hta file extension, to indicate

that they are part of a Hypertext Application (HTA).

A Hypertext Application is made up of a special ‘trusted’ pages that contain the <HTA:APPLICATION> element in the <HEAD> section of the page, for example:

<HTA:APPLICATION ID=“objMyApp” APPLICATIONNAME=“myAPP”>

Page 19: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

19

The Scripting.FileSystemObject ObjectWe can create an instance of the FileSystemObject object using:

<!-- Server-side with an OBJECT element -->

<OBJECT ID = “objFSO” RUNAT=“SERVER” SCOPE=“PAGE”

PROGID=“Scripting.FileSystemObject” >

</OBJECT>

‘ In VBScript

Dim objMyFSO

Set objMyFSO = Server.CreateObject(“Scripting.FileSystemObject”)

// In JSCript

var objMyFSO = Server.CreateObject(“Scripting.FileSystemObject”)

The type library for the complete scripting Runtime library can be added to any ASP page using:

<!-- METADATA TYPE=“typelib” FILE=“C:\WinNT\System32\scrrun.dll” -->

Page 20: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

20

The Scripting.FileSystemObject Members Summary

Property Description

Drives Returns the collection of Drive objects that are available from the local machine. This includes network drives that are mapped from this machine.

Method Description

DriveExists (drivespec)

Returns True if the drive specified in drivespec exists, or False if not. The drivespec parameter can be a drive letter as a string or a full absolute path for a folder or file.

GetDrive (drivespec)

Returns a Drive object corresponding to the drive specified in drivespec. The format for drivespec can include the colon, path separator or be a network share, i.e. “c”, “c:”, ”c:\” or “\\machine\sharename”

GetDriveName (drivespec)

Return the name of the drive specified in drivespec as a string. The drivespec parameter must be an absolute path to a file or folder, or just the drive letter such as “c:” or just “c”.

The FileSystemObject’s Property

The FileSystemObject’s Methods for Working with Drives

Page 21: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

21

The Scripting.FileSystemObject Members Summary

Method Description

BuildPath (path, name)

Adds the file or folder specified in name to the existing path, adding a path separator character (‘\’) if required.

CopyFolder (source, destination, overwrite)

Copies the folder (s) specified in source (wildcards can be included) to the folder specified in destination, including all the files contained in the source folder(s). If source contains wildcards or destination ends with a path separator character (‘\’), then destination is assumed to be a folder into which the copied folder(s) will be placed. Otherwise it is assumed to be a full path and name for a new folder to be created. An error will occur if the destination folder already exists and the optional overwrite parameter is set to False. The default for overwrite is True.

CreateFolder (foldername)

Creates a new folder which has the path and name specified in foldername. An error occurs if the specified folder already exists.

The FileSystemObject’s Methods for Working with Folders

Page 22: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

22

The Scripting.FileSystemObject Members SummaryMethod Description

DeleteFolder (folderspec, force)

Deletes the folder or folders specified in folderspec (wildcards can be included in the final component of the path) together with all their contents. If the optional force parameter is set to True, the folders will be deleted even if their read-only attribute (or that any contained files) is set. The default for force is False.

FolderExists (folderspec)

Returns True if the folder specified in folderspec exists, or False if not. The folderspec parameter can contain an absolute or relative path for the folder, or just the folder name to look in the current folder.

GetAbsolutePathName (pathspec)

Takes a path that unambiguously identifies a folder and, taking into account the current folder’s path, returns a full path specification for the pathspec folder. For example, if the current folder is “c:\docs\sales\” and pathspec is “jan”, the returned value is “c:\docs\sales\jan”. Wildcards and the “..” and “\\” path operators are accepted.

Page 23: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

23

The Scripting.FileSystemObject Members Summary

Method Description

GetFolder (folderspec)

Returns a Folder object corresponding to the folder specified in folderspec. This can be a relative or absolute path to the required folder.

GetParentFolder (pathspec)

Returns the name of the parent folder of the file or folder specified in pathspec. Doesn’t check for existence of the folder.

GetSpecialFolder (folderspec)

Returns a Folder object corresponding to 1 of the special Windows folders. The permissible values for folderspec are WindowsFolder (0), SystemFolder (1) and TemporaryFolder (2).

MoveFolder (source, destionation)

Moves the folder or folders specified in source to the folder specified in destination. Wildcards can be included in source, but not in destination. If source contains wildcards or destination ends with a path separator character (‘\’) then destination is assumed to be the folder in which to place the moved folders. Otherwise it is assumed to be a full path and name for a new folder. An error will occur if the destination folder already exists.

Page 24: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

24

The Scripting.FileSystemObject Members Summary

Method Description

CopyFile (source, destination, overwrite)

Copies the file or files specified in source (wildcards can be included) to the folder specified in destination. If source contains wildcards or destination ends with a path separator character (‘\’), then destination is assumed to be a folder. Otherwise is assumed to be a full path and name for the new file. An error will occur if the destination file already exists and the optional overwrite parameter is set to False. The default for overwrite is True.

CreateTextFile (filename, overwrite, unicode)

Creates a new text file on disk with the specified filename, and returns a TextStream object that refers to it. If the optional overwrite parameter is set to True, any existing file with the same path and name will be overwritten. The default for for overwrite is False. If the optional unicode parameter is set to True, the content of the file will be stored as Unicode text. The default for unicode is False.

DeleteFile (filespec, force)

Deletes the file or files specified in filespec (wildcards can be included). If the optional force parameter is set to True, the file(s) will be deleted even if the Read-only attribute is set. The default for force is False.

The FileSystemObject’s Methods for Working with Files

Page 25: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

25

The Scripting.FileSystemObject Members Summary

Method Description

FileExists (filespec)

Returns True if the file specified in filespec exists, or False if not. The filespec parameter can contain an absolute or relative path for the file, or just the filename to look in the current folder.

GetBaseName (filespec)

Returns just the name of a file specified in filespec, i.e. with the path and file extension removed

GetExtensionName (filespec)

Returns just the file extension of a file specified in filespec, i.e. with the path and filename removed.

GetFile (filespec) Returns a File object corresponding to the file specified in filespec. This can be a relative or absolute path to the required file.

GetFileName (pathspec)

Returns the name part of the path and filename specified in pathspec, or the last folder name of there is no file name. Doesn’t check for existence of the file or folder.

GetTempName ( ) Returns a randomly generated file name, which can be used for performing operations that require a temporary file or folder.

Page 26: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

26

The Scripting.FileSystemObject Members Summary

Method Description

MoveFile (source, destination)

Moves the file or files specified in source to the folder specified in destination. Wildcards can be included in source but not in destination. If source contains wildcards or destination ends with path separator character (‘\’), then destination is assumed to be a folder. Otherwise it is assumed to be a full path and name for the new file. An error will be occur if the destination file already exists.

OpenTextFile (filename, iomode, create, format)

Creates a file named filename, or opens an existing file named filename, and returns a TextStream object that refers to it. The filename parameter can contain an absolute or relative path. The iomode parameter specifies the type of access required. The permissible values are ForReading(1 –the default), ForWriting (2), and ForAppending (8). If the create parameter is set to True when writing or appending to file that doesn’t exists, a new file will be created. The default for create is False. The format parameter specifies the format of the data to be read from or written to the file. Permissible values are TristateFalse (0-default) to open it as ASCII, TristateTrue (-1) to open it as Unicode, and TristateUseDefault (-2) to open it using the system default format.

Page 27: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

27

Working with DrivesGet a list of available drive letters using the DriveExists method.‘ In VBScriptResponse.Write "<H1>Using the DriveExists Method<HR></H1>“Set objFSO = Server.CreateObject(“Scripting.FileSystemObject”)For intCode=65 To 90 ‘ANSI Codes for ‘A’ to ‘Z’

strLetter = Chr(intCode)If objFSO.DriveExists(strLetter) Then

Response.Write “Found drive “ & strLetter & “ : <BR>”End If

Next

Page 28: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

28

The Drive ObjectProperty Description

AvailableSpace Returns the amount of space available to this user on the drive, taking into account quotas and/or other restrictions.

DriveLetter Returns the drive letter of the drive.

DriveType Returns the type of the drive. The values are Unknown (0), Removable (1), Fixed (2), Network (3), CDRom (4), and RamDisk (5). However, note that the current version of scrrun.dll does not include the pre-defined constant for Network, so you may have to use the decimal value 3 instead.

FileSystem Returns the type of file system for the drive. The values include “FAT”, “NTFS”, and “CDFS”

FreeSpace Returns the actual total amount of free space available on the drive.

IsReady Returns a Boolean value indicating if the drive is ready (True) or not (False).

Path Returns the path for the drive as a drive letter and colon, i.e. “C:”.

RootFolder Returns a Folder object representing the root folder of the drive.

SerialNumber Returns a decimal serial number used to uniquely identify a disk volume.

ShareName Returns the network share name for the drive if it is a networked drive.

TotalSize Returns the total size (in bytes) of the drive.

VolumeName Sets or returns the volume name of the drive if it is a local drive.

Page 29: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

29

The Drive Object1. <%2. 'In VBScript:3. Set objFSO = Server.CreateObject("Scripting.FileSystemObject")4. Set colDrives = objFSO.Drives 'Create a Drives collection5. Response.Write "<H1>Using the Drives Collection<HR></H1>"6. For Each objDrive in colDrives 'Iterate through the Drives collection7. Response.Write "DriveLetter : " & objDrive.DriveLetter & "<BR>"8. Response.Write "DriveType : " & objDrive.DriveType9. If objDrive.DriveType = 3 Then10. If objDrive.IsReady Then11. Response.Write "Remote drive with ShareName: <B>" & objDrive.ShareName & "</B><BR>"12. Else13. Response.Write "Remote drive - IsReady property returned False<BR>"14. End If15. Else16. Response.Write "FileSystem: <B>" & objDrive.FileSystem & "</B>, "17. Response.Write "SerialNumber: <B>" & objDrive.SerialNumber & "</B><BR> "18. Response.Write "Local drive with VolumeName: <B>" & objDrive.VolumeName & "</B>, "19. Response.Write "AvailableSpace: <B>" & objDrive.AvailableSpace & "</B> bytes, "20. Response.Write "FreeSpace: <B>" & objDrive.FreeSpace & "</B> bytes, "21. Response.Write "TotalSize: <B>" & objDrive.TotalSize & "</B> bytes<BR><BR>"22. End If23. Next24. %>

Page 30: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

30

The Drive ObjectIf you don’t have a disk in your A: drive or CD-ROM drive, you’ll get a ‘Disk Not Ready’ error

Page 31: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

31

The Folder ObjectThe RootFolder property of the Drive object returns a Folder object

Property Description

Attributes Returns the attributes of the folder. Can be a combination of any of the following values: Normal (0), ReadOnly (1), Hidden (2), System (4), Volume (name) (8), Directory (folder) (16), Archive (32), Alias (64) and Compressed (128). For Example, a hidden read-only file would have the value 3.

DateCreated Returns the date and time that the folder was created.

DateLastAccessed Returns the date and time that the folder was last access.

DateLastModified Returns the date and time that the folder was last modified.

Drive Returns the drive letter of the drive on which the folder resides.

Files Returns a Files collection containing File objects representing all the files within this folder.

IsRootFolder Returns a Boolean value indicating if the folder is the root folder of the current drive.

Name Sets or returns the name of the folder.

ParentFolder Returns the Folder object for the parent folder of this folder.

Page 32: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

32

The Folder ObjectProperty Description

Path Returns the absolute path of the folder, using long file names where appropriate.

ShortName Returns the DOS-style 8.3 version of the folder name.

ShortPath Returns the DOS-style 8.3 version of the absolute path of this folder.

Size Returns the size of all files and subfolders contained in the folder.

SubFolders Returns a Folders collection consisting of all folders contained in the folder, including hidden and system folders.

Type Returns a string that is a description of the folder type (such as “Recycle Bin”) if available.

Methods Description

Copy (destination, overwrite)

Copies this folder and all its contents to the folder specified in destination. If destination ends with a path separator character (‘\’) then destination is assumed to be a folder into which the copied folder will be placed. Otherwise, it is assumed to be a full path and name for a new folder to be created. An error will occur if the destination folder already exists, and the optional overwrite parameter is set to False. The default for overwrite is True.

Page 33: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

33

The Folder ObjectMethod Description

Delete (force) Deletes this folder and all its contents. If the optional force parameter is set to True the folder will be deleted, even if the Read-only attribute is set on it or any contained files. The default for force is False.

Move (destination)

Moves this folder and all its contents to the folder specified in destination. If destination ends with a path separator character (‘\’) then destination is assumed to be a folder in which to place the moved folder. Otherwise, it is assumed to be a full path and name for a new folder. An error will occur if the destination folder already exists.

CreateTextFile (filename, overwrite, unicode)

Creates a new text file within this folder with the specified filename, and returns a TextStream object that refers to it. If the optional overwrite parameter is set to True, any existing file with the same name will be overwritten. The default for overwrite is False. If the optional unicode parameter is set to True, the content of the file will be stored as unicode text. The default for unicode is False.

Page 34: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

34

The Folder Object1. <%2. 'In VBScript3. Response.Write "<H1>Using the Folders Collection<HR></H1>"

4. Set objFSO = Server.CreateObject("Scripting.FileSystemObject")5. Set objDriveC = objFSO.GetDrive("C:") 'get a reference to drive C6. Set objRoot = objDriveC.RootFolder 'get a reference to the root folder7. Set colFolders = objRoot.SubFolders ‘get a reference to the Folders

collection

8. For Each objFolder in colFolders9. Response.Write "Name: " & objFolder.Name & "&nbsp; &nbsp;"10. Response.Write "ShortName: " & objFolder.ShortName & "&nbsp;&nbsp;"11. Response.Write "Type: " & objFolder.Type & "<BR>"12. Response.Write "Path: " & objFolder.Path & "&nbsp;&nbsp;"13. Response.Write "ShortPath: " & objFolder.ShortPath & "<BR>"14. Response.Write "Created: " & objFolder.DateCreated & "&nbsp;&nbsp;"15. Response.Write "LastModified: " & objFolder.DateLastModified & "<P>"16. Next17. %>

Page 35: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

35

The Folder Object

Page 36: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

36

The Folder Object

Working with Special Folders

GetSpecialFolder method returns the Folder object for any of three ‘special folders’ on the machine:

WindowsFolder – the %Windows% directory, by default WinNT (or Windows on a non-NT/2000 machine)

SystemFolder – the %System% directory, by default WinNT\System32 (or Windows\System on a non-NT/2000 machine)

TemporaryFolder – the %Temp% directory, by default WinNT\Temp (or Windows\Temp on a non-NT/2000 machine)

Page 37: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

37

The Folder Object

1. <%2. 'In VBScript3. Response.Write "<H1>Using the SpecialFolders Method<HR></H1>"

4. Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

5. Set objFolder = objFSO.GetSpecialFolder(WindowsFolder)6. Response.Write "GetSpecialFolder(WindowsFolder) returned:<BR>"7. Response.Write "Path: " & objFolder.Path & "<BR>"8. Response.Write "Type: " & objFolder.Type & "<P>"

9. Set objFolder = objFSO.GetSpecialFolder(SystemFolder)10. Response.Write "GetSpecialFolder(SystemFolder) returned:<BR>"11. Response.Write "Path: " & objFolder.Path & "<BR>"12. Response.Write "Type: " & objFolder.Type & "<P>"

13. Set objFolder = objFSO.GetSpecialFolder(TemporaryFolder)14. Response.Write "GetSpecialFolder(TemporaryFolder) returned:<BR>"15. Response.Write "Path: " & objFolder.Path & "<BR>"16. Response.Write "Type: " & objFolder.Type & "<P>"17. %>

Page 38: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

38

The Folder Object

Page 39: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

39

The File Object Provides access to the properties of file, and implements methods

to manipulate that file. Each Folder object exposes a Files collection, containing File

objects that correspond to the files in that folder

Property Description

Attributes Returns the attributes of the file. Can be a combination of any of the following values: Normal (0), ReadOnly (1), Hidden (2), System (4), Volume (name) (8), Directory (folder) (16), Archive (32), Alias (64) and Compressed (128).

DateCreated Returns the date and time that the file was created.

DateLastAccessed Returns the date and time that the file was last access.

DateLastModified Returns the date and time that the file was last modified.

Drive Returns a drive object representing the drive on which the file resides.

Name Sets or returns the name of the file.

Page 40: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

40

The File ObjectProperty Description

ParentFolder Returns the Folder object for the parent folder of this file.

Path Returns the absolute path of the file, using long file names where appropriate.

ShortName Returns the DOS-style 8.3 version of the file name.

ShortPath Returns the DOS-style 8.3 version of the absolute path of this file.

Size Returns the size of all the file in bytes

Type Returns a string that is a description of the file type (such as “Text Document” for a .txt file) if available.

Method Description

Copy (destination, overwrite)

Copies this file to the folder specified in destination. If destination ends with a path separator character (‘\’) then destination is assumed to be a folder into which the copied file will be placed. Otherwise, it is assumed to be a full path and name for a new folder to be created. An error will occur if the destination file already exists, and the optional overwrite parameter is set to False. The default for overwrite is True.

Page 41: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

41

The File ObjectMethod Description

Delete (force) Deletes this file. If the optional force parameter is set to True the file will be deleted, even if the Read-only attribute is set. The default for force is False.

Move (destination) Moves this file to the folder specified in destination. If destination ends with a path separator character (‘\’) then destination is assumed to be a folder in which to place the moved file. Otherwise, it is assumed to be a full path and name for a new file. An error will occur if the destination file already exists.

CreateTextFile (filename, overwrite, unicode)

Creates a new text file within this folder with the specified filename, and returns a TextStream object that refers to it. If the optional overwrite parameter is set to True, any existing file with the same path and name will be overwritten. The default for overwrite is False. If the optional unicode parameter is set to True, the content of the file will be stored as unicode text. The default for unicode is False.

OpenAsTextStream (iomode, format)

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file. The iomode parameter specifies the type of access required. The permissible values are ForReading (1- the default), ForWriting (2), and ForAppending (8). The format parameter specifies the format of the data to be read from or written to the file. Permissible values are TristateFalse (0 - the default) to open it as ASCII, TristateTrue (-1) to open it as Unicode, and TristateUseDefault (-2) to open it using the system default format.

Page 42: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

42

The File Object1. <% 'In VBScript2. Response.Write "<H1>Using the Files Collection<HR></H1>"3. Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

4. Set objFSO = Server.CreateObject("Scripting.FileSystemObject")5. Set objDriveC = objFSO.GetDrive("C:") 'get a reference to drive C6. Set objRoot = objDriveC.RootFolder 'get a reference to the root folder7. Set objFolders = objRoot.SubFolders ' get a reference to the Folders

collection

8. 'get a reference to the first folder in the SubFolders collection9. For Each objFolder In objFolders10. Set objFolder1 = objFolders.Item((objFolder.Name))11. Exit For12. Next

13. For Each objFile in objFolder1.Files14. Response.Write "Name: " & objFile.Name & "&nbsp; &nbsp;"15. Response.Write "ShortName: " & objFile.ShortName & "&nbsp;&nbsp;"16. Response.Write "Size: " & objFile.Size & "<BR>"17. Response.Write "Type: " & objFile.Type & "<BR>"18. Response.Write "Path: " & objFile.Path & "&nbsp;&nbsp;"19. Response.Write "ShortPath: " & objFile.ShortPath & "<BR>"20. Response.Write "Created: " & objFile.DateCreated & "&nbsp;&nbsp;"21. Response.Write "LastModified: " & objFile.DateLastModified & "<P>"22. Next23. %>

Page 43: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

43

The File Object

Page 44: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

44

The Scripting.TextStream Object Methods for creating TextStream Object

CreateTextFile (filename, overwrite, unicode) OpenTextFile (filename, iomode, create, format) OpenAsTextStream (iomode, format)

Method FileSystemObject object

Folder object File object

CreateTextFile Yes Yes Yes

OpenTextFile Yes (No) (No)

OpenAsTextStream (No) (No) Yes

Page 45: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

45

The Scripting.TextStream Object Creating New Text Files

‘In VBScript

Set objFSO = Server.CreateObject(“Scripting.FileSystemObject”)

Set objTStream = objFSO.CreateTextFile(“C:\TextFiles\MyFile.txt”, True, False)

‘In JScript

var objFSO = Server.CreateObject(‘Scripting.FileSystemObject’);

var objTStream = objFSO.CreateTextFile(‘C:\TextFiles\MyFile.txt’, True, False);

Once the file has been created, we can use the objTStream reference to work with the file.

Page 46: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

46

The Scripting.TextStream Object Opening Existing Text Files

To open file for writing, and create a new file if the one specified doesn’t exists

‘In VBScriptSet objFSO = Server.CreateObject(“Scripting.FileSystemObject”)Set objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForReading)

‘In JScriptvar objFSO = Server.CreateObject(‘Scripting.FileSystemObject’);var objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’);

‘In VBScriptSet objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForWriting, True)

‘In JScriptvar objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’, ForWriting, true);

Page 47: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

47

The Scripting.TextStream Object Opening Existing Unicode File ready to append data to it, but

not create a new file if the one specified doesn’t already exists

‘In VBScriptSet objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForAppending, _

False, TristateTrue)

‘In JScriptvar objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’, ForAppending, _

false, true);

Page 48: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

48

The Scripting.TextStream Object Opening a File Object as a TextStream Object

To start with a new empty file

To read from the file

‘In VBScriptSet objTStream = objFileObject.OpenAsTextStream(ForAppending, False)

‘In JScriptvar objTStream = objFileObject.OpenTextFile(ForAppending, false);

‘In VBScriptSet objTStream = objFileObject.OpenAsTextStream(ForWriting)

‘In JScriptvar objTStream = objFileObject.OpenTextFile(ForWriting);

‘In VBScriptSet objTStream = objFileObject.OpenAsTextStream(ForReading)

‘In JScriptvar objTStream = objFileObject.OpenTextFile(ForReading);

Page 49: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

49

The Scripting.TextStream ObjectProperty Description

AtEndOfLine Returns True if the file pointer is at the end of a line in the file.

AtEndOfStream Returns True if the file pointer is at the end of the file.

Column Returns the column number of the current character in the file, starting from 1.

Line Returns the current line number in the file, starting from 1.

All the properties are read-only.

The AtEndOfLine and AtEndOfStream are only available for a file that is opened with iomode of ForReading. Referring to them otherwise causes an error to occur.

Page 50: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

50

The Scripting.TextStream ObjectMethod Description

Close ( ) Closes an open file.

Read (numchars) Reads numchars characters from the file.

ReadAll ( ) Reads the entire file as a single string.

ReadLine ( ) Reads a line (up to a carriage return and line feed) from the file as a string.

Skip (numchars) Skips and discards numchars characters when reading from the file.

SkipLine ( ) Skips and discards the next line when reading from the file.

Write (string) Writes string to the file.

WriteLine (string) Writes string (optional) and a new line character to the file.

WriteBlankLines (n) Writes n new line characters to the file.

Page 51: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

51

The Scripting.TextStream ObjectWriting to a Text File‘ In VBScriptobjTStream.WriteLine “At last I can create files with VBScript!”objTStream.WriteLineobjTStream.WriteLine “Here are three blank lines : “objTStream.WriteBlankLines 3objTStream.Write “… and this is “objTStream.WriteLine “the last line.”objTStream.Close

// In JScriptobjTStream.WriteLine (‘At last I can create files with JScript!’);objTStream.WriteLine ();objTStream.WriteLine (‘Here are three blank lines : ‘);objTStream.WriteBlankLines (3);objTStream.Write (‘… and this is ‘);objTStream.WriteLine (‘the last line.’);objTStream.Close();

Page 52: 2004 Tau Yenny, SI - Binus M0194 Web-based Programming Lanjut Session 4.

2004 Tau Yenny, SI - Binus

52

The Scripting.TextStream ObjectReading from a Text File‘ In VBScriptDo While Not objTStream.AtEndOfStream intLineNum = objTSTream.Line ‘get the line number strLineNum = Right(“000” & CStr(intLineNum), 4) ‘format it as a 4-character strLineText = objTStream.ReadLine Response.Write strLineNum & “ : “ & strLineText & “<BR>”LoopobjTStream.Close// In JScriptwhile (! objTStream.AtEndOfStream) { intLineNum = objTSTream.Line; ‘get the line number strLineNum = ‘000’ + intLineNum.toString(); ‘format and convert to a string strLineNum = substr(strLineNum, strLineNum.length – 4, 4); strLineText = objTStream.ReadLine(); Response.Write (strLineNum + ‘ : ‘ + strLineText & <BR>’);}objTStream.Close();