Академический Документы
Профессиональный Документы
Культура Документы
NET - 32
Question: How can I read the entire contents of a text file into a string?
Answer: To read the contents of a text file use the StreamReader class like so:
VB.NET
Dim sr as New StreamReader("C:\SomeDir\SomeFile.txt")
Dim contents as String
contents = sr.ReadToEnd()
Question: How do I copy or move a file from one location to another?
Answer: Copying a File
The File class contains a Copy() method to copy a file from one location to another. The Copy()
method can accept either two or three input parameters. The first two (required) input parameters
are strings and specify the source file name and the destination file name, respectively. An
example of using the Copy() method can be seen below:
' VB.NET
File.Copy("C:\Dir1\SomeFile.txt", "C:\SomeOtherDir\SomeFile.txt")
// C#
File.Copy("C:\\Dir1\\SomeFile.txt", @"C:\SomeOtherDir\SomeFile.txt");
Question: What is XSLT and how does it relate to XML?
Answer: XSLT, or eXtensible Stylesheet Language, is a language for transforming XML content
from its native form into some other form. For example, many times developers want to display
XML data in a Web page. In these cases, XSLT is used to transform the raw XML content into
HTML.
When transforming XML to HTML using XSLT, typically a .xsl file is created that contains the
specific "instructions" on how to transform the XML content from XML to HTML. .xsl files are
XML-formatted files themselves, and have the following content:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> ... transformation content goes here...
</xsl:stylesheet>
Since XSLT files are XML files, all of the formatting rules that apply to XML files apply to XSLT
files. That is, XSLT files are case-sensitive. All tags must be properly nested and have a matching
closing tag. This includes the HTML tags you use inside the XSLT file!. For example, if in your
XSLT file you wish to add a <br>, you must add it like so: <br />, so that it is a complete tag.
For each book, there is a <book> element. The root element of the XML file is <books>. Now that
we have examined this XML file, imagine that we want to display its contents in an HTML <table>.
We could use XSLT to accomplish this.
XSLT contains a number of tags itself. The most primitive tag is the <xsl:template /> tag. This tag
itself contains further XSLT tags and the content to transform the XML data to. The xsl:template
tag contains a match attribute, which specifies what tag to match in the XML file. For each
instance of the matched tag, the rules within the xsl:template tag are applied.
Since this no doubt sounds terribly confusing, let's take a look at an example, which should help
clarify things. Let's say that we have the following XSLT file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="books/book">
<xsl:value-of select="title" /><br />
</xsl:template>
</xsl:stylesheet>
Here, the xsl:template tag has books/book as its match attribute. This means that for each
books/book in the XML file, the content inside the xsl:template will be applied. (Note that the
books/book returns each book element. This books/book syntax is known as XPath, and is
discussed in greater detail in this FAQ <http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?
FAQID=200>.)
This code example also introduces a new XSLT tag: xsl:value-of. The xsl:value-of tag displays
the text value of the element specified by the select attribute. In the example above, this will
display the title of each of the books in the XML file, with a <br /> immediately after each title.
In addition to the xsl:template and xsl:value-of tags, XSLT contains one more vitally important tag:
xsl:for-each. The xsl:for-each tag is used to iterate through the child tags of a particular tag. For
example, the authors tag in the XML file can have an arbitrary number of child <author> tags. If
we wanted to display the authors for a book, we would need to use a xsl:for-each tag to iterate
through each <author> tag. The syntax for displaying each author's name for a particular book in
an unordered list would be:
<ul>
<xsl:for-each select="authors/author">
<li><xsl:value-of select="text()" /></li>
</xsl:for-each>
</ul>
Here, the XPath expression authors/author specified as the select attribute for the for-each loop
causes each <author> tag to be visited. In order to display the value of the <author> tag, we need
to use <xsl:value-of select="text()" />. (The text() function returns the contents of the inner text of
an XML element.)
Putting it all together, the XSLT file for displaying the list of books in an HTML table can be seen
below:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<table border="1" cellspacing="1" align="center">
<xsl:for-each select="books/book">
<tr><td>
Title: <xsl:value-of select="title" /><br />
Price: <xsl:value-of select="@price" /><br />
Authors:
<ul>
<xsl:for-each select="authors/author">
<li><xsl:value-of select="text()" /></li>
</xsl:for-each>
</ul>
Year Published: <xsl:value-of select="year" />
</td></tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
Here, rather than using the xsl:template tag to match on the each books/book, we simply match
on the document's root node (/) and then use an xsl:for-each to visit each <book> element.
(Also note that an <xsl:output ... /> element has been added. This element informs the XSLT
engine that the output medium is HTML. If you do not set the method attribute to HTML, the XSLT
will emit the XML pre-processing directive - <?xml version="1.0" encoding="utf-8" ?>.)
Question: How can I display XSL-formatted XML data in an ASP.NET Web page?
Answer: Introduction
In a previous FAQ <http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=203>, we examined
a technology called XSL, or eXtensible Stylesheet Language. XSL allows for XML data to be
transformed from its raw form into some other format. A typical application of XSL is to transform
XML data into HTML content, such as an HTML <table>. (An XSLT file is a file that contains XSL
syntax describing how an XML file should be formatted.)
Oftentimes you want to use XSL to display XML data in a Web page. With certain browsers, this
transformation can be applied on the Web browser itself, by specifying the XSL document in the
XML file and having the user visit the XML file directly through their browser. More often than not,
though, you want to transform the XML data to HTML using an XSLT file on the server-side, and
then send this HTML to the requesting browser.
This task can be accomplished in any server-side Web programming language, such as PHP,
ASP, ASP.NET, JSP, and so on. This FAQ will look at how to use the ASP.NET XML Web control
to display XSL-formatted XML data in an ASP.NET Web page - it's insanely easy. Also, at the
end of this FAQ you can find links to information on how to accomplish the same through a
classic ASP page.
* Document
* DocuumentSournce
* DocumentContent
The Document property, if set, must be set to an instance of the XmlDocument class. Therefore,
this is a property that you would set programmatically. For instance, say that you are retrieving
XML data from an RSS feed. As discussed in Consuming an RSS Feed with ASP.NET
<http://aspnet.4guysfromrolla.com/articles/031903-1.aspx>, an RSS feed is XML data retrieved
from a remote URL, and can be accessed with just a few lines of source code in an ASP.NET file.
This XML stream can be read in through an XmlDocument object, which could then be assigned
to the XML Web control's Document property to be displayed in the Web control.
In addition to specifying the XML data for the XML Web control, we also want to specify the XSL
to transform the XML into HTML. The XSL can be specified in a similar fashion as the XML data
was, through one of three properties:
* Transform
* TransformSource
* TransformArgumentList
As with the Document property, the Transform property expects an instance of the XslTransform
class. TransformSource, like DocumentSource, expects a file name that contains the XSL
content. The TransformArgumentList property expects an instance of the XsltArgumentList class.
The XsltArgumentList class can be used to specify a number of XSLT transformations.
An Example
A simple example of displaying XML data using an XSLT file in an ASP.NET Web page can be
seen at this live demo <http://aspnet.4guysfromrolla.com/demos/DisplayXMLinASPNET.aspx>.
The live demo has contains an XML Web control with its DocumentSource and TransformSource
property set to specific file names. Specifically, the XML data comes from this file
<http://aspnet.4guysfromrolla.com/demos/aspnetbooks.xml>, while the XSL comes from this file
<http://aspnet.4guysfromrolla.com/demos/dispBooks.xsl>.
Note that for this example to work, we simply used the following Web control syntax:
<asp:xml runat="server" id="xmlDisp"
DocumentSource="aspnetbooks.xml"
TransformSource="dispBooks.xsl" />
No code needed! It's that simple.
Question: Using CDONTS, how can I set a Reply To email address?
Answer: By default, CDONTS doesn't support any sort of ReplyTo property... for the actual email
it only has the To, From, Subject, Cc, Bcc, Importance and Body properties.
However, CDONTS does have a Value property that can be used to write headers to the email
message. The Reply-To email header indicates an alternative email reply address (as opposed to
the address of the email's sender). Therefore, the following line of code will create a reply to email
address of bob@4GuysFromRolla.com:
CDONTSObjectInstance.Value("Reply-To") = "bob@4GuysFromRolla.com"
Pretty neat, eh? Below is a full example of sending an email and setting the Reply-To parameter
as we did above:
<%
Dim objCDO
Set objCDO = Server.CreateObject("CDONTS.NewMail")
objCDO.To = "mitchell@4guysfromrolla.com"
objCDO.From = "info@4guysfromrolla.com"
objCDO.Value("Reply-To") = "scott@4guysfromrolla.com"
objCDO.Subject = "test"
objCDO.Body = "test"
objCDO.Send
<%
Dim emailAddress
emailAddress = Request("emailAddress")
if emailAddress <> "" then
emailAddress = Cstr(emailAddress)
if emailAddress <> "" then
blnValidEmail = RegExpTest(emailAddress)
if blnValidEmail then
Response.Write("Valid email address")
else
Response.Write("Not a valid email address")
end if
end if
Function RegExpTest(sEmail)
RegExpTest = false
Dim regEx, retVal
Set regEx = New RegExp
RegExpTest = true
End Function
Else
%>
<%End If %>
</body>
</html>
Question: How can I send an email using CDONTS?
Answer: Before you can successfully send an email using CDONTS, you must have the SMTP
Service setup correctly on your Web server. To learn more about this process be sure to read
Getting Starting: The SMTP Service <http://www.aspfaqs.com/webtech/faq/Email/faq1.shtml>.
This FAQ will not delve into the specifics of this task.
Assuming the SMTP Service is setup correctly and the CDONTS component was installed with
the NT Option Pack, sending an email using CDONTS couldn't be easier. All you have to do is
create the object, set some properties, and call the Send method! That's it!
The main properties we are interested in are: To, From, Subject, and Body. Once we set these
properties, a simple call to the Send method shoots off the email! Below you will see a sample
script provided by Rob Taylor:
<%
Dim objMail
Set objMail = Server.CreateObject("CDONTS.NewMail")
objMail.From = "rob@tconsult.com"
objMail.Subject = "How TO send email with CDONTS"
objMail.To = "someone@someplace.com"
objMail.Body = "This is an email message" & vbcrlf&_
"with CDONTS." & vbcrlf&_
"It is really easy. "
objMail.Send
<%
if request("email") <> "" then
Response.write(test(request("email")))
end if
%>
<form action="regex_new.asp">
<input type="text" name="email">
<input type="submit" name="submit" value="check email">
</form>
</body>
</html>
Question: Can I send emails without using CDONTS?
Answer: Heavens yes! CDONTS is just one email component, there are many others. CDONTS
has its limitations - it can only be used on Windows NT Server and does not provide very many
options in sending emails. According to Microsoft's documentation, CDONTS was designed for
sending quick, text-based emails. The nice thing about CDONTS is that it is likely already
installed on your Web server and it's free!
Question: How do you send email attachments through an ASP page?
Answer: The CDONTS mail object can be used to send email attachments - it contains a method
named AttachFile. The file you wish to attach must exist on the Web server (or be accessible on a
remote machine by the IUSR_MachineName account) and the IUSR_MachineName must have
Read permission on the file you wish to attach. Furthermore, you must know the file's physical
path.
Dim objMail
Set objMail = Server.CreateObject("CDONTS.NewMail")
objMail.From = "friend@somewhere.com"
objMail.Subject = "A message TO you"
objMail.AttachFile("d:\images\pic.gif")
objMail.To = "someone@someplace.com"
objMail.Body = "This is the body of the Message"
objMail.Send
As a rule it looks like to set global cookies that can be readable by both the client and server do
this:
Setting on server:
path="/"
domain="www.mydomain.com"
Setting on client:
<no path>
domain="www.mydomain.com"
Question: How can I display all of the cookies/cookie values for a user through a Web page?
Answer: All of the cookies and their values for a particular user are stored in the Cookies
collection of the Request object. These can easily be cycled through using a For Each ... Next
script. Such a script is shown below, and was submitted by Ed A. (armelino@yahoo.com
<mailto:armelino@yahoo.com>):
<html>
<body>
<font face="ariel, helvetica" size="3">
Here are the active session Cookies with Keys:
</font>
<table border="0" cellspacing="0" cellpadding="0">
<%
Dim Cookie, Key, vCount
vCount = 0
If Request.Cookies(Cookie).HasKeys Then
For Each Key in Request.Cookies(Cookie)%>
<tr>
<td>
<font face="ariel, helvetica" size="2">
<%=Cookie%> (<%=vCount%>) is called:
<%=Key%>
</font>
</td>
<td>
<font face="ariel, helvetica" size="2">
<%=Cookie%> (<%=Key%>) =
<%=Request.Cookies(Cookie)(Key)%>
</font>
</td>
</tr>
<%
vCount = vCount + 1
Next
Else %>
<tr>
<td colspan="2">
<font face="ariel, helvetica" size="2">
No Keys in this cookie. <br>
</font>
</td>
</tr>
<%
End If
Response.Write "<br><br>"
vCount = 0
Next %>
</table>
</body>
</html>
Question: How can I delete an existing cookie?
Answer: Many sites that use cookies as a form of authentication or user settings, provide a "Log-
off" button (or something similar) that will seemingly "destroy" all of the cookies that represent the
authentication (or user preferences). This is accomplished quite simple. First, assume that you
have a page named SetCookie.asp that creates a cookie using the following code:
<%
Response.Cookies("MyCookie") = "Foobar"
%>
A page, LogOff.asp could be created with a very simple line of code, that would, in effect, "delete"
the cookie MyCookie. The code for LogOff.asp follows:
<% Response.Cookies("MyCookie") = "" %>
Question: How can I determine if a visitor has cookies support enabled in his/her browser?
Answer: There are a number of ways to determine whether or not a user has Cookies enabled in
his or her browser. The simplest, and cheapest, way to accomplish this is fairly straightforward:
With the current version of Norton AntiVirus, there is a new feature that blocks script access. The
scanner thinks that your IUSR_MachineName is doing something nefarious. You may turn the
"script blocking" feature off. View this link for more details:
Question: How can I randomly select n lines from a text file?
Answer: Imagine the situation where you have a large text file and you want to randomly choose
some subset of lines from the file. For example, imagine that you had hundreds of MP3s on your
computer and a text file that had a listing of these files, such that each line of the text file
contained the full path to the MP3 file. Now, you might want to have a program that randomly
select, say, 10 MP3 files from the text file containing the list of all MP3s.
This task is fairly easy to accomplish using the FileSystemObject in tandem with VBScript's split
function. The split function breaks up a delimited string into a one-dimensional array; therefore, if
we read the entire contents of a file into a string and then use the split method (using new line
characters (vbCrLf) as the delimiters), we can read an entire file's contents into an array, where
each element in the array corresponds to a line in the file. (For more information on split, see:
Parsing with split and join <http://www.4guysfromrolla.com/webtech/050999-1.shtml>.)
First, we simply read the entire contents of the file into an array, aFiles, where each element in
the array corresponds to a line in the text file:
Dim objFSO, objTS
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Now, use split to load the contents of the file into an array
Dim aFile
aFile = split(s, vbCrLf)
Easy enough. Now we can use the Rnd function to choose random values between 0 and the
upper bound of aFile. To do this, first we must use the Randomize Timer function and then
perform a loop to snip out the n random elements from the array.
Randomize Timer
For i = 1 to n
value = aFiles(Int(Rnd * UBound(aFiles)))
4Guys visitor Rafeeq has created such a function and shares it in a User Tip
<http://www.aspfaqs.com/webtech/tips/> titled: Reading a File into an Array
<http://www.aspfaqs.com/webtech/tips/t101700-1.shtml>.
(For more information on using the FileSystemObject, see the following FAQ: What is the
FileSystemObject? <http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=23> For more
information on resizing arrays, be sure to visit the FAQ: How can I dynamically resize an array?
<http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=7>)
Another option is to use VBScript's built-in split function. The split function breaks up a delimited
string into a one-dimensional array; therefore, if we read the entire contents of a file into a string
and then use the split method (using new line characters (vbCrLf) as the delimiters), we can read
an entire file's contents into an array, where each element in the array corresponds to a line in the
file. (For more information on split, see: Parsing with split and join
<http://www.4guysfromrolla.com/webtech/050999-1.shtml>.)
Essentially, you can use the following code (taking advantage of the textstream's ReadAll
method, that reads the entire contents of a file in one go):
Dim objFSO, objTS
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Now, use split to load the contents of the file into an array
Dim aFile
aFile = split(s, vbCrLf)
Question: How can I delete files by extension in a given directory? What if I have multiple file
extension names I want to delete?
Answer: There are many situations in which you may wish to delete all files containing a certain
file extension in a certain directory. The naive approach to solving this problem would involve
iterating through all of the files in the directory and checking the file extension for each file - if it
matched the criteria, the file would be deleted. While such an approach would work, there's a
much easier way to accomplish the same task.
Th DeleteFile method of the FileSystemObject can accept wildcards. That means, you can call
DeleteFile like so:
objFSO.DeleteFile("C:\SomeDirectory\*.txt")
to delete all of the .txt files in C:\SomeDirectory. Neat, eh? In fact, you can use wildcards other
than the *, such as the ?.
Well, it isn't that easy, there is one catch. If there are no files in the directory that match the
wildcard expression the DeleteFile method will raise an error, saying it couldn't delete the
specified file. Hence, before using the DeleteFile method with wildcards you should turn off error
handling via a On Error Resume Next statement. To learn more about error handling in VBScript
be sure to read: Error Handling in ASP <http://www.4guysfromrolla.com/webtech/060399-
1.shtml>.
Now, if you wanted to allow the user to delete multiple file extensions, you'll need to call the
DeleteFile method multiple times. Below you'll find a function that accepts two input parameters:
objFSO.MoveFile Server.MapPath("/someDir/Foo.asp"), _
Server.MapPath("/someDir/Bar.asp")
To rename a directory on a Web server, we must use the same approach using the
MoveDirectory method (seeing as there's no RenameDirectory method available). So, if you have
a directory on your Web server with the physical path C:\Foo and you wished to rename it to
C:\Bar, you could use the following code:
'Create an instance of the FileSystemObject
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Open the text file
Dim objTextStream
Set objTextStream = objFSO.OpenTextFile("C:\SomeFile.txt", fsoForReading)
One important thing to keep in mind when using the FileSystemObject is permissions! In
Windows NT, there are three types of permissions: Read, Write, and Full Access. Whenever an
ASP page attempts to execute some file system command using FSO, the anonymous web user
ID is used: IUSR_machinename (i.e., if your webserver is named Bob, the user ID is IUSR_Bob).
If IUSR_machinename doesn't have permissions to Read for a particular directory, you cannot
use FSO to read the contents of a file in that directory through an ASP page. If
IUSR_machinename doesn't have permissions to Write for a particular directory, you cannot use
FSO to write a file to that directory through an ASP page. If IUSR_machinename doesn't have
Full Access permissions for a particular directory, you cannot use FSO to delete or move a file
from that directory through an ASP page.
Question: How can I create a file with a random file name?
Answer: There are oftentimes when developers need to create a temporary text file whose
usefulness usually extends only for a short period of time. For example, in Creating Excel
Spreadsheets with Office Web Components (OWC)
<http://www.4guysfromrolla.com/webtech/022801-1.shtml>, a dynamically generated Excel
spreadsheet is created each time a user visits a page. Imagine what might happen if, for every
visitor to the page, an Excel spreadsheet was created with a single, hard-coded filename (say
Results.xls). UserA might visit the ASP page that generates a personal Excel spreadsheet named
Results.xls, which can be downloaded. If between the time UserA generates the spreadsheet and
when UserA actually gets around to downloading the file, what would happen if UserB comes in
and hits the same page, generating his own Excel spreadsheet with the same file name
(Results.xls)? When UserA went to download his spreadsheet, he would see the result of UserB's
query! Egad.
The thing to note is that a random (temporary) file name will be generated from the method. Note
that this method does not create a file, it just returns a file name that can be used to create a
temporary file. (View the technical docs
<http://msdn.microsoft.com/scripting/vbscript/doc/vsmthgettempname.htm> for GetTempName.)
The GetTempName method only returns a file name, though. If you want to grab the official
Windows temporary folder you can use the GetSpecialFolder method of the FileSystemObject.
This method expects one parameter, the specific "special folder" path to return. This parameter
can accept one of three values:
Of course we should strive to not use magic numbers, but rather define constants for the values
of 0, 1, and 2. The code below shows how to use the GetSpecialFolder method to return the
name of the temporary folder and how to use the GetSpecialFolder method in conjunction with
the GetTempName method to return a fully functioning temporary folder/file name.
<%
Const fsoTempFolder = 2
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Question: How can I get the path of the system temporary folder? Also, how can I get a filename
for a temporary file?
Answer: The FileSystemObject provides a function - GetSpecialFolder - that can be used to
retrieve the path of the folder Windows has designated as the temporary folder. GetSpecialFolder
can also be used to get the Windows folder name and the System folder name (usually
C:\WINNT\ and C:\WINNT\System32, respectively). The GetSpecialFolder function has the
following definition:
FileSystemObjectReference.GetSpecialFolder(folderspec)
folderspec determines what special folder is returned:
0 - The Windows Folder is returned
1 - The System folder is returned
2 - The Temporary folder is returned
The GetSpecialFolder function returns a Folder object, which contains a number of properties. To
simply get the path to the temporary folder, we will use the GetSpecialFolder to return a folder
object, and then use the Path property of the Folder object to return the path of the temporary
folder.
<%
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
When using the TextStream object or other FSO objects, you need to first declare an instance of
the FileSystemObject. For our script, let's start by creating an instance of the FileSystemObject:
'Create an instance of the FileSystemObject object
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Before we open a file, we should always test to make sure it exists. The FileSystemObject
provides a useful function to determine whether or not a file exists, aptly named FileExists. The
syntax for FileExists is:
FileSystemObjectInstance.FileExists(FullFilePath)
So, in this example, we want to output the contents of the text file D:\scott\resume.txt. Before we
open our file, we will make sure that it exists.
Earlier I mentioned that the TextStream object is responsible for reading and writing to the
contents of a text file. A TextStream object instance is used to iterate through the contents of a
particular text file. So, before we can use a TextStream, we must inform the TextStream object
instance what text file we are interested in. This is accomplished using the FileSystemObject's
OpenTextFile method. The OpenTextFile method has the following syntax:
FileSystemObjectInstance.OpenTextFile(FullFilePath[, iomode])
Note: there are two more parameters, but we are only interested in these first two for the time
being. If you are interested in the full specifications, read this
<http://help.activeserverpages.com/iishelp/VBScript/htm/vbs352.htm>.
The optional iomode parameter decides what IO mode the file is opened with. The following
values can be used:
ForReading - 1
ForWriting - 2
ForAppending - 8
These constants are not defined in a text file like the ADO constants are defined in ADOVBS.inc,
which you can learn more about at: ADOVBS.inc: Use It!
<http://www.aspfaqs.com/webtech/faq/Beginner/faq7.shtml> Therefore, you should define the
constant you wish to use. For example, if I use the ForReading constant, you
will see ASP code like:
Const fsoForReading = 1
The OpenTextFile method returns a TextStream object instance. So, to set a variable to a
TextStream object instance for reading the contents of a particular file, you would use the
following syntax:
'Assumes a FileSystemObject instance named objFSO exists
Const fsoForReading = 1
Dim objTextStream
Set objTextStream = objFSO.OpenTextFile("C:\SomeFile.txt", fsoForReading)
The TextStream object has the following important methods for reading text files:
Read(characters) - Reads a specified number of characters from the text file, returning a resulting
string.
ReadLine - Reads an entire line up to, but not including, the new line character. The results are
returned as a string.
ReadAll - Reads the entire contents of the file, returning the results as a string.
Finally, the TextStream object has a Close method, which should be used when you have
finished reading from the file.
Now, let's look at how we could read the entire contents of a text file, D:\scott\resume.txt. We will
use the FileExists method first, to make sure that the file does indeed exist. If it does, we'll output
the contents of the file; if it doesn't, we'll display an appropriate message.
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Dim objTextStream
If objFSO.FileExists("D:\scott\resume.txt") then
'The file exists, so open it and output its contents
Set objTextStream = objFSO.OpenTextFile(strFileName, fsoForReading)
Response.Write "<PRE>" & objTextStream.ReadAll & "</PRE>"
objTextStream.Close
Set objTextStream = Nothing
Else
'The file did not exist
Response.Write strFileName & " was not found."
End If
'Clean up
Set objFSO = Nothing
end function
Question: How can I rename a file on my Web site through an ASP page?
Answer: Unfortunately the FileSystemObject doesn't contain a Rename method; it does, however,
have a method that can be used as a substitute for Rename: MoveFile. MoveFile accepts two
parameters: the physical path to an existing file and the physical path to where you want to move
the file. To rename a file, all we have to do is alter the filename from the first parameter to the
second. For example, if we wanted to rename Foo.asp to Bar.asp, we could use the following
code:
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile Server.MapPath("/someDir/Foo.asp"), _
Server.MapPath("/someDir/Bar.asp")
DeleteFile takes one required and one optional parameter. The first parameter, which is required,
is the physical file name of the file to delete, like C:\MyFiles\foo.txt. The second parameter, which
is option, is a Boolean value (True or False) and, if not specified, defaults to a value of False. This
second parameter determines whether or not read-only files can be deleted. If you will be deleting
read-only files, you must specify the second parameter as True.
So, if we wanted to delete the file C:\Foo\readme.txt, we could use the following code:
'Create the FileSystemObject
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Create C:\FooBar
objFSO.CreateFolder("C:\FooBar")
It's that simple! One caveat: if the folder already exists and you try creating it, you will get a "File
Already Exists" error. Therefore, rather than just blindly adding a new folder, you may wish to
check if it exists first and, if it doesn't, then add it. You can check to see if a folder exists using the
FolderExists method of the FileSystemObject object like so:
'Create an instance of the FileSystemObject
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Create C:\FooBar
If Not objFSO.FolderExists("C:\FooBar") then
objFSO.CreateFolder("C:\FooBar")
End If
Question: How can I create a text file on the Web server's file system?
Answer: The FileSystemObject contains a handy method for creating text files on the Web
server's file system. This method was aptly named: CreateTextFile, and has the following calling
syntax:
TextStreamObject = fsoObjectInstance.CreateTextFile(filename[, overwrite[, unicode]])
filename should be the complete physical path of the file you wish to create. For instance, if you
wish to create a text file in the directory C:\Inetpub\wwwroot\MyWeb named Hello.txt, filename
should be: C:\Inetpub\wwwroot\MyWeb\Hello.txt. (If you don't know the full physical path of your
Web site you can always find out using Server.MapPath. For more information see: Using
Server.MapPath <http://www.4guysfromrolla.com/webtech/121799-1.shtml>!)
overwrite and unicode are both optional Boolean values, both of which default to False. overwrite
indicates what should happen when you try to create a file but a file with the same name in the
same folder already exists. If overwrite is specified True, the file will be overwritten; if overwrite is
specified as False (or omitted) the file will not be overwritten and you will receive an error. If
unicode is specified as True, the file is treated as a Unicode file; if unicode is specified False (or
omitted), the file is treated with the ASCII encoding.
Update from Bill Wilkinson <mailto:billw@chilisoft.com>
BEGIN QUOTE
You say: "if unicode is specified False (or omitted), the file is treated with the ASCII encoding."
Not true. The file is treated as multibyte character encoding. That is, the current
Session.CodePage is used in converting the Unicode characters that are ALWAYS used inside
VBS and JS into the given multibyte encoding. In US English, and in most Western European
languages, the multibyte encoding is actually single byte and is ASCII (well...not really...because
ASCII only goes to character number 127...ISO would be more accurate). But in all the Eastern
Asia languages and some of the other non-European languages, each unicode character
translates to 2 or 3 or even 4 bytes in the text file stream when unicode is not specified.
END QUOTE
Thanks Bill!
The CreateTextFile method returns a TextStream object that represents the newly created file.
With this TextStream object you can write the contents to the file. (Check out Using the
FileSystemObject to Write to Text Files
<http://www.4guysfromrolla.com/webtech/faq/FileSystemObject/faq3.shtml> for information on
using the TextStream object to write to a file.)
The following shows some very simple code that will create a text file named
C:\MyDirectory\foo.txt with the contents Hello, World!.
<%
'Create our FSO and TextStream objects
Dim objFSO, objTS
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Clean up!
objTS.Close
Set objTS = Nothing
Set objFSO = Nothing
%>
Question: When I get a list of all files in a directory via the FileSystemObject, they aren't ordered
in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or...
Answer: The short answer is: Copy all the files into an array and then sort the array.
If all you want to do is sort the files by name, then that is pretty easy to do.
However, if you want to sort the files by size or date created or whatever, then you can't use a
simple array. You must use a two-dimensional array, an array of VBScript objects (that is,
instances of a VBScript Class that you define), or--my own preference for this particular task--an
array of arrays.
The following code is a demonstration page that allows the user to choose the desired sort by
clicking in a link at the head of any column. (And clicking the same link twice will reverse the sort!)
You might be able to use some variation on this almost unchanged for your own purposes.
However, if you want to "fix" the sort order, it's easy to do. Just get rid of the HTML links (the <A
HREF=...> stuff) and the JavaScript code and hard-code in the values for sortBy and priorSort
and presto! You will have your sorted directory listing.
Give it a try!
<HTML>
<HEAD>
<TITLE>Bill Wilkinson's sort-it-any-which-way Directory Listing</TITLE>
</HEAD>
<BODY>
<%
' In this demo, at least, we don't allow user to change directories...
' Change the DIRECTORY to point to any virtual directory of your choice.
CONST DIRECTORY = "/" ' relative path in virtual directories
'
' did user ask for same sort? to reverse the order?
' but if so, then zap priorSort so clicking again will do forward!
If sortBy = priorSort Then
reverse = true
priorSort = -1
Else
reverse = false
priorSort = sortBy
End If
' We collect all the info about each file and put it into one
' "slot" in our "theFiles" array.
'
For Each fileItem in curFiles
fname = fileItem.Name
fext = InStrRev( fname, "." )
If fext < 1 Then fext = "" Else fext = Mid(fname,fext+1)
ftype = fileItem.Type
fsize = fileItem.Size
fcreate = fileItem.DateCreated
fmod = fileItem.DateLastModified
faccess = fileItem.DateLastAccessed
currentSlot = currentSlot + 1
If currentSlot > UBound( theFiles ) Then
ReDim Preserve theFiles( currentSlot + 99 )
End If
' note that what we put here is an array!
theFiles(currentSlot) = Array(fname,fext,ftype,fsize,fcreate,fmod,faccess)
Next
'
' files are now in the array...
'
' As noted, it is actually an ARRAY *OF* ARRAYS. Which makes
' picking the column we will sort on easier!
'
' ...size and sort it...
fileCount = currentSlot ' actually, count is 1 more, since we start at 0
ReDim Preserve theFiles( currentSlot ) ' really not necessary...just neater!
'
' A simple bubble sort for now...easier to follow the code...
'
For i = fileCount TO 0 Step -1
minmax = theFiles( 0 )( sortBy )
minmaxSlot = 0
For j = 1 To i
Select Case kind ' which kind of sort are we doing?
' after the "is bigger/smaller" test (as appropriate),
' mark will be true if we need to "remember" this slot...
Case 1 ' string, reverse...we do case INsensitive!
mark = (strComp( theFiles(j)(sortBy), minmax, vbTextCompare ) < 0)
Case 2 ' string, forward...we do case INsensitive!
mark = (strComp( theFiles(j)(sortBy), minmax, vbTextCompare ) > 0)
Case 3 ' non-string, reverse ...
mark = (theFiles( j )( sortBy ) < minmax)
Case 4 ' non-string, forward ...
mark = (theFiles( j )( sortBy ) > minmax)
End Select
' so is the current slot bigger/smaller than the remembered one?
If mark Then
' yep, so remember this one instead!
minmax = theFiles( j )( sortBy )
minmaxSlot = j
End If
Next
' is the last slot the min (or max), as it should be?
If minmaxSlot <> i Then
' nope...so do the needed swap...
temp = theFiles( minmaxSlot )
theFiles( minmaxSlot ) = theFiles( i )
theFiles( i ) = temp
End If
Next
' Ta-da! The array is sorted!
'
%>
<FORM Name="doSort" Method="Get">
<INPUT Type=Hidden Name=priorSort Value="<% = priorSort %>">
<INPUT Type=Hidden Name=sortBy Value="-1">
</FORM>
<SCRIPT Language="JavaScript">
function reSort( which )
{
document.doSort.sortBy.value = which;
document.doSort.submit( );
}
</SCRIPT>
<CENTER>
<FONT Size="+2">
Showing <% = (fileCount+1) %> files from directory <% = path %>
</FONT>
<P>
Click on a column heading to sort by that column. Click the same column
again to reverse the sort.
<P>
<TABLE Border=1 CellPadding=3>
<TR>
<TH><A HREF="javascript:reSort(0);">File name</A></TH>
<TH><A HREF="javascript:reSort(1);">Extension</A></TH>
<TH><A HREF="javascript:reSort(2);">Type</A></TH>
<TH><A HREF="javascript:reSort(3);">Size</A></TH>
<TH><A HREF="javascript:reSort(4);">Created</A></TH>
<TH><A HREF="javascript:reSort(5);">Last modified</A></TH>
<TH><A HREF="javascript:reSort(6);">Last accessed</A></TH>
</TR>
<%
' With the array nicely sorted, this part is a piece of cake!
For i = 0 To fileCount
Response.Write "<TR>" & vbNewLine
For j = 0 To UBound( theFiles(i) )
Response.Write " <TD>" & theFiles(i)(j) & "</TD>" & vbNewLine
Next
Response.Write "</TR>" & vbNewLine
Next
%>
</TABLE>
</BODY>
</HTML>
Question:
How can I determine the file size of a file on the Web server?
Answer:
The FileSystemObject contains a library of objects, one of which is the File object. This object, as
its name suggests, provides information relating to a file on the Web server. One of the properties
of the File object is Size, which returns the size of the file in bytes. The FileSystemObject
contains a method, GetFile(FilePath), which will return a File object that represents the file
specified by FilePath.
So, putting this all together, we can get the size, in bytes, of a file on the Web server with the
following code:
'What is the path of the file whose size you're interested in?
Dim strFileName
strFileName = "C:\FooBar\blah.txt"
Question: How do I insert more information into the middle of a text file? How do I delete
something from a text file? How do I add to the front of a text file?
Answer: Short answer: YOU CAN NOT DO THAT.
Longer answer: First of all, we need to note that this is not a limitation of ASP, of the
FileSystemObject, of VBScript, or of the Windows operating system. There is no system in the
world, on any kind of computer, that allows any of those operations.
To understand why, you have to understand how data is stored on a disk, especially data in the
form of a text file.
A directory entry (a file name) simply points to a starting point of the disk. (Perhaps something in
the form of "start at block number 77123".) And then the data starts at that spot and continues,
without interruption, to the end of the block. If the data is larger than a block, then again the
directory (typically...there are other schemes possible, though none that I know of used in modern
operating systems) points to the next block to be used. Again, the data continues at the start of
the next block and continues to the end of it. The process is repeated until all the data is written to
the disk.
Now, can you dream up a scheme whereby you could insert or remove some data from the
middle of that file???
Effectively, you'd have to find a way to "stretch" or "shrink" a block on the disk, wouldn't you? But
blocks are always a fixed size (in fact, excepting for a few mainframe operating systems, they are
always the same size throughout a given disk drive). You can't change their size! So you can't
insert or delete data. Period.
The only way to alter the contents of a text file (other than by appending data to the end of it--
which is allowed by Windows) is to read all the data (the entire text file) into memory, change the
data, erase the original file, and then write the new data back to the same file.
ASP vs ASP.NET
Question: Can I still run ASP pages on a server that runs ASP.Net?
Answer: Yes. They will run side-by-side with no adverse affects to the ASP pages at all.
Question: Can ASP pages and ASP.Net pages share session variables.
Answer: No. Both support session variables, but the session variables are not shared across the
two platforms.
Controls built with .NET run within a secure client-side sandbox -- so that they can be prevented
from maliciously attacking a users client system (so that it has none of the security concerns that
activex controls have today). Once downloaded they are also cached on the client machine --
enabling you to have to re-download them again on each visit to the page.
Question: I want to use a style sheet class directly on a control instead of using inline or page-
level formatting, is it possible?
Answer: Every WebControl derived control has a CssClass property which allows you to set it's
format to a style sheet.
COM
Question: Is it true that COM objects no longer need to be registered on the server?
Answer: Yes and No. Legacy COM objects still need to be registered on the server before they
can be used. COM developed using the new .NET Framework will not need to be registered.
Developers will be able to auto-register these objects just by placing them in the 'bin' folder of the
application.
Question: Can .NET Framework components use the features of Component Services?
Answer: Yes, you can use the features and functions of Component Services from a .NET
Framework component
Question: Some of my VB6 COM+ DLLs won't work in ASP.Net. Can I make them work?
Answer: Try adding the following line to the top of your .aspx page.
<%@ page aspcompat=true %>
Question: What does the line <%@ page aspcompat=true %> actually do?
Answer: ASP used an STA based thread-pool optimized for apartment-threaded
components. This thread-pool was managed by MTS -- which is how/why ObjectContext could
be flowed to components on a page.
Request = HttpContext.Current.Request
Response = HttpContext.Current.Response
Enabling the <%@ page aspcompat=true %> switch at the top of the page does two things:
1) Causes that page to be executed on an STA thread-pool instead of the new MTA one. This
optimizes performance for VB6 created apartment threaded components.
2) Causes us to surface the old ASP COM Intrinsics via ObjectContext. This will enable existing
COM components built against the old ASP typelibraries to continue to work (note that if you want
to get access to the new ASP.NET intrinsics -- you need to write code like the ones above).
Configuration
Question: Why can't I pull a certain key from the config.web file?
Answer: Configuration lives in XML files, and XML is case sensitive, no matter the language.
Double-check that you are referencing the key name exactly as it is specified.
For example, the below config.web file could be used to set specific authorization settings on an
individual file (called "MyFile.aspx"):
<configuration>
<location path="MyFile.aspx">
<security>
<authorization>
<deny users="redmond\scottgu"/>
</authorization>
</security>
</location>
</configuration>
The below config.web file can be used to set specific authorization settings on a subdirectory
called "mysubdirectory":
<configuration>
<location path="mysubdirectory">
<security>
<authorization>
<allow users="redmond\scottgu"/>
<deny users="*"/>
</authorization>
</security>
</location>
</configuration>
Note that an alternative way to do the above subdirectory approach would also to have just
dropped a config.web file (with no location directive) within the "mysubdirectory"
directory. ASP.NET would then have those settings apply to that directory and any of its own
subdirectories.
Question: How can I set up security (using cookie authentication) so that all pages are off limits
unless you are logged in - except a few select pages?
Answer: You can configure ASP+ to disallow non-authenticated users by adding the following
section to your config.web file:
<configuration>
<security>
<authentication>
<deny users="?"/>
</authentication>
</security>
</configuration>
This will deny access to "anonymous users" (ie: ones who haven't logged in yet). You can also
use config.web settings to allow access to only a few select pages by using the <location>
directive:
<configuration>
<location path="Default.aspx">
<security>
<authentication>
<allow users="*" />
</authentication>
</security>
</location>
</configuration>
The above example will grant access to the "Default.aspx" page for everyone.
Question: I store database connection information in my config.web file. Should I read this
information once and manually cache it for a performance gain?
Answer: The recommended way to use GetConfig() is to call it within each request and let the
configuration system cache the results.
Question: Where should I store some basic configuration information - like database connection
strings?
Answer: You can use the built-in ASP.NET XML configuration system. To store "Application level
settings" simply add an <AppSettings> tag to your application's config.web file:
<configuration>
<appsettings>
<add key="dsn" value="myserver"/>
<add key="someotherkey" value="somevalue"/>
</appsettings>
</configuration>
You can then read these values from any page/service/component by writing the following code:
All of these settings are cached -- so it ends up being super fast/scalable to use this
approach. ASP.NET also automatically monitors the config files. If they ever change -- this will
automatically be reflected within the
configuration APIs you use within your application.
Question: How can I configure forms authentication on a sub-directory beneath a web root?
Answer: Here is some sample code to demonstrate this....
<configuration>
<system.web>
<customErrors mode="Off"/>
<authentication mode="Forms">
<forms name="TestAuthCookie" loginUrl="/admin/login.aspx">
<credentials passwordFormat="Clear">
<user name="testuser" password="password"/>
</credentials>
</forms>
</authentication>
</system.web>
<location path="test">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
Question: Why do I get an error when I try to use decryptionkey in my forms authentication.
Answer: decriptionKey is now a server-wide setting. You need to set this value in the
machine.config file and can not over-ride it at the web level.
Installation
Question: What are the system requirements to install and run the Beta 1 .Net Framework?
Answer: * Processor: Intel Pentium II-class 300 MHz (Intel Pentium III-class 600 MHz
recommended)
* RAM: 96 MB (128 MB recommended)
* Hard disk space required to install: 360 MB
* Hard disk space required: 210 MB
* Additional space required to install and compile all samples: 300 MB
* Video: 800x600, 256 colors
Question: Do I need to uninstall the PDC version of the .Net Framework before installing the Beta
1 version?
Answer: Yes. You need to completely remove the PDC versions of the Visual Studio and also
the .Net Framework
The SDK contains docs, samples and utilities. It also contains basic ASP.NET support (does not
have web farm session state or output caching support in it though). This will be changed for
RTM -- when the SDK will have everything.
So, to summarize:
2a. Open IIS in the MMC and view the properties of the quickstart applications.
2b. Click on the Directory Security Tab
2c. Click the button "Edit" under IP Address and Domain Name Restrictions.
2d. Either Grant Access to your machine IP or to everyone, depending on your need.
Question: Is there a way to install VS.Net beta 1 on a machine that has VS PDC installed -
without having to reformat?
Answer: It is recommended to place Visual Studio .Net Beta 1 on a machine that has NOT had
the PDC version installed. If you can't rebuild the machine for some reason, you will have to make
sure that the PDC version is fully removed before installing Beta 1.
To remove the PDC version:
1. From the Start menu, choose Run.
2. In the Run dialog box, type the following: msiexec.exe /x {33334F07-0C6B-11D3-A51D-
00A0C9231BA1} NOVSUI=1
3. Answer Yes, when prompted, to proceed with the removal of Visual Studio.NET PDC Tech
Preview.
4. In the Run dialog box, type the following: msiexec.exe /x {62EDCF3C-69F4-11D3-A521-
00A0C9231BA1}
5. Answer Yes, when prompted, to proceed with removal of the Pre-release Bootstrap for Visual
Studio.NET PDC Tech Preview.
6. From the Start menu, choose Settings and then Control Panel.
7. Choose the Add/Remove Programs and then choose Change or Remove Programs.
8. Select Microsoft NGWS SDK and choose Change/Remove.
9. Answer Yes to proceed with removal.
10. Remove all files from n:\Documents and Settings\All Users\Application Data\Microsoft Help.
This step ensures that PDC release documentation is removed and that only beta documentation
appears.
State Management
Question: What is being passed back and forth in the _ViewState form control?
Answer: The __VIEWSTATE hidden field is used to transfer the differences in controls from what
is declared in the page -- and the values they contain at the end of a request immediately prior to
rendering. We can then use this information to re-construct the server controls to match that last
rendered state during "postbacks" to a page.
The information within the __VIEWSTATE field is not really encrypted -- although the values are
definitely "cyptic" to read (mainly because server controls try to store information in as compact a
format as possible -- and because our serializer performs some limited compression).
You can see how much viewstate each control is saving by enabling tracing for the page. For
example, by adding a trace attribute to the page directive:
This will cause a table to be output at the bottom of the page. This won't show the exact values
stored in viewstate -- but will give you a rough estimate of the size of each server control value.
Note that you can disable the viewstate feature -- either for the entire page or on specific server
controls. This is done at the page level by setting the following page directive:
Question: How do I setup web farm session state to use SQL Server?
Answer: Run the ASP.NET Session State SQL Script to create the appropriate tables within a
SQL Server database. Then modify your application's config.web file to point to this
database. ASP.NET will then, under the covers, handle serializing your state from the Session
intrinsic to/from the database.
Question: What new ways are there to handle session state in a web cluster?
Answer: There are two new methods of handling session state in a web cluster.
The first method is to designate one server as a "state server" by enabling the state service on it.
This server can then be the central store of state information for the entire cluster.
Another option is to persist the state information directly to a SQL Server database. This not only
gives you a shared, central store for state information but also allows you to retain state
information in case of a failure or server reboot.
Question: How well does the ASPState perform when stored in SQL Server?
Answer: The target performance for the full release of ASP.Net will be 75-80% of the
performance seen by using in-process state management.
Question: Is there a way to directly query session data if a SQL Server StateStore is being used?
Answer: The session data is encrypted but the creation date, expiration date,
session id, and timeout are all directly available.
Instead, if you need to save the DataSet across requests, I'd recommend storing it in Session
state. ASP.NET now supports web farm session state -- meaning you will no longer need to
worry about being tied down to a single machine in this scenario.
using System.Net
VB
If want to mix comments with the HTML you can do something like:
<%--
this is a comment inside of some html
that will not show up at the client
--%>
Try
line=sr.ReadLine()
lineENC = server.HTMLencode(line) & vbcrlf & "<br>"
build.append (lineENC)
For i = 1 To 10
Response.Write("<P>" & r.Next(1, 10))
Next
VB.NET
Question: How do I resolve the VS.Net error "has not been setup for the current user"?
Answer: Run regedit and try to find the following Registry Key
[HKEY_CLASSES_ROOT\Licenses\C4B8C1BC-A36C-4723-AF48-F362BFAB9DF5]
XML
Question: What happened to System.NewXML that was in the pre-beta?
Answer: It has been renamed to System.XML in Beta 1
Question: What is a good tool to use when working with XML?
Answer: XMLSpy has been recommended by several people as one of the better XML tools
available.
Question: I'm trying to create a DataView from an XML data source but I am getting this error 'No
compositors found under ComplexType'.
Answer: Add the <all> tag around the elements in the complexType. This is a schema change
from the PDC bits.
Example:
<element name="State">
<complexType content="elementOnly">
<all>
<element name="Name" type="string" />
<element name="Abbreviation" type="string" />
</all>
</complexType>
</element>
Question: Where is sample code that demonstrates a use of the <asp:xml> server control?
Answer: Here is a simple sample that demonstrates a use of the <asp:xml> server control that
shipped in Beta1
<html>
<body>
<asp:xml id="MyXml1" DocumentSource="Perf.xml" TransformSource="Perf.xsl"
runat=server/>
</body>
</html>
--------------------------------
Perf.xml:
--------------------------------
<?xml version='1.0'?>
<sales>
<division id='North'>
<revenue>10</revenue>
<growth>9</growth>
<bonus>7</bonus>
</division>
<division id='South'>
<revenue>4</revenue>
<growth>3</growth>
<bonus>4</bonus>
</division>
<division id='West'>
<revenue>6</revenue>
<growth>-1.5</growth>
<bonus>2</bonus>
</division>
</sales>
--------------------------------
Perf.xsl:
--------------------------------
Note that the <asp:xml> server control has four properties: DocumentSource (filepath to XML
data file), TransformSource (filepath to XSL/T transform file), Document (reference to an
XmlDocument object), and Transform (reference to an XslTransform object). You can
programmatically manipulate any of them by giving the control an "id" (just like any other server
control).
Note also that if you want you can optionally obtain the XML document from a database (any
database -- SQL or otherwise). This is done by creating an XmlDataDocument out of a populated
dataset. The below sample demonstrates how to easily do this. It also illustrates the use of the <
%@ Page ContentType="whatever" %> directive that is new to ASP.NET -- and enables you to
easily and declaratively control the HTTP content type that ASP.NET sends back to a client
during the request.
-------------------------------------
Return dataset
End Function
MyXml1.Document = XmlDoc
End Sub
</script>
-------------------------------------
GENERAL
Question: Why won't ASP.Net cookie authentication redirect to a logon page specified by a
relative path?
Answer: This is a known issue with Beta 1. To work around this you should use a fully qualified
path to the logon page. ('/logon.aspx' instead of 'logon.aspx')
Question: Why do I get a JavaScript error when I try to use paging on a DataGrid control?
Answer: The DataGrid control needs to be rendered inside of a server-side form so it knows to
generate the required JavaScript.
Question: I have a .Net DLL loaded into \myweb\bin\ but the namespace isn't getting registered.
What could be the problem?
Answer: Make sure that \myweb\ is defined as a separate IIS 'application'. By default the .Net
framework looks for DLLs in the web root, so defining this sub-folder as it's own web (application)
should correct the error.
When the "type" declaration is not added, the VB.NET compiler will automatically declare it as
type "Object". This is roughly analogous to a Variant in VBScript -- meaning any type can be
assigned to it. Note that all of the generic .NET Dictionaries, arrays, collections, etc. accept data
types of type Object -- meaning you can put anything into them.
Then, you'll need to have the VSSafe client installed on your client machine. Since File Share
access doesn't rely on FrontPage, you don't have to get source control installed on your web
server.
Then, all you need to do is choose File->Source Control->Add Solution to source control. You
then check in and out through the IDE, and use 'Get latest version' to get new changes others
have checked in.
Each new member who joins the team simply does File->Open from source control, choosing the
same solution file. They will be prompted to choose a location for their private copy of the web
projects (The Set Project Location dialog). They will be able to check in, out and get just as each
other team member can.
Note that, in beta1, there are issues with Web References to other projects. If you plan to use
these, you should be sure to use http://localhost in the Set Project Location dialog.
If you use SQLDataReader or the SQLCommand object directly, however, then you do need to
manually close it once you are done.
The general rule to remember: if you explicitly open a connection (by calling an Open() method),
then you probably need to explicitly close it. If you didn't have to explicitly open a connection (like
in the DataSet case), then you probably don't need to explicitly close it.
Question: How can I read cookies from multiple folders under my site?
Answer: By default an Http Cookie is set to associate itself only to the current request path of the
activating page. If you want the cookie to apply to a wider URL path, you should set the "Path"
property appropriately.
The above code will cause the "name" value to apply to everything below the root of the site.
Each simply allows you to reference the namespaces you're planning to use so that you can refer
to their members without prefixing the member names with the full namespace.
Question: I'm tring to customize a page I created in VS.Net but for reason the Page_Load event
will not fire to execute my code.
Answer: Visual Studio .Net adds a Page directive of AutoEventWireup="false", which prevents the
Page_Load event from firing. You can remove this option but it may break the code that VS.Net
created.
Question: What is a good regular expression that can be used to validate an email address?
Answer: ^[\w\.\-_]+@([\w\.\-_]+\.)+[A-Za-z]{2,4}$
Question: Is it true that you can only have one form per ASP.Net page?
Answer: You can have multiple forms, but only one form can be set with the runat="server"
attribute.
Question: Is there a way to set Option Explicit and Option Strict in an ASP.Net page without using
a code-behind file?
Answer: Yes, you can use:
End Class
Question: I get an 'Type does not exist' error when trying to use a simple custom control.
Answer: Make sure the DLL is located in the \bin\ folder directly under the web root.
Also make sure you have pre-compiled the control into a DLL before trying to use it.
Note that all querystring variables need to be exactly the same as a previous request for a
cached copy to be used.
This is very useful for increasing performance on pages where the underlying data doesn't
change very often.
<asp:DataGrid ...>
<property name="Columns">
<asp:hyperlink runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "msg_id") %>'
NavigateUrl='<%# "editmessage.aspx?id=" +
DataBinder.Eval(Container.DataItem,"msg_id") + "&cid=" +
DataBinder.Eval(Container.DataItem,"c_id") %>'
Target="_new" />
</property>
</asp:DataGrid>
Question: How do I get a DropDownList that is databound to have a blank first entry?
Answer: You can use the Insert() method of the Dropdownlist's Items collection to
programmatically insert a new list item at the top of the list. But you'll need to do this after the list
is databound, for example, in the list's
PreRender event:
Assuming each row in the DataSource for your outer DataList contains
a field/column called "Topics" which can be used as a data source, i.e.,
it implements at least IEnumerable, this will get you the desired result.
<html>
<head>
<script runat="server" language="VB">
Public Sub Page_Load(Source As Object, E As EventArgs)
Dim myUserControl As UserControl = LoadControl("myControl.ascx")
' Page.Controls(2) is the Form
' Controls.AddAt is used to "insert" the control
' Controls.Add can also be used to append the user control to the end of the collection
Page.Controls(2).Controls.AddAt(0, myUserControl)
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<asp:Label runat="server">
This is the first control in the Form's Controls collection.
The user control will be dynamically loaded before this control.
</asp:Label>
</form>
</body>
</html>
You may also want to change the cache size through the registry as listed in this article:
http://www.gotdotnet.com/journal/1129.aspx
ds.Tables["Files"].Rows[0]["FileType"].ToString()
Response.Write("Yo"); // OK
Functional Use beginning and ending Use braces to declare functional blocks of code:
blocks statements to declare void Show(string strX)
functional blocks of code:
Sub Show(strX as String) {
Response.Write(strX) Response.Write(strX);
End Sub }
Type Implicit type conversions are Implicit type conversions are limited to operations
conversion permitted by default: that are guaranteed not to lose information, such as
Dim X As Integer converting from int to float:
int X = 0;
X = 3.14 ’ OK
You can limit conversions by float Y = X; // OK
including an Option Strict On Other type conversions are performed explicitly by
statement at the beginning of casts:
modules. Y = 3.14F;
Z = Y.ToString();
Comments Comments always start with There are three different types of comments: block
an apostrophe (‘): (/* */), inline (//), and documentation (///):
‘ This is a comment. /* Block comments can
/// <summary>Description
/// of class.</summary>
For more information about documentation
comments, see the "XML Documentation" topic
in the Visual Studio online Help.
Arrays Array elements are specified Array elements are specified using square brackets:
using arrFruit[1] = "Apple";
parentheses:
arrFruit(1) = "Apple"
Methods You can omit parentheses You must include parentheses after all methods:
after method names if strX = objX.ToString();
arguments are omitted:
strX = objX.ToString
Statement Statements are terminated by Statements are terminated by the semicolon (;):
termination carriage return: Response.Write("Hello");
Response.Write("Hello")
Statement Statements are continued Statements continue until the semicolon (;) and can
continuation using the underscore (_): span multiple lines if needed:
intX = System.Math.PI * _ intX = System.Math.PI *
intRadius intRadius;
String Use the ampersand (&) or Use the plus sign (+) to join strings:
operator plus sign (+) to join strings: strFruit = "Apples" +
strFruit = "Apples" & _
" Oranges";
" Oranges"
Comparison Use =, >, <, >=, <=, <> to Use ==, >, <, >=, <=, != to compare values:
operators compare values: if (intX >= 5)
If intX >= 5 Then
Negation Use the Not keyword to Use the ! operator to express logical negation:
express logical negation: if (!IsPostBack)
If Not IsPostBack Then
Object Use the Is keyword to Use == to compare object variables:
comparison compare object variables: if (objX == objY)
If objX Is objY Then
Object Use the Nothing keyword or Use the null keyword to check whether an object
existence the IsNothing function to exists:
check whether an object if (objX == null)
exists:
If IsNothing(objX) Then