| << 14.3.2- The Record Object | Chapter14 | 14.4.0- Summary >> |
The Stream Object
We can use the Record object in a file system or mail system to move and copy the files or mail messages and their containing files, but that still doesn't tell us how to access the data that's contained within them. And let's face it, that's what we really want to do – there's only so much satisfaction we can get from moving files around! To meet this demand, we use the ADO Stream object. The Stream object is used to represent the most basic denomination of data – binary data or just plain text. In this chapter, we'll only look at the latter case, as the former is quite a bit more complex.
In order to create an instance of the ADO Stream object, we use the Server object's CreateObject method. The ProgID for the ADO Stream object is ADODB.Stream:
Set objStream = Server.CreateObject("ADODB.Stream")
The Open Method
The Stream object, like the Record and Recordset objects, has its own Open method. Similarly, we use its Open method to open the object on a data source and hence access the stream of data contained within:
objStream.Open "http://chrisu/BegASP/ReadMe.txt", adModeRead, adOpenStreamFromURL
This example opens the Stream object on the stream of text contained in the file ReadMe.txt, which is contained in a virtual directory of my web server machine. It specifies values for three of the parameters:
- Source: this the URL of the file whose content we want to access
- ModeofAccess: the second is the mode of access (whether we're allowing read or write access). The example above specifies the value adModeRead, which allows read-only access to the contents of the file. A value of adModeReadWrite would allow read and write access to the source file
- OpenOptions: the third parameter specifies from where we're getting the data. The value adOpenStreamFromURL specifies that we're opening the stream using a URL as the source, while the value adOpenStreamFromRecord should be used when opening a stream using an existing Record object
We're not going to cover the full list of available parameter values here, because it's beyond the scope of this book. You can find more details in our title Professional Active Server Pages 3.0 (Wrox, ISBN 1-861002-61-0). (This book is no longer available from Wrox but you might find it from a store that sells used books.)
The Open method has two more optional parameters, which we can use to specify a UserID and password when accessing the web server remotely; so the full syntax for the Open method is:
objStream.Open Source, ModeOfAccess, OpenOptions, UserId, Password
Before we try an example, we'll quickly cover some of the Stream object's other methods and properties.
The ReadText Method
Once the Stream object has been opened on a file we can use its ReadText method to examine the contents of the file. Then, by sending the results of this method to Response.Write, we can display the contents of the file. However, you'll hit a problem if you try a line like the following:
Response.Write (objStream.ReadText) ' ...may give unexpected redults!
If you try this you'll find that the output to the page takes the form of a sequence of question marks, and not the text that you might have expected. This is because the Stream object needs to know which character set it is supposed to be using. In order to give that information, we also need to use the Charset property.
The Charset Property
The default character set used by the Stream object is UNICODE, and that's what it will use unless we tell it specifically to use a different character set. In this case, we're using the traditional ASCII set. So in order to achieve the expected output, we need to set the Charset property of the Stream object to ASCII. Then, when we call the ReadText method, we should get some recognizable text:
objStream.Charset = "Ascii"
Response.Write (objStream.ReadText)
The WriteText Method
There is also a WriteText method, which allows you to write text into the source file of the Stream object. For example, we could declare and define a character string (like the strText string below), and then pass this string as a parameter to the WriteText method, ready for writing:
strText = "We'll write this text into the stream"
objStream.WriteText(strText)
Of course, we need to think about at what point in the stream we want the new string to be added. For that, we have the Position property.
The Position Property
The Position property, quite simply, is used to indicate the position within the stream that you wish to start writing. It's an integer value, which indicates the position in terms of the number of characters after the first character. For example:
objStream.Position = 0
This would set the pointer for writing to the beginning of the file.
The EOS Property and the SetEOS Method
If we want to set the position to the end of the file, but we don't know how long the file is then we can use the EOS (end-of-stream) property:
intNum = objStream.EOS
Alternatively, we can force the stream to end at a particular position by using the setEOS method, which updates the value of the EOS property by setting it to be the same as the current Position. For example:
objStream.Position = 0
objStream.SetEOS
This would set the end of stream property to 0. Beware – when you call SetEOS, you'll lose any data that lies between the position specified in the Position property and the old EOS. In particular, the above two lines will succeed in deleting the contents of the file.
We haven't covered all of the Stream object's methods and properties here, but we've covered enough to put it into practice. Let's look at an example that allows the user to change the contents of a text file. Here's what we'll do: we'll ask the user to provide the URL of a text file that needs backing up, and a location for the new backup file to be placed. We'll use a Record object to create the copy of the text file. Then we'll open a Stream object on the contents of the backed-up file, and we'll change the contents of the stream, adding a datestamp.
Try It Out – Creating a Backup
1. Open up your favourite ASP editor to create a new file (which we'll call PromptForURL.htm. Type in the following:
<HTML>
<HEAD>
<TITLE>Backup</TITLE>
</HEAD>
<BODY>
<FORM NAME=form1 METHOD=POST ACTION=CreateBackup.asp>
Type the full URL of the file to be backed up here:<BR>
<INPUT TYPE=TEXT SIZE=50 NAME=URLofFile><BR><BR>
Type the full URL of the desired location for the backup file here:<BR>
<INPUT TYPE=TEXT SIZE=50 NAME=URLofBackup><BR><BR>
<INPUT TYPE=SUBMIT VALUE="Create Backup">
</FORM>
</BODY>
</HTML>
Save PromptForURL.htm into the \inetpub\wwwroot\BegASPFiles folder.
2. Now open another new file (this one will be called CreateBackup.asp) and type in the following:
<%Option Explicit %>
<!-- METADATA TYPE="typelib"
FILE="c:\program files\common files\system\ado\msado15.dll" -->
<HTML>
<HEAD>
<TITLE>Writing the backup</TITLE>
</HEAD>
<BODY>
<%
Dim objStream, objRecord, strURLofFile, strURLofBackup, strText, strDatestamp
strURLofFile = Request.Form("URLofFile")
strURLofBackup = Request.Form("URLofBackup")
Set objRecord = Server.CreateObject("ADODB.Record")
objRecord.Open "", "URL=" & strURLofFile
objRecord.CopyRecord "", strURLofBackup, , , adCopyOverWrite
objRecord.Close
Set objRecord = Nothing
strDatestamp = "'This backup file was created on " & Date & " "
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open "URL=" & strURLofBackup, adModeReadWrite, 'adOpenStreamFromURL
objStream.Charset = "ascii" ' select character set
strText = objStream.ReadText ' read stream into local variable
objStream.Position = 0 ' set current position
objStream.SetEOS ' set EOS to be position 0
' now use strDatestamp and strText to rewrite contents of the stream
objStream.WriteText (strDatestamp + vbcrlf + vbcrlf + strText)
Response.Write "Backup created."
objStream.Close
Set objStream = Nothing
%>
</BODY>
</HTML>
Save CreateBackup.asp into the same folder.
|
3. Now start up your browser and browse to PromptForURL.htm. Type in the full URL of a text or HTML file on your server, and the location of a place where you'd like it to be backed up:
|
|
In order to keep the example simple, we haven't written any error handling – so be careful to enter a valid URL in each text box.
4. When you click the Create Backup button, the CreateBackup.asp page will create the backup and add the datestamp to the backed up copy; and you'll see a message in the browser, informing you that the backup has been created.
|
But the real proof of the pudding is in the eating, so use your Windows Explorer to open the backup file and view its contents
|
|
How It Works
The first page, PromptForURL.htm, just contains an HTML form that prompts the user for the URLs of the original file and the desired location for the backup copy:
<FORM NAME=form1 METHOD=POST ACTION=CreateBackup.asp>
Type the full URL of the file to be backed up here:<BR>
<INPUT TYPE=TEXT SIZE=50 NAME=URLofFile><BR><BR>
Type the full URL of the desired location for the backup file here:<BR>
<INPUT TYPE=TEXT SIZE=50 NAME=URLofBackup><BR><BR>
<INPUT TYPE=SUBMIT VALUE="Create Backup">
</FORM>
These URLs are passed to the page CreateBackup.asp, where they are accessible via the Request.Forms collection (with the names URLofFile and URLofBackup). The first thing we do there is to save those values to local variables:
strURLofFile = Request.Form("URLofFile")
strURLofBackup = Request.Form("URLofBackup")
The rest of the page is concerned with two tasks: first, to create the backup copy (which we'll do using the Record object's CopyRecord method); second, to append the datestamp to the contents of the backup copy (which requires the Stream object's ReadText and WriteText methods).
So let's deal with the first task. We create a new ADO Record object, and open it using the first URL:
Set objRecord = Server.CreateObject("ADODB.Record")
objRecord.Open "", "URL=" & strURLofFile
Now we create the copy of the file. This is just like the code we saw in the RecordMove.asp example, earlier in the chapter. The first parameter of the CopyRecord method is blank, ensuring that we take the default (i.e. the record on which the Record object is opened); the second parameter is the URL of the destination of the backup copy. The option adCopyOverWrite is used to indicate that writing over an existing version of the destination file is allowed:
objRecord.CopyRecord "", strURLofBackup, , , adCopyOverWrite
This is enough to create a copy of the original file. Now the Record object has done its job, we can Close it and release its resources:
objRecord.Close
Set objRecord = Nothing
And that's the first task done; now to the second. We'll start by defining a character string containing the text of the datestamp:
strDatestamp = "'This backup file was created on " & Date & " "
The datestamp string contains the current date, which is generated when needed using the VBScript Date function.
Now we'll open the backup file for modification. To do this, we open an ADO Stream object on the backup file, so that the Stream object represents the character stream of that file:
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open "URL=" & strURLofBackup, adModeReadWrite, adOpenStreamFromURL
We've specified three parameters here. The first parameter is a URL specifying the source of the stream. The second parameter gives us read and write permissions of the stream, and the third indicates that we're opening a stream from a URL.
Note: in a prerelease version of msado15.dll for ADO2.5, the constant adOpenStreamFromURL was undefined. If you have difficulty with this, try adding the following line to your ASP before this point:
Const adOpenStreamFromURL = 8
This is enough to define the missing constant.
We need to specify the character set we're using, to prevent ADO from assuming that we are using UNICODE and generating an error. To specify the character set as ASCII we set the Charset property:
objStream.Charset = "ascii" ' select character set
Now we read the existing contents of the file into a variable called strText:
strText = objStream.ReadText ' read stream into local variable
Now that we have the original contents of the file stored in a string variable, we can write new contents to the file. First, we set the current position to the beginning of the stream, and the EOS (end-of-stream) property to the same position (thus cleaning out the entire stream):
objStream.Position = 0 ' set current position
objStream.SetEOS ' set EOS to be position 0
Then we write our new text into the file. The new content of the stream will consist of the datestamp first, followed by two carriage returns and then the whole of the original contents of the text file:
objStream.WriteText (strDatestamp + vbcrlf + vbcrlf + strText)
Next we write to the browser to inform the user that the backup process has been completed.
Response.Write "Backup created."
Finally we tidy up our Stream object:
objStream.Close
Set objStream = Nothing
And that concludes our basic backup utility.
In this section we've tried to provide only a very brief introduction to ADO's two new objects – the Record and Stream objects. An in-depth discussion is beyond the scope of this book, but hopefully the techniques demonstrated here will go some way to illustrating the kind of functionality that is available from these objects, particularly in the remote administration of web sites, and will tempt you to investigate them further. For more information, try Professional Active Server Pages 3.0 (Wrox, ISBN 1-861002-61-0) and Professional ADO 2.5 (Wrox, ISBN 1-861002-75-0). (Neither of these books is still available from Wrox but you might find them from a store that sells used books.)
| << 14.3.2- The Record Object | Chapter14 | 14.4.0- Summary >> |

RSS



