• No results found

B VBScript11

N/A
N/A
Protected

Academic year: 2021

Share "B VBScript11"

Copied!
63
0
0

Loading.... (view fulltext now)

Full text

(1)

VBScript

VBScript

Session 11

(2)

What we learn last session?

What we learn last session?

VBScript string manipulation.

VBScript string manipulation.

VBScript string math.

VBScript string math.

VBScript date manipulation.

VBScript date manipulation.

VBScript Formatting Strings.

VBScript Formatting Strings.

(3)

Subjects for session 11

Subjects for session 11

The OOP model.

The OOP model.

Objects.

Objects.

COM objects.

COM objects.

Set statement.

Set statement.

Nothing keyword

Nothing keyword

CreateObject function.

CreateObject function.

New keyword.

New keyword.

FileSystem object.

FileSystem object.

(4)

OOP Model

OOP Model

Abstractions

Abstractions

Encapsulation

Encapsulation

Polymorphism

Polymorphism

Inheritance

Inheritance

Reusabillity

Reusabillity

(5)

OOP Model

OOP Model

Abstractions

Abstractions

The ability for a program to

The ability for a program to ignore some aspects of the informationignore some aspects of the information it's manipulating, i.e. the abil

it's manipulating, i.e. the ability to focus on the essential.ity to focus on the essential. An abstract class cannot be

An abstract class cannot be instantiated.instantiated. An abstract class may

An abstract class may contain abstract methods and accessors.contain abstract methods and accessors. An abstract class can be partially

An abstract class can be partially implemented, or not at allimplemented, or not at all implemented.

implemented.

Abstract classes are useful

Abstract classes are useful when creating components becausewhen creating components because they allow you specify an invariant level

they allow you specify an invariant level of functionality in someof functionality in some methods, but leave the implementation of other methods until a methods, but leave the implementation of other methods until a specific implementation of that class is needed.

(6)

OOP Model

OOP Model

Encapsulation

Encapsulation

The ability for the program to hide

The ability for the program to hide

information about the implementation of a

information about the implementation of a

module from its users, i.e. the ability to

module from its users, i.e. the ability to

prevent users from breaking the invariants

prevent users from breaking the invariants

of the program.

of the program.

The term encapsulation refer to

The term encapsulation refer to

Information hiding in software

Information hiding in software..

(7)

OOP Model

OOP Model

Polymorphism

Polymorphism

Polymorphism is the ability for classes to

Polymorphism is the ability for classes to

provide different implementations of 

provide different implementations of 

methods that are called by the same

methods that are called by the same

name.

name.

Polymorphism allows a method of a class

Polymorphism allows a method of a class

to be called without regard to what

to be called without regard to what

specific implementation it provides.

specific implementation it provides.

(8)

OOP Model

OOP Model

Polymorphism

Polymorphism

You might have a class named Road which calls the Drive

You might have a class named Road which calls the Drive

method of an additional class.

method of an additional class.

This Car class may be SportsCar, or SmallCar, but both

This Car class may be SportsCar, or SmallCar, but both

would provide the Drive method.

would provide the Drive method.

Though the implementation of the Drive method would

Though the implementation of the Drive method would

be different between the classes, the Road class would

be different between the classes, the Road class would

still be able to call it, and it would provide results that

still be able to call it, and it would provide results that

would be usable and interpretable by the Road class.

would be usable and interpretable by the Road class.

(9)

OOP Model

OOP Model

Inheritance

Inheritance

Defining classes as extensions

Defining classes as extensions of existing

of existing

classes.

classes.

In computer science, the term

In computer science, the term

inheritance

inheritance may be applied to a variety of 

may be applied to a variety of 

situations in which certain characteristics

situations in which certain characteristics

are passed on from one context to

are passed on from one context to

another.

another.

The term originates with the biological

The term originates with the biological

concept of a parent passing on certain

concept of a parent passing on certain

traits to a child

(10)

Dimensions Dimensions Flanks Flanks Rectangle Rectangle Shape Shape Triangle Triangle Circle Circle Area Area Perimeter Perimeter Radious Radious *pi

*pi anglesangles HeightHeightWidthWidth

3D

3D depthdepth

Where is the Where is the right place for right place for this action?

(11)

OOP Model

OOP Model

Reusabillity

Reusabillity

reusability

reusability is the likelihood a is the likelihood a segment of structured code can besegment of structured code can be used again to add new functionalities with slight or

used again to add new functionalities with slight or nono modification.

modification.

Reusable code reduces implementation time, increases the Reusable code reduces implementation time, increases the likelihood that prior testing and use has eli

likelihood that prior testing and use has eliminated bugs andminated bugs and localizes code modifications when a change in i

localizes code modifications when a change in implementation ismplementation is required.

required.

Subroutines or functions are the simplest form of reuse. Subroutines or functions are the simplest form of reuse. A chunk of code is regularly organized using module or A chunk of code is regularly organized using module or namespace.

namespace.

Proponents claim that objects and software components offer a Proponents claim that objects and software components offer a more advanced form of reusability.

(12)

Object Model

Object Model

Object.

Object.

Collection.

Collection.

Container object.

Container object.

Method.

Method.

Event.

Event.

Property.

Property.

Attribute.

Attribute.

(13)

Object Model

Object Model

Objects

Objects

In computer science , an

In computer science , an objectobject is a data structure (incorporatingis a data structure (incorporating data and methods) whose instance is unique and separate from data and methods) whose instance is unique and separate from other objects, although it can "communicate" with

other objects, although it can "communicate" with other objects.other objects. In some occasions, some object can be conceived of as a

In some occasions, some object can be conceived of as a subsub

program which can communicate with others by receiving or giving program which can communicate with others by receiving or giving instructions based on its, or the other's, data or methods. Data can instructions based on its, or the other's, data or methods. Data can consist of numbers, literal strings ,

consist of numbers, literal strings , variables, and references.variables, and references. the

the object lifetimeobject lifetime (or(or life cyclelife cycle) ) of of an an object object in in OOP OOP is is thethe time between an object's creation (also known as

time between an object's creation (also known as instantiationinstantiation oror construction

construction) till the object is no longer used, and is) till the object is no longer used, and is destructeddestructed or

(14)

Object Model

Object Model

Collection

Collection

An object that contains zero or more objects

An object that contains zero or more objects

(member).

(member).

Collections normally contain objects of the same

Collections normally contain objects of the same

class.

class.

Also referred to as a collection object or an

Also referred to as a collection object or an

object collection.

object collection.

Collection has normally two single read-only

Collection has normally two single read-only

properties, Item and Count

properties, Item and Count

you usually use the Item property or method

you usually use the Item property or method

and pass the name or index number of the

and pass the name or index number of the

member.

(15)

Object Model

Object Model

Container Object

Container Object

An object that contains other objects

An object that contains other objects

from different classes.

from different classes.

Collection can have properties and/or

Collection can have properties and/or

methods.

(16)

Object Model

Object Model

Methods

Methods

Method

Method is a function or subroutine

is a function or subroutine that is associated

that is associated

with a class in OPP.

with a class in OPP.

Like a function in procedural languages, it may contain

Like a function in procedural languages, it may contain

a set of program statements that perform an action,

a set of program statements that perform an action,

and (in most computer languages ) can take a set of 

and (in most computer languages ) can take a set of 

input arguments and can return some kind of result.

input arguments and can return some kind of result.

The purpose of a method is to provide a mechanism

The purpose of a method is to provide a mechanism

for changing or accessing information stored in an

for changing or accessing information stored in an

object

(17)

Object Model

Object Model

Methods

Methods

A method should preserve invariants

A method should preserve invariants associated with

associated with

the class, and should be able to assume that every

the class, and should be able to assume that every

invariant is valid on entry to the method

invariant is valid on entry to the method

A method can have

A method can have parameters.

parameters.

method may produce output, which are constrained by

method may produce output, which are constrained by

postconditions

postconditions of

of the

the method.

method.

If the a

If the arguments

rguments to a

to a method do

method do not satisfy

not satisfy their

their

preconditions, a method can raise an

(18)

Object Model

Object Model

Event

Event

In the context of programming, the occurrence

In the context of programming, the occurrence

of some particular action or the occurrence of a

of some particular action or the occurrence of a

change of state that can be handled by

change of state that can be handled by an

an

application or COM object that is invoked in

application or COM object that is invoked in

response to the triggering of an event. .

response to the triggering of an event. .

For example, the arrival of a message to the

For example, the arrival of a message to the

SMTP service is an event that can be handled by

SMTP service is an event that can be handled by

any number of Applications or objects.

(19)

Object Model

Object Model

Property

Property

Properties are like smart fields.

Properties are like smart fields.

A property is an information that is associated with an

A property is an information that is associated with an

object.

object.

Each property has a value.

Each property has a value. value

value is a keyword in the

is a keyword in the

syntax for the property definition.

syntax for the property definition.

The variable

The variable value

value is assigned to the property in the

is assigned to the property in the

calling code.

calling code.

The type of 

The type of value

value must be the same as the declared

must be the same as the declared

type of the property to which it is assigned.

type of the property to which it is assigned.

properties fall into two categories: run-time properties

properties fall into two categories: run-time properties

and persistent properties.

(20)

Object Model

Object Model

Attribute

Attribute

Each property has

Each property has attributes

attributes..

Attributes provide information about the property.

Attributes provide information about the property.

For example, the

For example, the First Name

First Name property has the following

property has the following

attributes: Name, Display Name, Description, and Type.

attributes: Name, Display Name, Description, and Type.

Attributes include information such as the data type of 

Attributes include information such as the data type of 

the profile property (for example, number, text, decimal,

the profile property (for example, number, text, decimal,

or site term), and whether the property is single-valued

or site term), and whether the property is single-valued

(for example, only one

(for example, only one First Name

First Name entry is allowed per

entry is allowed per

user) or multi-valued.

(21)

COM

COM

Component Object Model

Component Object Model

An architecture for defining

An architecture for defining i

i

nterfaces (a set of abstract

nterfaces (a set of abstract

methods and properties that encompass some common

methods and properties that encompass some common

purpose) and interaction among objects implemented by

purpose) and interaction among objects implemented by

widely varying software applications.

widely varying software applications.

All COM interfaces are extend and derived from the

All COM interfaces are extend and derived from the

IUnknown

IUnknown, interface which includes the methods

, interface which includes the methods

QueryInterface

QueryInterface,, AddRef 

AddRef , and

, and Release

Release..

COM interfaces additionally define a binary signature that

COM interfaces additionally define a binary signature that

acts as a contract between the interface designer and client

acts as a contract between the interface designer and client

applications written to use the interface COM classes

applications written to use the interface COM classes

provide concrete implementations of COM interfaces.

provide concrete implementations of COM interfaces.

(22)

COM

COM

IUnknown

IUnknown

The fundamental COM interface, which must be

The fundamental COM interface, which must be

extended by every valid COM interface.

extended by every valid COM interface.

IUnknown

IUnknown exposes three methods:

exposes three methods:

QueryInterface

QueryInterface, used to find out if the object

, used to find out if the object

supports a certain interface and return the interface if 

supports a certain interface and return the interface if 

it does.

it does.

AddRef 

AddRef , to increment the interface reference count.

, to increment the interface reference count.

Release

(23)

COM

COM

COM Class

COM Class

An implementation of one or more COM

An implementation of one or more COM

interfaces.

interfaces.

COM objects are instances of COM

COM objects are instances of COM

classes.

(24)

COM

COM

COM Interface

COM Interface

A pointer to a vtable pointer where the

A pointer to a vtable pointer where the

first three methods in that table are

first three methods in that table are

QueryInterface

(25)

COM Objects

COM Objects

COM Extensions Technologies

COM Extensions Technologies

COM+(Component Services )

COM+(Component Services )

ActiveX, OLE

ActiveX, OLE

SOM, DSOM

SOM, DSOM

 – –

IBM

IBM

’’

s System object model

s System object model

DCOM (Distributed COM)

DCOM (Distributed COM)

Distributed COM

Distributed COM

CORBA

CORBA

 – –

Common Object Request Broker

Common Object Request Broker

Architecture

Architecture

RMI, JavaBeans

RMI, JavaBeans

 – –

SUN Microsystems

SUN Microsystems

technologies.

technologies.

RPC

(26)

COM objects

COM objects

Where they are?

Where they are?

In the registry under HKEY_CLASSES_ROOT you

In the registry under HKEY_CLASSES_ROOT you

will se all the classes registered in your system.

will se all the classes registered in your system.

You can find there the Scripting.FileSystemObject

You can find there the Scripting.FileSystemObject

Key, Excel.Applicatio

Key, Excel.Application key

n key etc

etc

All those classes can be used in VBScript.

All those classes can be used in VBScript.

Each class has a description, a CLSID entry and

Each class has a description, a CLSID entry and

some a version entry.

some a version entry.

In CLSID you will find the class identifier.

In CLSID you will find the class identifier.

If you move to HKEY_CLASSES_ROOT\CLSID you

If you move to HKEY_CLASSES_ROOT\CLSID you

will see wich dll’s using this class.

will see wich dll’s using this class.

For more information search for

For more information search for <registration>

<registration>

Element

(27)

Set statement

Set statement

Assigns an object reference to a

Assigns an object reference to a variable or property, or associates a procedurevariable or property, or associates a procedure reference with an event.

reference with an event. To be valid,

To be valid, object object must be an object must be an object type consistent with the object beingtype consistent with the object being assigned to it.

assigned to it. The

The DimDim,, PrivatePrivate,, PublicPublic, or, or ReDimReDim statements only declare a variable thatstatements only declare a variable that refers to an object.

refers to an object.

No actual object is referred to

No actual object is referred to until you use theuntil you use the SetSet statement to assign astatement to assign a specific object.

specific object.

Generally, when you use

Generally, when you use SetSet to assign an object reference to to assign an object reference to a variable, no copya variable, no copy of the object is

of the object is created for that variable.created for that variable.

Instead, a reference to the object is created. Instead, a reference to the object is created. More than one object variable can refer to

More than one object variable can refer to the same object.the same object. Because these variables are references to (rather than copies

Because these variables are references to (rather than copies of) the object, anyof) the object, any change in the object is reflected in

(28)

Nothing Keyword

Nothing Keyword

The

The NothingNothing keyword in VBScript is used to disassociate an objectkeyword in VBScript is used to disassociate an object variable from any actual object.

variable from any actual object. Use the

Use the SetSet statement to assignstatement to assign NothingNothing to an object variable. Forto an object variable. For example:

example: Set

Set MyObject = NothingMyObject = Nothing

Several object variables can refer to the same

Several object variables can refer to the same actual object.actual object. When

When NothingNothing is assigned to an object variable, that variable is assigned to an object variable, that variable nono longer refers to any actual object.

longer refers to any actual object.

When several object variables refer to the same object, memory and When several object variables refer to the same object, memory and system resources associated with the object to which the variables system resources associated with the object to which the variables refer are released only after all

refer are released only after all of them have been set toof them have been set to NothingNothing,, either explicitly using

either explicitly using SetSet, or implicitly after the last object variable, or implicitly after the last object variable set to

(29)

CreateObject Function

CreateObject Function

CreateObject

CreateObject((servername.typename [servername.typename [,, location]location]))

Creates and returns a reference to an Automation object. Creates and returns a reference to an Automation object.

servername

servername - Required. The name of the appli- Required. The name of the application providingcation providing the object.

the object. typename

typename - Required. The type or - Required. The type or class of the object to create.class of the object to create. location

location - Optional. The name of the network server w- Optional. The name of the network server where thehere the object is to be created.

object is to be created.

Automation servers provide at least one type of object. Automation servers provide at least one type of object. For example, a word-processing application may provide For example, a word-processing application may provide anan application object, a document object, and a toolbar object. application object, a document object, and a toolbar object.

(30)

CreateObject Function

CreateObject Function

For example, a word-processing application

For example, a word-processing application

may provide an application object, a

may provide an application object, a

document object, and a toolbar object.

document object, and a toolbar object.

To create an Automation object, assign the

To create an Automation object, assign the

object returned by

object returned by CreateObject

CreateObject

to an

to an

object variable:

object variable:

Dim

Dim ExcelSheetExcelSheet Set

(31)

CreateObject Function

CreateObject Function

Once an object is created, refer to it in code using the object variable you Once an object is created, refer to it in code using the object variable you defined.

defined.

you can access properties and methods of the new object using the object you can access properties and methods of the new object using the object variable.

variable.

Creating an object on a remote server can only

Creating an object on a remote server can only be accomplished whenbe accomplished when Internet security is turned off.

Internet security is turned off.

You can create an object on a remote networked computer by passing You can create an object on a remote networked computer by passing the name of the computer to the

the name of the computer to the servernameservername argument of argument of  CreateObject

CreateObject..

That name is the same as the

That name is the same as the machine name portion of a share name.machine name portion of a share name. For a network share

For a network share named "\\myserver\public", thenamed "\\myserver\public", the servernameservername isis "myserver". In addition, you can specify

"myserver". In addition, you can specify servernameservername using DNS formatusing DNS format or an IP address.

(32)

CreateObject Function

CreateObject Function

Summary

Summary

Creating an object

Creating an object

Set

Set myDoc =myDoc = CreateObjectCreateObject ((““Word.DocumentWord.Document””))

Using The object

Using The object

MyDoc.content =

MyDoc.content = ““abcabc””

MyDoc.SaveAs

MyDoc.SaveAs ““Doc1.docDoc1.doc””

MyDoc.Close MyDoc.Close

Free the object

Free the object

Set

Set Mydoc =Mydoc = NothingNothing

Type

COM

Type

COM

Library Class

Library Class

(33)

FileSystemO

FileSystemO

bject

bject

Object

Object

Basics

Basics

When writing scripts it's often important to add,

When writing scripts it's often important to add,

move, change, create, or delete folders and

move, change, create, or delete folders and

files.

files.

It may also be necessary to get information

It may also be necessary to get information

about and manipulate drives attached to

about and manipulate drives attached to the

the

machine.

machine.

Scripting allows you to process drives, folders,

Scripting allows you to process drives, folders,

and files using the

and files using the FileSystemObject

FileSystemObject (FSO)

(FSO)

object model.

(34)

New Keyword

New Keyword

Keyword used to create a new instance of a class.

Keyword used to create a new instance of a class.

If 

If objectvar 

objectvar  contained a reference to an object, that

contained a reference to an object, that

reference is released when the new one is assigned.

reference is released when the new one is assigned.

The

The New

New

keyword can only be used to create an instance

keyword can only be used to create an instance

of a class.

of a class.

Using the

Using the New

New

keyword allows you to concurrently

keyword allows you to concurrently

create an instance of a class and assign it to an object

create an instance of a class and assign it to an object

reference variable.

reference variable.

The variable to which the instance of the class is being

The variable to which the instance of the class is being

assigned must already have been declared with the

assigned must already have been declared with the Dim

Dim

(or equivalent) statement.

(or equivalent) statement.

(35)

FileSystemObejc

FileSystemObejc

t

t

Object

Object

Model

Model

The

The FileSystemObjectFileSystemObject (FSO) object model allows you to use the(FSO) object model allows you to use the familiar

familiar object.method object.method syntax with a rich set of syntax with a rich set of properties, methods,properties, methods, and events to process folders and files.

and events to process folders and files.

The FSO object model gives to the QTP the ability to create, alter, The FSO object model gives to the QTP the ability to create, alter, move, and delete folders, or to detect if particular folders exi

move, and delete folders, or to detect if particular folders exist, and if st, and if  so, where. You can also find out information about folders, such as so, where. You can also find out information about folders, such as their names, the date they were created or l

their names, the date they were created or last modified, and so forth.ast modified, and so forth. The FSO object model also makes it

The FSO object model also makes it easy to process files. Wheneasy to process files. When processing files, the primary goal is to store data

processing files, the primary goal is to store data in a space- andin a space- and resource-efficient, easy-to-access format.

resource-efficient, easy-to-access format. You need to be able to create files,

You need to be able to create files, insert and change the data, andinsert and change the data, and output (read) the data.

(36)

FileSystemObejc

FileSystemObejc

t

t

Object

Object

Model

Model

The FSO object model, which is contained in the

The FSO object model, which is contained in the

Scripting type library (Scrrun.dll), supports text

Scripting type library (Scrrun.dll), supports text

file creation and manipulation through the

file creation and manipulation through the

TextStream

TextStream

object.

object.

Although it does not yet support the creation or

Although it does not yet support the creation or

manipulatio

manipulation of

n of binary files, future support of 

binary files, future support of 

binary files is planned.

(37)

Dani Vainstein 37

FileSystemObject Objects

Main

Main object.

Contains methods and properties that allow you to create, delete, gain information about, and generally manipulate drives, folders, and files.

Many of the methods associated with this object duplicate those in other FSO objects; they are provided for

(38)

Dani Vainstein 38

FileSystemObject Objects

Drive Object

Contains methods and properties that allow you to gather information about a drive attached to the system, such as its share name and how much room is available.

Note that a "drive" isn't necessarily a hard disk, but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the system; it can be also be logically connected through a network.

(39)

FileSystemO

FileSystemO

bject

bject

Objects

Objects

Drive Collection

Drive Collection

Provides a list of the drives attached to

Provides a list of the drives attached to

the system, either physically or logically.

the system, either physically or logically.

The

The Drives

Drives collection includes all drives,

collection includes all drives,

regardless of type.

regardless of type.

Removable-media drives need not have

Removable-media drives need not have

media inserted for them to appear in this

media inserted for them to appear in this

collection.

(40)

Dani Vainstein 40

FileSystemObject Objects

File Object

Contains methods and properties that

allow you to create, delete, or move a

file.

Also allows you to query the system for a

file name, path, and various other

(41)

Dani Vainstein

Dani Vainstein 4141

FileSystemO

FileSystemO

bject

bject

Objects

Objects

Files Collection

Files Collection

Provides a list of all files contained wi

Provides a list of all files contained within

thin

a folder.

(42)

Dani Vainstein

Dani Vainstein 4242

FileSystemO

FileSystemO

bject

bject

Objects

Objects

Folder Object

Folder Object

Contains methods and properties that

Contains methods and properties that

allow you to create, delete, or

allow you to create, delete, or move

move

folders.

folders.

Also allows you to query the system for

Also allows you to query the system for

folder names, paths, and various other

folder names, paths, and various other

properties.

(43)

Dani Vainstein

Dani Vainstein 4343

FileSystemO

FileSystemO

bject

bject

Objects

Objects

Folders Collection

Folders Collection

Provides a list of all the folders

Provides a list of all the folders within a

within a

Folder

(44)

Dani Vainstein

Dani Vainstein 4444

FileSystemO

FileSystemO

bject

bject

Objects

Objects

TextStream Object

TextStream Object

Allows you to read and write text

(45)

Dani Vainstein Dani Vainstein 4545

Programming the

Programming the

FileSystemObject

FileSystemObject

Use the

Use the CreateObject

CreateObject method to create

method to create

a

a FileSystemObject

FileSystemObject object.

object.

Use the appropriate method on the newly

Use the appropriate method on the newly

created object.

created object.

Access the object's properties.

Access the object's properties.

Set

Set objFSO =objFSO = CreateObjectCreateObject("Scripting.FileSystemObject")("Scripting.FileSystemObject")

Scripting

Scripting is the name of the type library

is the name of the type library

and

and FileSystemObject

FileSystemObject is the name of 

is the name of 

the object that you want to create.

(46)

Dani Vainstein

Dani Vainstein 4646

Accessing Existing Drives, Files,

Accessing Existing Drives, Files,

and Folders

and Folders

To gain access to an existing drive, fil

To gain access to an existing drive, file, or folder, use the appropriatee, or folder, use the appropriate "get" method of the

"get" method of the FileSystemObjectFileSystemObject object:object:

GetDrive GetDrive GetFolder GetFolder GetFile GetFile

Do not use the "get" methods for newly created objects, since the Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object.

"create" functions already return a handle to that object. For example, if you create a new

For example, if you create a new folder using thefolder using the CreateFolderCreateFolder method, don't use the

method, don't use the GetFolderGetFolder method to access its method to access its properties,properties, such as

such as NameName,, PathPath,, SizeSize, and so forth., and so forth. Just set a variable to the

Just set a variable to the CreateFolderCreateFolder function to gain a handle tofunction to gain a handle to the newly created folder, then access its properties, methods, and the newly created folder, then access its properties, methods, and events.

(47)

Dani Vainstein

Dani Vainstein 4747

Accessing the Object's

Accessing the Object's

Properties

Properties

Once you have a handle to an object, you can

Once you have a handle to an object, you can

access its properties.

access its properties.

For example, to get the name of a particular

For example, to get the name of a particular

folder, first create an instance of the object,

folder, first create an instance of the object,

then get a handle to it

then get a handle to it with the appropriate

with the appropriate

method (in this case, the

method (in this case, the GetFolder

GetFolder method,

method,

since the folder already exists).

(48)

Dani Vainstein 48

Working with Drives and

Folders

With the FileSystemObject (FSO)

object model, you can work with drives

and folders programmatically just as you

can in the Windows Explorer

interactively.

You can copy and move folders, get

information about drives and folders, and

so forth.

(49)

Dani Vainstein

Dani Vainstein 4949

Getting Information About

Getting Information About

Drives

Drives

The

The Drive

Drive object allows you to gain

object allows you to gain

information about the various drives

information about the various drives

attached to a system, either physically or

attached to a system, either physically or

over a network.

(50)

Dani Vainstein 50

Getting Information About

Drives

The total size of the drive in bytes (TotalSize property).

How much space is available on the drive in bytes (AvailableSpace or FreeSpace properties).

What letter is assigned to the drive (DriveLetter property).

What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk (DriveType property).

The drive's serial number (SerialNumber property).

The type of file system the drive uses, such as FAT, FAT32, NTFS, and so forth (FileSystem property).

Whether a drive is available for use (IsReady property)

The name of the share and/or volume (ShareName and VolumeName properties)

(51)

Dani Vainstein

Dani Vainstein 5151

Working With Folders

Working With Folders

Create a folder - FileSystemObject.CreateFolder Create a folder - FileSystemObject.CreateFolder

Delete a folder - Folder.Delete or FileSystemObject.DeleteFolder Delete a folder - Folder.Delete or FileSystemObject.DeleteFolder Move a folder - Folder.Move or FileSystemObject.MoveFolder Move a folder - Folder.Move or FileSystemObject.MoveFolder Copy a folder - Folder.Copy or FileSystemObject.CopyFolder Copy a folder - Folder.Copy or FileSystemObject.CopyFolder Retrieve the name of a folder - Folder.Name

Retrieve the name of a folder - Folder.Name

Find out if a folder exists on a drive - FileSystemObject.FolderExists Find out if a folder exists on a drive - FileSystemObject.FolderExists Get an instance of an existing

Get an instance of an existing FolderFolder object - FileSystemObject.GetFolderobject - FileSystemObject.GetFolder Find out the name of a folder's parent folder

Find out the name of a folder's parent folder -FileSystemObject.GetParentFolderName

FileSystemObject.GetParentFolderName

Find out the path of system folders - FileSystemObject.GetSpecialFolder Find out the path of system folders - FileSystemObject.GetSpecialFolder

(52)

Dani Vainstein

Dani Vainstein 5252

Working With Files

Working With Files

There are two major categories of 

There are two major categories of 

file manipulation

file manipulation

Creating, adding, or removing data,

Creating, adding, or removing data,

and reading files.

and reading files.

Moving, copying, and deleting files.

Moving, copying, and deleting files.

(53)

Dani Vainstein

Dani Vainstein 5353

Creating Files

Creating Files

There are three ways to create an empty

There are three ways to create an empty

text file.

text file.

The first way is to use the

The first way is to use the

CreateTextFile

CreateTextFile method.

method.

The second way to create a text file is to

The second way to create a text file is to

use the

use the OpenTextFile

OpenTextFile method of the

method of the

FileSystemObject

FileSystemObject object with the

object with the

ForWriting

ForWriting flag set.

flag set.

A third way to create a text file is to use

A third way to create a text file is to use

the

the OpenAsTextStream

OpenAsTextStream method with

method with

the

(54)

Dani Vainstein 54

Adding Data to the File

Once the text file is created, add data to the file using the following three steps:

Open the text file. Write the data. Close the file.

To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.

To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object according to your task.

To close an open file, use the Close method of the TextStream object.

Note The newline character contains a character or characters to advance the cursor to the beginning of the next line. Be aware that the end of some strings may already have such nonprinting

(55)

Dani Vainstein 55

Reading Files

To read data from a text file, use the

Read, ReadLine, or ReadAll method of 

the TextStream object.

If you use the Read or ReadLine method

and want to skip to a particular portion of 

data, use the Skip or SkipLine method.

The resulting text of the read methods is

stored in a string which can be displayed

in a control, parsed by string functions

(such as Left, Right, and Mid),

(56)

Dani Vainstein 56

Moving, Copying, and Deleting

Files

The FSO object model has two

methods each for moving, copying,

and deleting files

Move a file - File.Move or

FileSystemObject.MoveFile

Copy a file - File.Copy or

FileSystemObject.CopyFile

Delete a file - File.Delete or

FileSystemObject.DeleteFile

(57)

Dani Vainstein 57

Lab 11.1

Tip

Const DRV_UNKNOWN = 0

Const DRV_REMOVABLE = 1

Const DRV_FIXED = 2

Const DRV_NETWORK = 3

Const DRV_CDROM = 4

Const DRV_RAMDISK = 5

(58)

Dani Vainstein

Dani Vainstein 5858

Lab 11.2

Lab 11.2

Declare the follow constants : Declare the follow constants :

Constants returned by Drive.DriveType Constants returned by Drive.DriveType

Const

Const conDriveTypconDriveTypeRemovable = eRemovable = 11 Const

Const conDriveTypconDriveTypeFixed = eFixed = 22 Const

Const conDriveTypconDriveTypeNetwork = eNetwork = 33 Const

Const conDriveTypeCDROM = 4conDriveTypeCDROM = 4 Const

Const conDriveTypeRAMDisk = 5conDriveTypeRAMDisk = 5

Constants returned by File.Attributes Constants returned by File.Attributes

Const

Const conFileAttrNormal = 0conFileAttrNormal = 0 Const

Const conFileAttrReadOnly = 1conFileAttrReadOnly = 1 Const

Const conFileAtconFileAttrHidden = trHidden = 22 Const

Const conFileAttrSystem = 4conFileAttrSystem = 4 Const

Const conFileAttrVolume = 8conFileAttrVolume = 8 Const

Const conFileAtconFileAttrDirectory = trDirectory = 1616 Const

Const conFileAttrArchive = 32conFileAttrArchive = 32 Const

Const conFileAttrAlias = 64conFileAttrAlias = 64 Const

Const conFileAtconFileAttrCompressed = trCompressed = 128128

Constants for opening files Constants for opening files

Const

Const conOpenFilconOpenFileForReading = eForReading = 11 Const

Const conOpenFilconOpenFileForWriting = eForWriting = 22 Const

(59)

Dani Vainstein

Dani Vainstein 5959

Lab 11.2

Lab 11.2

Write the following functions. Write the following functions. ShowDriveType

ShowDriveType(objDrive) - Generates a string describing the(objDrive) - Generates a string describing the drive type of a given Drive object.

drive type of a given Drive object. ShowFileAttr

ShowFileAttr(objFile) - Generates a string describing (objFile) - Generates a string describing thethe attributes of a file or folder.

attributes of a file or folder. GenerateDriveInformation

GenerateDriveInformation(objFSO) – reports about the Drive(objFSO) – reports about the Drive Letter,Path, Type, IsReady, ShareName, VolumeName, TotalSize, Letter,Path, Type, IsReady, ShareName, VolumeName, TotalSize, FreeSpace, AvailableSpace, and SerialNumber.

FreeSpace, AvailableSpace, and SerialNumber. GenerateFileInformation

GenerateFileInformation(objFile) – File Name, Type, File(objFile) – File Name, Type, File Attributes, Date Created, Last Accessed, Last Modified and

Attributes, Date Created, Last Accessed, Last Modified and SizeSize GenerateFolderInformation

GenerateFolderInformation(objFolder) – Folder Name, Folder(objFolder) – Folder Name, Folder Attributes, Date Created, Last Accessed, Last Modified and

(60)

Dani Vainstein 60

Lab 11.1

Create a Folder in the D:\ drive, if not exist in

C:\ Drive.

The name of the folder is VBSInfo.

Create a file in the folder, TestInfo.txt

The file will contain the report of the program.

The data will displayed like a table (rows and

columns with headers) use the vbTab for

separate the data.

For getting information about the directories

and files, please DON

T do it an all drives, select

(61)

Lab 11.1

Lab 11.1

Create a Folder in the D:\ drive, if not exist in

Create a Folder in the D:\ drive, if not exist in

C:\ Drive.

C:\ Drive.

The name of the folder is VBSInfo.

The name of the folder is VBSInfo.

Create a file in

Create a file in the folder, TestInfo.txt

the folder, TestInfo.txt

The file will contain the report of the program.

The file will contain the report of the program.

The data will displayed like a

The data will displayed like a table (rows and

table (rows and

columns with headers) use the vbTab for

columns with headers) use the vbTab for

separate the data.

separate the data.

For getting information about the directories

For getting information about the directories

and files, please DON

and files, please DON

’’

T do it an all drives, select

T do it an all drives, select

only the drive were you created your file.

only the drive were you created your file.

(62)

What’s Next

What’s Next

What means error handling.

What means error handling.

When to use On E

When to use On Error statements.

rror statements.

Using the error object.

Using the error object.

Raising our own errors.

Raising our own errors.

The next session is for advanced users. The next session is for advanced users.

(63)

Make sure to visit us

Tutorials

Articles

Proikects

And much more

www.AdvancedQTP.com

References

Related documents

rights, the definition of an issuer under federal law has been explicitly limited to owners of fractional undivided interests in oil, gas, or other mineral rights who

V nadaljevanju bomo skonstruirali naˇso izvrˇsljivo kodo (katero bomo upo- rabili tudi v poglavju 7), pogledali kako lahko zakrijemo sledi in predstavili, v kakˇsnih oblikah

the Create Mail dialog is launched, this signature is automatically selected. ※Please choose in the order of 1) template and 2) signature. If the signature is chosen first instead,

In conclusion, the IBD-based method and heterozygosity used to estimate genetic diversity of ungenotyped regions of the genome (i.e. between markers) give similar results for

Division of Air Quality State Local Programs Federal Public Associations Central Office Regional Offices -Complaints -Stakeholders -Public Hearings • Business / Industry •

In addition, the first-year turnover rate (the number of employees who leave before being at the institution even just one year) is even higher: 28.3% on average iii.. This means

(iii) General endorsement which requires a student to demonstrate proficient performance in a majority of the areas of the common core of knowledge and skills, which include

series is written by teachers and teacher trainers, people who know the reality of the classroom and the support teachers need to get the most out of their students.. Our aim is